title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C program to count zeros and ones in binary representation of a number - GeeksforGeeks
05 Aug, 2021 Given a number N, the task is to write C program to count the number of 0s and 1s in the binary representation of N. Examples: Input: N = 5 Output: Count of 0s: 1 Count of 1s: 2 Explanation: Binary representation of 5 is “101”.Input: N = 22 Output: Count of 0s: 2 Count of 1s: 3 Explanation: Binary representation of 22 is “10110”. Method 1 – Naive Approach: The idea is to iterate through all bits in the binary representation of N and increment the count of 0s if current bit is ‘0’ else increment the count of 1s. Below is the implementation of the above approach: C // C program for the above approach#include <stdio.h> // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise count variables int count0 = 0, count1 = 0; // Iterate through all the bits while (N > 0) { // If current bit is 1 if (N & 1) { count1++; } // If current bit is 0 else { count0++; } N = N >> 1; } // Print the count printf("Count of 0s in N is %d\n", count0); printf("Count of 1s in N is %d\n", count1);} // Driver Codeint main(){ // Given Number int N = 9; // Function Call count1s0s(N); return 0;} Count of 0s in N is 2 Count of 1s in N is 2 Time Complexity: O(log N) Method 2 – Recursive Approach: The above approach can also be implemented using Recursion. Below is the implementation of the above approach: C // C program for the above approach#include <math.h>#include <stdio.h> // Recursive approach to find the// number of set bit in 1int recursiveCount(int N){ // Base Case if (N == 0) { return 0; } // Return recursively return (N & 1) + recursiveCount(N >> 1);} // Function to find 1s complementint onesComplement(int n){ // Find number of bits in the // given integer int N = floor(log2(n)) + 1; // XOR the given integer with // pow(2, N) - 1 return ((1 << N) - 1) ^ n;} // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise the count variables int count0, count1; // Function call to find the number // of set bits in N count1 = recursiveCount(N); // Function call to find 1s complement N = onesComplement(N); // Function call to find the number // of set bits in 1s complement of N count0 = recursiveCount(N); // Print the count printf("Count of 0s in N is %d\n", count0); printf("Count of 1s in N is %d\n", count1);} // Driver Codeint main(){ // Given Number int N = 5; // Function Call count1s0s(N); return 0;} Count of 0s in N is 1 Count of 1s in N is 2 Time Complexity: O(log N) Method 3 – Using Brian Kernighan’s Algorithm We can find the count of set bits using the steps below: Initialise count to 0. If N > 0, then update N as N & (N – 1) as this will unset the most set bit from the right as shown below: if N = 10; Binary representation of N = 1010 Binary representation of N - 1 = 1001 ------------------------------------- Logical AND of N and N - 1 = 1000 Increment the count for the above steps and repeat the above steps until N becomes 0. To find the count of 0s in the binary representation of N, find the one’s complement of N and find the count of set bits using the approach discussed above. Below is the implementation of the above approach: C // C program for the above approach#include <math.h>#include <stdio.h> // Function to find 1s complementint onesComplement(int n){ // Find number of bits in the // given integer int N = floor(log2(n)) + 1; // XOR the given integer with // pow(2, N) - 1 return ((1 << N) - 1) ^ n;} // Function to implement count of// set bits using Brian Kernighan’s// Algorithmint countSetBits(int n){ // Initialise count int count = 0; // Iterate until n is 0 while (n) { n &= (n - 1); count++; } // Return the final count return count;} // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise the count variables int count0, count1; // Function call to find the number // of set bits in N count1 = countSetBits(N); // Function call to find 1s complement N = onesComplement(N); // Function call to find the number // of set bits in 1s complement of N count0 = countSetBits(N); // Print the count printf("Count of 0s in N is %d\n", count0); printf("Count of 1s in N is %d\n", count1);} // Driver Codeint main(){ // Given Number int N = 5; // Function Call count1s0s(N); return 0;} Count of 0s in N is 1 Count of 1s in N is 2 Time Complexity: O(log N) kartikey134 gabaa406 base-conversion binary-representation setBitCount Bit Magic C Programs School Programming Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File Basics of File Handling in C
[ { "code": null, "e": 26713, "s": 26685, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26830, "s": 26713, "text": "Given a number N, the task is to write C program to count the number of 0s and 1s in the binary representation of N." }, { "code": null, "e": 26842, "s": 26830, "text": "Examples: " }, { "code": null, "e": 27048, "s": 26842, "text": "Input: N = 5 Output: Count of 0s: 1 Count of 1s: 2 Explanation: Binary representation of 5 is “101”.Input: N = 22 Output: Count of 0s: 2 Count of 1s: 3 Explanation: Binary representation of 22 is “10110”. " }, { "code": null, "e": 27233, "s": 27048, "text": "Method 1 – Naive Approach: The idea is to iterate through all bits in the binary representation of N and increment the count of 0s if current bit is ‘0’ else increment the count of 1s." }, { "code": null, "e": 27284, "s": 27233, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27286, "s": 27284, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h> // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise count variables int count0 = 0, count1 = 0; // Iterate through all the bits while (N > 0) { // If current bit is 1 if (N & 1) { count1++; } // If current bit is 0 else { count0++; } N = N >> 1; } // Print the count printf(\"Count of 0s in N is %d\\n\", count0); printf(\"Count of 1s in N is %d\\n\", count1);} // Driver Codeint main(){ // Given Number int N = 9; // Function Call count1s0s(N); return 0;}", "e": 27968, "s": 27286, "text": null }, { "code": null, "e": 28012, "s": 27968, "text": "Count of 0s in N is 2\nCount of 1s in N is 2" }, { "code": null, "e": 28038, "s": 28012, "text": "Time Complexity: O(log N)" }, { "code": null, "e": 28130, "s": 28038, "text": "Method 2 – Recursive Approach: The above approach can also be implemented using Recursion. " }, { "code": null, "e": 28181, "s": 28130, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28183, "s": 28181, "text": "C" }, { "code": "// C program for the above approach#include <math.h>#include <stdio.h> // Recursive approach to find the// number of set bit in 1int recursiveCount(int N){ // Base Case if (N == 0) { return 0; } // Return recursively return (N & 1) + recursiveCount(N >> 1);} // Function to find 1s complementint onesComplement(int n){ // Find number of bits in the // given integer int N = floor(log2(n)) + 1; // XOR the given integer with // pow(2, N) - 1 return ((1 << N) - 1) ^ n;} // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise the count variables int count0, count1; // Function call to find the number // of set bits in N count1 = recursiveCount(N); // Function call to find 1s complement N = onesComplement(N); // Function call to find the number // of set bits in 1s complement of N count0 = recursiveCount(N); // Print the count printf(\"Count of 0s in N is %d\\n\", count0); printf(\"Count of 1s in N is %d\\n\", count1);} // Driver Codeint main(){ // Given Number int N = 5; // Function Call count1s0s(N); return 0;}", "e": 29357, "s": 28183, "text": null }, { "code": null, "e": 29401, "s": 29357, "text": "Count of 0s in N is 1\nCount of 1s in N is 2" }, { "code": null, "e": 29427, "s": 29401, "text": "Time Complexity: O(log N)" }, { "code": null, "e": 29530, "s": 29427, "text": "Method 3 – Using Brian Kernighan’s Algorithm We can find the count of set bits using the steps below: " }, { "code": null, "e": 29553, "s": 29530, "text": "Initialise count to 0." }, { "code": null, "e": 29659, "s": 29553, "text": "If N > 0, then update N as N & (N – 1) as this will unset the most set bit from the right as shown below:" }, { "code": null, "e": 29822, "s": 29659, "text": "if N = 10;\nBinary representation of N = 1010\nBinary representation of N - 1 = 1001\n-------------------------------------\nLogical AND of N and N - 1 = 1000" }, { "code": null, "e": 29908, "s": 29822, "text": "Increment the count for the above steps and repeat the above steps until N becomes 0." }, { "code": null, "e": 30065, "s": 29908, "text": "To find the count of 0s in the binary representation of N, find the one’s complement of N and find the count of set bits using the approach discussed above." }, { "code": null, "e": 30117, "s": 30065, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30119, "s": 30117, "text": "C" }, { "code": "// C program for the above approach#include <math.h>#include <stdio.h> // Function to find 1s complementint onesComplement(int n){ // Find number of bits in the // given integer int N = floor(log2(n)) + 1; // XOR the given integer with // pow(2, N) - 1 return ((1 << N) - 1) ^ n;} // Function to implement count of// set bits using Brian Kernighan’s// Algorithmint countSetBits(int n){ // Initialise count int count = 0; // Iterate until n is 0 while (n) { n &= (n - 1); count++; } // Return the final count return count;} // Function to count the number of 0s// and 1s in binary representation of Nvoid count1s0s(int N){ // Initialise the count variables int count0, count1; // Function call to find the number // of set bits in N count1 = countSetBits(N); // Function call to find 1s complement N = onesComplement(N); // Function call to find the number // of set bits in 1s complement of N count0 = countSetBits(N); // Print the count printf(\"Count of 0s in N is %d\\n\", count0); printf(\"Count of 1s in N is %d\\n\", count1);} // Driver Codeint main(){ // Given Number int N = 5; // Function Call count1s0s(N); return 0;}", "e": 31356, "s": 30119, "text": null }, { "code": null, "e": 31400, "s": 31356, "text": "Count of 0s in N is 1\nCount of 1s in N is 2" }, { "code": null, "e": 31426, "s": 31400, "text": "Time Complexity: O(log N)" }, { "code": null, "e": 31438, "s": 31426, "text": "kartikey134" }, { "code": null, "e": 31447, "s": 31438, "text": "gabaa406" }, { "code": null, "e": 31463, "s": 31447, "text": "base-conversion" }, { "code": null, "e": 31485, "s": 31463, "text": "binary-representation" }, { "code": null, "e": 31497, "s": 31485, "text": "setBitCount" }, { "code": null, "e": 31507, "s": 31497, "text": "Bit Magic" }, { "code": null, "e": 31518, "s": 31507, "text": "C Programs" }, { "code": null, "e": 31537, "s": 31518, "text": "School Programming" }, { "code": null, "e": 31547, "s": 31537, "text": "Bit Magic" }, { "code": null, "e": 31645, "s": 31547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31691, "s": 31645, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 31742, "s": 31691, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31793, "s": 31742, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31836, "s": 31793, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 31852, "s": 31836, "text": "Bit Fields in C" }, { "code": null, "e": 31865, "s": 31852, "text": "Strings in C" }, { "code": null, "e": 31906, "s": 31865, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31941, "s": 31906, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31982, "s": 31941, "text": "C Program to read contents of Whole File" } ]
Python | Boolean List AND and OR operations - GeeksforGeeks
29 Oct, 2019 Sometimes, while working with Python list, we can have a problem in which we have a Boolean list and we need to find Boolean AND or OR of all elements in it. This kind of problem has application in Data Science domain. Let’s discuss an easy way to solve both these tasks. Method #1 : AND operation – Using all()The solution to this problem is quite straight forward, but application awareness is required. The all() performs the Boolean AND of the list and returns the result. # Python3 code to demonstrate working of# Boolean List AND and OR operations# AND Operation - Using all() # initialize listtest_list = [True, True, False, True, False] # printing original listprint("The original list is : " + str(test_list)) # Boolean List AND and OR operations# AND Operation - Using all()res = all(test_list) # printing resultprint("Result after performing AND among elements : " + str(res)) The original list is : [True, True, False, True, False] Result after performing AND among elements : False Method #2 : OR operation – Using any()This task can be performed using any(). This checks for any True element in list and returns True in that case else returns a False. # Python3 code to demonstrate working of# Boolean List AND and OR operations# OR operation - Using any() # initialize listtest_list = [True, True, False, True, False] # printing original listprint("The original list is : " + str(test_list)) # Boolean List AND and OR operations# OR operation - Using any()res = any(test_list) # printing resultprint("Result after performing OR among elements : " + str(res)) The original list is : [True, True, False, True, False] Result after performing OR among elements : True Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25763, "s": 25735, "text": "\n29 Oct, 2019" }, { "code": null, "e": 26035, "s": 25763, "text": "Sometimes, while working with Python list, we can have a problem in which we have a Boolean list and we need to find Boolean AND or OR of all elements in it. This kind of problem has application in Data Science domain. Let’s discuss an easy way to solve both these tasks." }, { "code": null, "e": 26240, "s": 26035, "text": "Method #1 : AND operation – Using all()The solution to this problem is quite straight forward, but application awareness is required. The all() performs the Boolean AND of the list and returns the result." }, { "code": "# Python3 code to demonstrate working of# Boolean List AND and OR operations# AND Operation - Using all() # initialize listtest_list = [True, True, False, True, False] # printing original listprint(\"The original list is : \" + str(test_list)) # Boolean List AND and OR operations# AND Operation - Using all()res = all(test_list) # printing resultprint(\"Result after performing AND among elements : \" + str(res))", "e": 26655, "s": 26240, "text": null }, { "code": null, "e": 26763, "s": 26655, "text": "The original list is : [True, True, False, True, False]\nResult after performing AND among elements : False\n" }, { "code": null, "e": 26936, "s": 26765, "text": "Method #2 : OR operation – Using any()This task can be performed using any(). This checks for any True element in list and returns True in that case else returns a False." }, { "code": "# Python3 code to demonstrate working of# Boolean List AND and OR operations# OR operation - Using any() # initialize listtest_list = [True, True, False, True, False] # printing original listprint(\"The original list is : \" + str(test_list)) # Boolean List AND and OR operations# OR operation - Using any()res = any(test_list) # printing resultprint(\"Result after performing OR among elements : \" + str(res))", "e": 27348, "s": 26936, "text": null }, { "code": null, "e": 27454, "s": 27348, "text": "The original list is : [True, True, False, True, False]\nResult after performing OR among elements : True\n" }, { "code": null, "e": 27475, "s": 27454, "text": "Python list-programs" }, { "code": null, "e": 27482, "s": 27475, "text": "Python" }, { "code": null, "e": 27498, "s": 27482, "text": "Python Programs" }, { "code": null, "e": 27596, "s": 27498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27631, "s": 27596, "text": "Read a file line by line in Python" }, { "code": null, "e": 27663, "s": 27631, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27685, "s": 27663, "text": "Enumerate() in Python" }, { "code": null, "e": 27727, "s": 27685, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27757, "s": 27727, "text": "Iterate over a list in Python" }, { "code": null, "e": 27800, "s": 27757, "text": "Python program to convert a list to string" }, { "code": null, "e": 27822, "s": 27800, "text": "Defaultdict in Python" }, { "code": null, "e": 27861, "s": 27822, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27907, "s": 27861, "text": "Python | Split string into list of characters" } ]
How to predict Loan Eligibility using Machine Learning Models | by Mridul Bhandari | Towards Data Science
Loans are the core business of banks. The main profit comes directly from the loan’s interest. The loan companies grant a loan after an intensive process of verification and validation. However, they still don’t have assurance if the applicant is able to repay the loan with no difficulties. In this tutorial, we’ll build a predictive model to predict if an applicant is able to repay the lending company or not. We will prepare the data using Jupyter Notebook and use various models to predict the target variable. github.com Sign-up for an IBM Cloud account to try this tutorial - ibm.biz Getting the system ready and loading the dataUnderstanding the dataExploratory Data Analysis (EDA)i. Univariate Analysisii. Bivariate AnalysisMissing value and outlier treatmentEvaluation Metrics for classification problemsModel Building: Part 1Logistic Regression using stratified k-folds cross-validationFeature EngineeringModel Building: Part 2i. Logistic Regressionii. Decision Treeiii. Random Forestiv. XGBoost Getting the system ready and loading the data Understanding the data Exploratory Data Analysis (EDA)i. Univariate Analysisii. Bivariate Analysis Missing value and outlier treatment Evaluation Metrics for classification problems Model Building: Part 1 Logistic Regression using stratified k-folds cross-validation Feature Engineering Model Building: Part 2i. Logistic Regressionii. Decision Treeiii. Random Forestiv. XGBoost We will be using Python for this course along with the below-listed libraries. Specifications Python pandas seaborn sklearn import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings(“ignore”) For this problem, we have three CSV files: train, test, and sample submission. Train file will be used for training the model, i.e. our model will learn from this file. It contains all the independent variables and the target variable. Test file contains all the independent variables, but not the target variable. We will apply the model to predict the target variable for the test data. Sample submission file contains the format in which we have to submit out predictions train = pd.read_csv(‘Dataset/train.csv’)train.head() test = pd.read_csv(‘Dataset/test.csv’)test.head() Let’s make a copy of the train and test data so that even if we have to make any changes in these datasets we would not lose the original datasets. train_original=train.copy()test_original=test.copy() train.columnsIndex(['Loan_ID', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed', 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term', 'Credit_History', 'Property_Area', 'Loan_Status'], dtype='object') We have 12 independent variables and 1 target variable, i.e. Loan_Status in the training dataset. test.columnsIndex(['Loan_ID', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed', 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term', 'Credit_History', 'Property_Area'], dtype='object') We have similar features in the test dataset as the training dataset except for the Loan_Status. We will predict the Loan_Status using the model built using the train data. train.dtypesLoan_ID objectGender objectMarried objectDependents objectEducation objectSelf_Employed objectApplicantIncome int64CoapplicantIncome float64LoanAmount float64Loan_Amount_Term float64Credit_History float64Property_Area objectLoan_Status objectdtype: object We can see there are three formats of data types: object: Object format means variables are categorical. Categorical variables in our dataset are Loan_ID, Gender, Married, Dependents, Education, Self_Employed, Property_Area, Loan_Status. int64: It represents the integer variables. ApplicantIncome is of this format. float64: It represents the variable that has some decimal values involved. They are also numerical train.shape(614, 13) We have 614 rows and 13 columns in the train dataset. test.shape(367, 12) We have 367 rows and 12 columns in test dataset. train[‘Loan_Status’].value_counts()Y 422N 192Name: Loan_Status, dtype: int64 Normalize can be set to True to print proportions instead of number train[‘Loan_Status’].value_counts(normalize=True) Y 0.687296N 0.312704Name: Loan_Status, dtype: float64train[‘Loan_Status’].value_counts().plot.bar() The loan of 422(around 69%) people out of 614 were approved. Now, let's visualize each variable separately. Different types of variables are Categorical, ordinal, and numerical. Categorical features: These features have categories (Gender, Married, Self_Employed, Credit_History, Loan_Status) Ordinal features: Variables in categorical features having some order involved (Dependents, Education, Property_Area) Numerical features: These features have numerical values (ApplicantIncome, Co-applicantIncome, LoanAmount, Loan_Amount_Term) train[‘Gender’].value_counts(normalize=True).plot.bar(figsize=(20,10), title=’Gender’)plt.show()train[‘Married’].value_counts(normalize=True).plot.bar(title=’Married’)plt.show()train[‘Self_Employed’].value_counts(normalize=True).plot.bar(title=’Self_Employed’)plt.show()train[‘Credit_History’].value_counts(normalize=True).plot.bar(title=’Credit_History’)plt.show() It can be inferred from the above bar plots that: 80% of applicants in the dataset are male. Around 65% of the applicants in the dataset are married. Around 15% of applicants in the dataset are self-employed. Around 85% of applicants have repaid their doubts. train[‘Dependents’].value_counts(normalize=True).plot.bar(figsize=(24,6), title=’Dependents’)plt.show()train[‘Education’].value_counts(normalize=True).plot.bar(title=’Education’)plt.show()train[‘Property_Area’].value_counts(normalize=True).plot.bar(title=’Property_Area’)plt.show() The following inferences can be made from the above bar plots: Most of the applicants don't have any dependents. Around 80% of the applicants are Graduate. Most of the applicants are from the Semiurban area. Till now we have seen the categorical and ordinal variables and now let's visualize the numerical variables. Let's look at the distribution of Applicant income first. sns.distplot(train[‘ApplicantIncome’])plt.show()train[‘ApplicantIncome’].plot.box(figsize=(16,5))plt.show() It can be inferred that most of the data in the distribution of applicant income are towards the left which means it is not normally distributed. We will try to make it normal in later sections as algorithms work better if the data is normally distributed. The boxplot confirms the presence of a lot of outliers/extreme values. This can be attributed to the income disparity in the society. Part of this can be driven by the fact that we are looking at people with different education levels. Let us segregate them by Education. train.boxplot(column=’ApplicantIncome’, by = ‘Education’) plt.suptitle(“”) We can see that there are a higher number of graduates with very high incomes, which are appearing to be outliers. Let’s look at the Co-applicant income distribution. sns.distplot(train[‘CoapplicantIncome’])plt.show()train[‘CoapplicantIncome’].plot.box(figsize=(16,5))plt.show() We see a similar distribution as that of the applicant's income. The majority of co-applicants income ranges from 0 to 5000. We also see a lot of outliers in the applicant's income and it is not normally distributed. train.notna()sns.distplot(train[‘LoanAmount’])plt.show()train[‘LoanAmount’].plot.box(figsize=(16,5))plt.show() We see a lot of outliers in this variable and the distribution is fairly normal. We will treat the outliers in later sections. Let’s recall some of the hypotheses that we generated earlier: Applicants with high incomes should have more chances of loan approval. Applicants who have repaid their previous debts should have higher chances of loan approval. Loan approval should also depend on the loan amount. If the loan amount is less, the chances of loan approval should be high. Lesser the amount to be paid monthly to repay the loan, the higher the chances of loan approval. Let’s try to test the above-mentioned hypotheses using bivariate analysis. After looking at every variable individually in univariate analysis, we will now explore them again with respect to the target variable. First of all, we will find the relation between the target variable and categorical independent variables. Let us look at the stacked bar plot now which will give us the proportion of approved and unapproved loans. Gender=pd.crosstab(train[‘Gender’],train[‘Loan_Status’])Gender.div(Gender.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show() It can be inferred that the proportion of male and female applicants is more or less the same for both approved and unapproved loans. Now let us visualize the remaining categorical variables vs target variable. Married=pd.crosstab(train[‘Married’],train[‘Loan_Status’])Dependents=pd.crosstab(train[‘Dependents’],train[‘Loan_Status’])Education=pd.crosstab(train[‘Education’],train[‘Loan_Status’])Self_Employed=pd.crosstab(train[‘Self_Employed’],train[‘Loan_Status’])Married.div(Married.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Dependents.div(Dependents.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Education.div(Education.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Self_Employed.div(Self_Employed.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show() The proportion of married applicants is higher for approved loans. Distribution of applicants with 1 or 3+ dependents is similar across both the categories of Loan_Status. There is nothing significant we can infer from Self_Employed vs Loan_Status plot. Now we will look at the relationship between remaining categorical independent variables and Loan_Status. Credit_History=pd.crosstab(train[‘Credit_History’],train[‘Loan_Status’])Property_Area=pd.crosstab(train[‘Property_Area’],train[‘Loan_Status’])Credit_History.div(Credit_History.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Property_Area.div(Property_Area.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.show() It seems people with a credit history as 1 are more likely to get their loans approved. The proportion of loans getting approved in the semi-urban area is higher as compared to that in rural or urban areas. Now let’s visualize numerical independent variables with respect to the target variable. We will try to find the mean income of people for which the loan has been approved vs the mean income of people for which the loan has not been approved. train.groupby(‘Loan_Status’)[‘ApplicantIncome’].mean().plot.bar() Here the y-axis represents the mean applicant income. We don’t see any change in the mean income. So, let’s make bins for the applicant income variable based on the values in it and analyze the corresponding loan status for each bin. bins=[0,2500,4000,6000,81000]group=[‘Low’,’Average’,’High’,’Very high’]train[‘Income_bin’]=pd.cut(train[‘ApplicantIncome’],bins,labels=group)Income_bin=pd.crosstab(train[‘Income_bin’],train[‘Loan_Status’])Income_bin.div(Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘ApplicantIncome’)P=plt.ylabel(‘Percentage’) It can be inferred that Applicant's income does not affect the chances of loan approval which contradicts our hypothesis in which we assumed that if the applicant's income is high the chances of loan approval will also be high. We will analyze the co-applicant income and loan amount variable in a similar manner. bins=[0,1000,3000,42000]group=[‘Low’,’Average’,’High’]train[‘Coapplicant_Income_bin’]=pd.cut(train[‘CoapplicantIncome’],bins,labels=group)Coapplicant_Income_bin=pd.crosstab(train[‘Coapplicant_Income_bin’],train[‘Loan_Status’])Coapplicant_Income_bin.div(Coapplicant_Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘CoapplicantIncome’)P=plt.ylabel(‘Percentage’) It shows that if co-applicants income is less the chances of loan approval are high. But this does not look right. The possible reason behind this may be that most of the applicants don’t have any co-applicant so the co-applicant income for such applicants is 0 and hence the loan approval is not dependent on it. So, we can make a new variable in which we will combine the applicant’s and co-applicants income to visualize the combined effect of income on loan approval. Let us combine the Applicant Income and Co-applicant Income and see the combined effect of Total Income on the Loan_Status. train[‘Total_Income’]=train[‘ApplicantIncome’]+train[‘CoapplicantIncome’]bins=[0,2500,4000,6000,81000]group=[‘Low’,’Average’,’High’,’Very high’]train[‘Total_Income_bin’]=pd.cut(train[‘Total_Income’],bins,labels=group)Total_Income_bin=pd.crosstab(train[‘Total_Income_bin’],train[‘Loan_Status’])Total_Income_bin.div(Total_Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘Total_Income’)P=plt.ylabel(‘Percentage’) We can see that Proportion of loans getting approved for applicants having low Total_Income is very less compared to that of applicants with Average, High & Very High Income. Let’s visualize the Loan Amount variable. bins=[0,100,200,700]group=[‘Low’,’Average’,’High’]train[‘LoanAmount_bin’]=pd.cut(train[‘LoanAmount’],bins,labels=group)LoanAmount_bin=pd.crosstab(train[‘LoanAmount_bin’],train[‘Loan_Status’])LoanAmount_bin.div(LoanAmount_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘LoanAmount’)P=plt.ylabel(‘Percentage’) It can be seen that the proportion of approved loans is higher for Low and Average Loan Amount as compared to that of High Loan Amount which supports our hypothesis in which we considered that the chances of loan approval will be high when the loan amount is less. Let’s drop the bins which we created for the exploration part. We will change the 3+ in dependents variable to 3 to make it a numerical variable. We will also convert the target variable’s categories into 0 and 1 so that we can find its correlation with numerical variables. One more reason to do so is few models like logistic regression takes only numeric values as input. We will replace N with 0 and Y with 1. train=train.drop([‘Income_bin’, ‘Coapplicant_Income_bin’, ‘LoanAmount_bin’, ‘Total_Income_bin’, ‘Total_Income’], axis=1)train[‘Dependents’].replace(‘3+’, 3,inplace=True)test[‘Dependents’].replace(‘3+’, 3,inplace=True)train[‘Loan_Status’].replace(’N’, 0,inplace=True)train[‘Loan_Status’].replace(‘Y’, 1,inplace=True) Now let’s look at the correlation between all the numerical variables. We will use the heat map to visualize the correlation. Heatmaps visualize data through variations in coloring. The variables with darker color means their correlation is more. matrix = train.corr()f, ax = plt.subplots(figsize=(9,6))sns.heatmap(matrix,vmax=.8,square=True,cmap=”BuPu”, annot = True) We see that the most correlate variables are (ApplicantIncome — LoanAmount) and (Credit_History — Loan_Status). LoanAmount is also correlated with CoapplicantIncome. Let’s list out feature-wise count of missing values. train.isnull().sum()Loan_ID 0Gender 13Married 3Dependents 15Education 0Self_Employed 32ApplicantIncome 0CoapplicantIncome 0LoanAmount 22Loan_Amount_Term 14Credit_History 50Property_Area 0Loan_Status 0dtype: int64 There are missing values in Gender, Married, Dependents, Self_Employed, LoanAmount, Loan_Amount_Term, and Credit_History features. We will treat the missing values in all the features one by one. We can consider these methods to fill the missing values: For numerical variables: imputation using mean or median For categorical variables: imputation using mode There are very few missing values in Gender, Married, Dependents, Credit_History, and Self_Employed features so we can fill them using the mode of the features. train[‘Gender’].fillna(train[‘Gender’].mode()[0], inplace=True)train[‘Married’].fillna(train[‘Married’].mode()[0], inplace=True)train[‘Dependents’].fillna(train[‘Dependents’].mode()[0], inplace=True)train[‘Self_Employed’].fillna(train[‘Self_Employed’].mode()[0], inplace=True)train[‘Credit_History’].fillna(train[‘Credit_History’].mode()[0], inplace=True) Now let’s try to find a way to fill the missing values in Loan_Amount_Term. We will look at the value count of the Loan amount term variable. train[‘Loan_Amount_Term’].value_counts()360.0 512180.0 44480.0 15300.0 1384.0 4240.0 4120.0 336.0 260.0 212.0 1Name: Loan_Amount_Term, dtype: int64 It can be seen that in the loan amount term variable, the value of 360 is repeating the most. So we will replace the missing values in this variable using the mode of this variable. train[‘Loan_Amount_Term’].fillna(train[‘Loan_Amount_Term’].mode()[0], inplace=True) Now we will see the LoanAmount variable. As it is a numerical variable, we can use mean or median to impute the missing values. We will use the median to fill the null values as earlier we saw that the loan amount has outliers so the mean will not be the proper approach as it is highly affected by the presence of outliers. train[‘LoanAmount’].fillna(train[‘LoanAmount’].median(), inplace=True) Now let's check whether all the missing values are filled in the dataset. train.isnull().sum()Loan_ID 0Gender 0Married 0Dependents 0Education 0Self_Employed 0ApplicantIncome 0CoapplicantIncome 0LoanAmount 0Loan_Amount_Term 0Credit_History 0Property_Area 0Loan_Status 0dtype: int64 As we can see that all the missing values have been filled in the test dataset. Let’s fill all the missing values in the test dataset too with the same approach. test[‘Gender’].fillna(train[‘Gender’].mode()[0], inplace=True)test[‘Married’].fillna(train[‘Married’].mode()[0], inplace=True)test[‘Dependents’].fillna(train[‘Dependents’].mode()[0], inplace=True)test[‘Self_Employed’].fillna(train[‘Self_Employed’].mode()[0], inplace=True)test[‘Credit_History’].fillna(train[‘Credit_History’].mode()[0], inplace=True)test[‘Loan_Amount_Term’].fillna(train[‘Loan_Amount_Term’].mode()[0], inplace=True)test[‘LoanAmount’].fillna(train[‘LoanAmount’].median(), inplace=True) As we saw earlier in univariate analysis, LoanAmount contains outliers so we have to treat them as the presence of outliers affects the distribution of the data. Let’s examine what can happen to a data set with outliers. For the sample data set:1,1,2,2,2,2,3,3,3,4,4We find the following: mean, median, mode, and standard deviationMean = 2.58Median = 2.5Mode=2Standard Deviation = 1.08If we add an outlier to the data set:1,1,2,2,2,2,3,3,3,4,4,400The new values of our statistics are:Mean = 35.38Median = 2.5Mode=2Standard Deviation = 114.74It can be seen that having outliers often has a significant effect on the mean and standard deviation and hence affecting the distribution. We must take steps to remove outliers from our data sets.Due to these outliers bulk of the data in the loan amount is at the left and the right tail is longer. This is called right skewness. One way to remove the skewness is by doing the log transformation. As we take the log transformation, it does not affect the smaller values much but reduces the larger values. So, we get a distribution similar to normal distribution.Let’s visualize the effect of log transformation. We will do similar changes to the test file simultaneously. train[‘LoanAmount_log’]=np.log(train[‘LoanAmount’])train[‘LoanAmount_log’].hist(bins=20)test[‘LoanAmount_log’]=np.log(test[‘LoanAmount’]) Now the distribution looks much closer to normal and the effect of extreme values has been significantly subsided. Let’s build a logistic regression model and make predictions for the test dataset. Let us make our first model predict the target variable. We will start with Logistic Regression which is used for predicting binary outcome. Logistic Regression is a classification algorithm. It is used to predict a binary outcome (1 / 0, Yes / No, True / False) given a set of independent variables. Logistic regression is an estimation of Logit function. The logit function is simply a log of odds in favor of the event. This function creates an S-shaped curve with the probability estimate, which is very similar to the required stepwise function To learn further on logistic regression, refer to this article: https://www.analyticsvidhya.com/blog/2015/10/basics-logistic-regression/Let's drop the Loan_ID variable as it does not have any effect on the loan status. We will do the same changes to the test dataset which we did for the training dataset. train=train.drop(‘Loan_ID’,axis=1)test=test.drop(‘Loan_ID’,axis=1) We will use scikit-learn (sklearn) for making different models which is an open source library for Python. It is one of the most efcient tools which contains many inbuilt functions that can be used for modeling in Python. To learn further about sklearn, refer here: http://scikit-learn.org/stable/tutorial/index.html Sklearn requires the target variable in a separate dataset. So, we will drop our target variable from the training dataset and save it in another dataset. X = train.drop(‘Loan_Status’,1)y = train.Loan_Status Now we will make dummy variables for the categorical variables. The dummy variable turns categorical variables into a series of 0 and 1, making them a lot easier to quantify and compare. Let us understand the process of dummies first: Consider the “Gender” variable. It has two classes, Male and Female. As logistic regression takes only the numerical values as input, we have to change male and female into a numerical value. Once we apply dummies to this variable, it will convert the “Gender” variable into two variables(Gender_Male and Gender_Female), one for each class, i.e. Male and Female. Gender_Male will have a value of 0 if the gender is Female and a value of 1 if the gender is Male. X = pd.get_dummies(X)train=pd.get_dummies(train)test=pd.get_dummies(test) Now we will train the model on the training dataset and make predictions for the test dataset. But can we validate these predictions? One way of doing this is we can divide our train dataset into two parts: train and validation. We can train the model on this training part and using that make predictions for the validation part. In this way, we can validate our predictions as we have the true predictions for the validation part (which we do not have for the test dataset). We will use the train_test_split function from sklearn to divide our train dataset. So, first, let us import train_test_split. from sklearn.model_selection import train_test_splitx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size=0.3) The dataset has been divided into training and validation part. Let us import LogisticRegression and accuracy_score from sklearn and fit the logistic regression model. from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoremodel = LogisticRegression()model.fit(x_train, y_train)LogisticRegression() Here the C parameter represents the inverse of regularization strength. Regularization is applying a penalty to increasing the magnitude of parameter values in order to reduce overfitting. Smaller values of C specify stronger regularization. To learn about other parameters, refer here: http://scikit- learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html Let’s predict the Loan_Status for validation set and calculate its accuracy. pred_cv = model.predict(x_cv)accuracy_score(y_cv,pred_cv)0.7891891891891892 So our predictions are almost 80% accurate, i.e. we have identified 80% of the loan status correctly. Let’s make predictions for the test dataset. pred_test = model.predict(test) Let's import the submission file which we have to submit on the solution checker. submission = pd.read_csv(‘Dataset/sample_submission.csv’)submission.head() We only need the Loan_ID and the corresponding Loan_Status for the final submission. we will fill these columns with the Loan_ID of the test dataset and the predictions that we made, i.e., pred_test respectively. submission[‘Loan_Status’]=pred_testsubmission[‘Loan_ID’]=test_original[‘Loan_ID’] Remember we need predictions in Y and N. So let’s convert 1 and 0 to Y and N. submission[‘Loan_Status’].replace(0, ’N’, inplace=True)submission[‘Loan_Status’].replace(1, ‘Y’, inplace=True) Finally, we will convert the submission to .csv format. pd.DataFrame(submission, columns=[‘Loan_ID’,’Loan_Status’]).to_csv(‘Output/logistic.csv’) To check how robust our model is to unseen data, we can use Validation. It is a technique that involves reserving a particular sample of a dataset on which you do not train the model. Later, you test your model on this sample before finalizing it. Some of the common methods for validation are listed below: The validation set approach k-fold cross-validation Leave one out cross-validation (LOOCV) Stratified k-fold cross-validation If you wish to know more about validation techniques, then please refer to this article: https://www.analyticsvidhya.com/blog/2018/05/improve-model-performance-cross-validation-in-python-r/ In this section, we will learn about stratified k-fold cross-validation. Let us understand how it works: Stratification is the process of rearranging the data so as to ensure that each fold is a good representative of the whole. For example, in a binary classification problem where each class comprises of 50% of the data, it is best to arrange the data such that in every fold, each class comprises of about half the instances. It is generally a better approach when dealing with both bias and variance. A randomly selected fold might not adequately represent the minor class, particularly in cases where there is a huge class imbalance. Let’s import StratifiedKFold from sklearn and fit the model. from sklearn.model_selection import StratifiedKFold Now let’s make a cross-validation logistic model with stratified 5 folds and make predictions for the test dataset. i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1)for train_index,test_index in kf.split(X,y): print (‘\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = LogisticRegression(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.80487804878048792 of kfold 5 accuracy_score 0.76422764227642283 of kfold 5 accuracy_score 0.78048780487804884 of kfold 5 accuracy_score 0.84552845528455295 of kfold 5 accuracy_score 0.8032786885245902Mean Validation Accuracy 0.7996801279488205 The mean validation accuracy for this model turns out to be 0.80. Let us visualize the roc curve. from sklearn import metricsfpr, tpr, _ = metrics.roc_curve(yvl, pred)auc = metrics.roc_auc_score(yvl, pred)plt.figure(figsize=(12,8))plt.plot(fpr, tpr, label=”validation, auc=”+str(auc))plt.xlabel(‘False Positive Rate’)plt.ylabel(‘True Positive Rate’)plt.legend(loc=4)plt.show() We got an auc value of 0.70 submission[‘Loan_Status’]=pred_testsubmission[‘Loan_ID’]=test_original[‘Loan_ID’] Remember we need predictions in Y and N. So let’s convert 1 and 0 to Y and N. submission[‘Loan_Status’].replace(0, ’N’, inplace=True)submission[‘Loan_Status’].replace(1, ‘Y’, inplace=True)pd.DataFrame(submission, columns=[‘Loan_ID’,’Loan_Status’]).to_csv(‘Output/Log1.csv’) Based on the domain knowledge, we can come up with new features that might affect the target variable. We will create the following three new features: Total Income — As discussed during bivariate analysis we will combine the Applicant Income and Co-applicant Income. If the total income is high, the chances of loan approval might also be high. EMI — EMI is the monthly amount to be paid by the applicant to repay the loan. The idea behind making this variable is that people who have high EMI’s might find it difficult to pay back the loan. We can calculate the EMI by taking the ratio of the loan amount with respect to the loan amount term. Balance Income — This is the income left after the EMI has been paid. The idea behind creating this variable is that if this value is high, the chances are high that a person will repay the loan and hence increasing the chances of loan approval. train[‘Total_Income’]=train[‘ApplicantIncome’]+train[‘CoapplicantIncome’]test[‘Total_Income’]=test[‘ApplicantIncome’]+test[‘CoapplicantIncome’] Let’s check the distribution of Total Income. sns.distplot(train[‘Total_Income’]) We can see it is shifted towards left, i.e., the distribution is right-skewed. So, let’s take the log transformation to make the distribution normal. train[‘Total_Income_log’] = np.log(train[‘Total_Income’])sns.distplot(train[‘Total_Income_log’])test[‘Total_Income_log’] = np.log(test[‘Total_Income’]) Now the distribution looks much closer to normal and the effect of extreme values has been significantly subsided. Let’s create the EMI feature now. train[‘EMI’]=train[‘LoanAmount’]/train[‘Loan_Amount_Term’]test[‘EMI’]=test[‘LoanAmount’]/test[‘Loan_Amount_Term’] Let’s check the distribution of the EMI variable. sns.distplot(train[‘EMI’]) train[‘Balance Income’] = train[‘Total_Income’]-(train[‘EMI’]*1000)test[‘Balance Income’] = test[‘Total_Income’]-(test[‘EMI’]*1000)sns.distplot(train[‘Balance Income’]) Let us now drop the variables which we used to create these new features. The reason for doing this is, the correlation between those old features and these new features will be very high, and logistic regression assumes that the variables are not highly correlated. We also want to remove the noise from the dataset, so removing correlated features will help in reducing the noise too. train=train.drop([‘ApplicantIncome’, ‘CoapplicantIncome’, ‘LoanAmount’, ‘Loan_Amount_Term’], axis=1)test=test.drop([‘ApplicantIncome’, ‘CoapplicantIncome’, ‘LoanAmount’, ‘Loan_Amount_Term’], axis=1) After creating new features, we can continue the model building process. So we will start with the logistic regression model and then move over to more complex models like RandomForest and XGBoost. We will build the following models in this section. Logistic Regression Decision Tree Random Forest XGBoost Let’s prepare the data for feeding into the models. X = train.drop(‘Loan_Status’,1)y = train.Loan_Status i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print (‘\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = LogisticRegression(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.79674796747967482 of kfold 5 accuracy_score 0.69105691056910573 of kfold 5 accuracy_score 0.66666666666666664 of kfold 5 accuracy_score 0.78048780487804885 of kfold 5 accuracy_score 0.680327868852459 Mean Validation Accuracy 0.7230574436891909submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/Log2.csv') Decision tree is a type of supervised learning algorithm(having a pre-defined target variable) that is mostly used in classification problems. In this technique, we split the population or sample into two or more homogeneous sets(or sub-populations) based on the most significant splitter/differentiator in input variables. Decision trees use multiple algorithms to decide to split a node into two or more sub-nodes. The creation of sub-nodes increases the homogeneity of resultant sub-nodes. In other words, we can say that purity of the node increases with respect to the target variable. For a detailed explanation visit https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/#six Let’s fit the decision tree model with 5 folds of cross-validation. from sklearn import treei=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print ('\n{} of kfold {} '.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = tree.DecisionTreeClassifier(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print ('accuracy_score',score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print ('\n Mean Validation Accuracy',mean/(i-1))1 of kfold 5 accuracy_score 0.73983739837398382 of kfold 5 accuracy_score 0.69918699186991873 of kfold 5 accuracy_score 0.75609756097560984 of kfold 5 accuracy_score 0.70731707317073175 of kfold 5 accuracy_score 0.6721311475409836 Mean Validation Accuracy 0.7149140343862455submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/DecisionTree.csv') RandomForest is a tree-based bootstrapping algorithm wherein a certain no. of weak learners (decision trees) are combined to make a powerful prediction model. For every individual learner, a random sample of rows and a few randomly chosen variables are used to build a decision tree model. Final prediction can be a function of all the predictions made by the individual learners. In the case of a regression problem, the final prediction can be the mean of all the predictions. For a detailed explanation visit this article https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/ from sklearn.ensemble import RandomForestClassifieri=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print (‘\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = RandomForestClassifier(random_state=1, max_depth=10) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.82926829268292682 of kfold 5 accuracy_score 0.81300813008130083 of kfold 5 accuracy_score 0.77235772357723584 of kfold 5 accuracy_score 0.80487804878048795 of kfold 5 accuracy_score 0.7540983606557377 Mean Validation Accuracy 0.7947221111555378 We will try to improve the accuracy by tuning the hyperparameters for this model. We will use a grid search to get the optimized values of hyper parameters. Grid-search is a way to select the best of a family of hyper parameters, parametrized by a grid of parameters. We will tune the max_depth and n_estimators parameters. max_depth decides the maximum depth of the tree and n_estimators decides the number of trees that will be used in the random forest model. from sklearn.model_selection import GridSearchCVparamgrid = {‘max_depth’: list(range(1,20,2)), ‘n_estimators’: list(range(1,200,20))}grid_search=GridSearchCV(RandomForestClassifier(random_state=1),paramgrid)from sklearn.model_selection import train_test_splitx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size=0.3, random_state=1)grid_search.fit(x_train,y_train)GridSearchCV(estimator=RandomForestClassifier(random_state=1), param_grid={'max_depth': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 'n_estimators': [1, 21, 41, 61, 81, 101, 121, 141, 161, 181]})grid_search.best_estimator_RandomForestClassifier(max_depth=5, n_estimators=41, random_state=1)i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print ('\n{} of kfold {} '.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = RandomForestClassifier(random_state=1, max_depth=3, n_estimators=41) model.fit(xtr,ytr) pred_test = model.predict(xvl) score = accuracy_score(yvl,pred_test) mean += score print ('accuracy_score',score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print ('\n Mean Validation Accuracy',mean/(i-1))1 of kfold 5 accuracy_score 0.81300813008130082 of kfold 5 accuracy_score 0.84552845528455293 of kfold 5 accuracy_score 0.80487804878048794 of kfold 5 accuracy_score 0.79674796747967485 of kfold 5 accuracy_score 0.7786885245901639 Mean Validation Accuracy 0.8077702252432362submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/RandomForest.csv') Let us find the feature importance now, i.e. which features are most important for this problem. We will use the feature_importances_ attribute of sklearn to do so. importances=pd.Series(model.feature_importances_, index=X.columns)importances.plot(kind=’barh’, figsize=(12,8)) We can see that Credit_History is the most important feature followed by Balance Income, Total Income, EMI. So, feature engineering helped us in predicting our target variable. XGBoost is a fast and efficient algorithm and has been used by the winners of many data science competitions. It’s a boosting algorithm and you may refer the below article to know more about boosting:https://www.analyticsvidhya.com/blog/2015/11/quick-introduction-boosting-algorithms-machine-learning/ XGBoost works only with numeric variables and we have already replaced the categorical variables with numeric variables. Let’s have a look at the parameters that we are going to use in our model. n_estimator: This specifies the number of trees for the model. max_depth: We can specify the maximum depth of a tree using this parameter. GBoostError: XGBoost Library (libxgboost.dylib) could not be loaded. If you face this error in macOS, run brew install libomp in Terminal from xgboost import XGBClassifieri=1 mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True) for train_index,test_index in kf.split(X,y): print(‘\n{} of kfold {}’.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = XGBClassifier(n_estimators=50, max_depth=4) model.fit(xtr, ytr) pred_test = model.predict(xvl) score = accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5accuracy_score 0.78048780487804882 of kfold 5accuracy_score 0.78861788617886173 of kfold 5accuracy_score 0.76422764227642284 of kfold 5accuracy_score 0.78048780487804885 of kfold 5accuracy_score 0.7622950819672131 Mean Validation Accuracy 0.7752232440357191submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/XGBoost.csv') To create an SPSS Modeler Flow and build a machine learning model using it, follow the instructions here: developer.ibm.com Sign-up for an IBM Cloud account to try this tutorial — ibm.biz In this tutorial, we learned how to create models to predict the target variable, i.e. if the applicant will be able to repay the loan or not.
[ { "code": null, "e": 464, "s": 172, "text": "Loans are the core business of banks. The main profit comes directly from the loan’s interest. The loan companies grant a loan after an intensive process of verification and validation. However, they still don’t have assurance if the applicant is able to repay the loan with no difficulties." }, { "code": null, "e": 688, "s": 464, "text": "In this tutorial, we’ll build a predictive model to predict if an applicant is able to repay the lending company or not. We will prepare the data using Jupyter Notebook and use various models to predict the target variable." }, { "code": null, "e": 699, "s": 688, "text": "github.com" }, { "code": null, "e": 755, "s": 699, "text": "Sign-up for an IBM Cloud account to try this tutorial -" }, { "code": null, "e": 763, "s": 755, "text": "ibm.biz" }, { "code": null, "e": 1179, "s": 763, "text": "Getting the system ready and loading the dataUnderstanding the dataExploratory Data Analysis (EDA)i. Univariate Analysisii. Bivariate AnalysisMissing value and outlier treatmentEvaluation Metrics for classification problemsModel Building: Part 1Logistic Regression using stratified k-folds cross-validationFeature EngineeringModel Building: Part 2i. Logistic Regressionii. Decision Treeiii. Random Forestiv. XGBoost" }, { "code": null, "e": 1225, "s": 1179, "text": "Getting the system ready and loading the data" }, { "code": null, "e": 1248, "s": 1225, "text": "Understanding the data" }, { "code": null, "e": 1324, "s": 1248, "text": "Exploratory Data Analysis (EDA)i. Univariate Analysisii. Bivariate Analysis" }, { "code": null, "e": 1360, "s": 1324, "text": "Missing value and outlier treatment" }, { "code": null, "e": 1407, "s": 1360, "text": "Evaluation Metrics for classification problems" }, { "code": null, "e": 1430, "s": 1407, "text": "Model Building: Part 1" }, { "code": null, "e": 1492, "s": 1430, "text": "Logistic Regression using stratified k-folds cross-validation" }, { "code": null, "e": 1512, "s": 1492, "text": "Feature Engineering" }, { "code": null, "e": 1603, "s": 1512, "text": "Model Building: Part 2i. Logistic Regressionii. Decision Treeiii. Random Forestiv. XGBoost" }, { "code": null, "e": 1682, "s": 1603, "text": "We will be using Python for this course along with the below-listed libraries." }, { "code": null, "e": 1697, "s": 1682, "text": "Specifications" }, { "code": null, "e": 1704, "s": 1697, "text": "Python" }, { "code": null, "e": 1711, "s": 1704, "text": "pandas" }, { "code": null, "e": 1719, "s": 1711, "text": "seaborn" }, { "code": null, "e": 1727, "s": 1719, "text": "sklearn" }, { "code": null, "e": 1883, "s": 1727, "text": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings(“ignore”)" }, { "code": null, "e": 1962, "s": 1883, "text": "For this problem, we have three CSV files: train, test, and sample submission." }, { "code": null, "e": 2119, "s": 1962, "text": "Train file will be used for training the model, i.e. our model will learn from this file. It contains all the independent variables and the target variable." }, { "code": null, "e": 2272, "s": 2119, "text": "Test file contains all the independent variables, but not the target variable. We will apply the model to predict the target variable for the test data." }, { "code": null, "e": 2358, "s": 2272, "text": "Sample submission file contains the format in which we have to submit out predictions" }, { "code": null, "e": 2411, "s": 2358, "text": "train = pd.read_csv(‘Dataset/train.csv’)train.head()" }, { "code": null, "e": 2461, "s": 2411, "text": "test = pd.read_csv(‘Dataset/test.csv’)test.head()" }, { "code": null, "e": 2609, "s": 2461, "text": "Let’s make a copy of the train and test data so that even if we have to make any changes in these datasets we would not lose the original datasets." }, { "code": null, "e": 2662, "s": 2609, "text": "train_original=train.copy()test_original=test.copy()" }, { "code": null, "e": 2916, "s": 2662, "text": "train.columnsIndex(['Loan_ID', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed', 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term', 'Credit_History', 'Property_Area', 'Loan_Status'], dtype='object')" }, { "code": null, "e": 3014, "s": 2916, "text": "We have 12 independent variables and 1 target variable, i.e. Loan_Status in the training dataset." }, { "code": null, "e": 3252, "s": 3014, "text": "test.columnsIndex(['Loan_ID', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed', 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term', 'Credit_History', 'Property_Area'], dtype='object')" }, { "code": null, "e": 3425, "s": 3252, "text": "We have similar features in the test dataset as the training dataset except for the Loan_Status. We will predict the Loan_Status using the model built using the train data." }, { "code": null, "e": 3815, "s": 3425, "text": "train.dtypesLoan_ID objectGender objectMarried objectDependents objectEducation objectSelf_Employed objectApplicantIncome int64CoapplicantIncome float64LoanAmount float64Loan_Amount_Term float64Credit_History float64Property_Area objectLoan_Status objectdtype: object" }, { "code": null, "e": 3865, "s": 3815, "text": "We can see there are three formats of data types:" }, { "code": null, "e": 4053, "s": 3865, "text": "object: Object format means variables are categorical. Categorical variables in our dataset are Loan_ID, Gender, Married, Dependents, Education, Self_Employed, Property_Area, Loan_Status." }, { "code": null, "e": 4132, "s": 4053, "text": "int64: It represents the integer variables. ApplicantIncome is of this format." }, { "code": null, "e": 4231, "s": 4132, "text": "float64: It represents the variable that has some decimal values involved. They are also numerical" }, { "code": null, "e": 4252, "s": 4231, "text": "train.shape(614, 13)" }, { "code": null, "e": 4306, "s": 4252, "text": "We have 614 rows and 13 columns in the train dataset." }, { "code": null, "e": 4326, "s": 4306, "text": "test.shape(367, 12)" }, { "code": null, "e": 4375, "s": 4326, "text": "We have 367 rows and 12 columns in test dataset." }, { "code": null, "e": 4458, "s": 4375, "text": "train[‘Loan_Status’].value_counts()Y 422N 192Name: Loan_Status, dtype: int64" }, { "code": null, "e": 4526, "s": 4458, "text": "Normalize can be set to True to print proportions instead of number" }, { "code": null, "e": 4682, "s": 4526, "text": "train[‘Loan_Status’].value_counts(normalize=True) Y 0.687296N 0.312704Name: Loan_Status, dtype: float64train[‘Loan_Status’].value_counts().plot.bar()" }, { "code": null, "e": 4743, "s": 4682, "text": "The loan of 422(around 69%) people out of 614 were approved." }, { "code": null, "e": 4860, "s": 4743, "text": "Now, let's visualize each variable separately. Different types of variables are Categorical, ordinal, and numerical." }, { "code": null, "e": 4975, "s": 4860, "text": "Categorical features: These features have categories (Gender, Married, Self_Employed, Credit_History, Loan_Status)" }, { "code": null, "e": 5093, "s": 4975, "text": "Ordinal features: Variables in categorical features having some order involved (Dependents, Education, Property_Area)" }, { "code": null, "e": 5218, "s": 5093, "text": "Numerical features: These features have numerical values (ApplicantIncome, Co-applicantIncome, LoanAmount, Loan_Amount_Term)" }, { "code": null, "e": 5584, "s": 5218, "text": "train[‘Gender’].value_counts(normalize=True).plot.bar(figsize=(20,10), title=’Gender’)plt.show()train[‘Married’].value_counts(normalize=True).plot.bar(title=’Married’)plt.show()train[‘Self_Employed’].value_counts(normalize=True).plot.bar(title=’Self_Employed’)plt.show()train[‘Credit_History’].value_counts(normalize=True).plot.bar(title=’Credit_History’)plt.show()" }, { "code": null, "e": 5634, "s": 5584, "text": "It can be inferred from the above bar plots that:" }, { "code": null, "e": 5677, "s": 5634, "text": "80% of applicants in the dataset are male." }, { "code": null, "e": 5734, "s": 5677, "text": "Around 65% of the applicants in the dataset are married." }, { "code": null, "e": 5793, "s": 5734, "text": "Around 15% of applicants in the dataset are self-employed." }, { "code": null, "e": 5844, "s": 5793, "text": "Around 85% of applicants have repaid their doubts." }, { "code": null, "e": 6126, "s": 5844, "text": "train[‘Dependents’].value_counts(normalize=True).plot.bar(figsize=(24,6), title=’Dependents’)plt.show()train[‘Education’].value_counts(normalize=True).plot.bar(title=’Education’)plt.show()train[‘Property_Area’].value_counts(normalize=True).plot.bar(title=’Property_Area’)plt.show()" }, { "code": null, "e": 6189, "s": 6126, "text": "The following inferences can be made from the above bar plots:" }, { "code": null, "e": 6239, "s": 6189, "text": "Most of the applicants don't have any dependents." }, { "code": null, "e": 6282, "s": 6239, "text": "Around 80% of the applicants are Graduate." }, { "code": null, "e": 6334, "s": 6282, "text": "Most of the applicants are from the Semiurban area." }, { "code": null, "e": 6501, "s": 6334, "text": "Till now we have seen the categorical and ordinal variables and now let's visualize the numerical variables. Let's look at the distribution of Applicant income first." }, { "code": null, "e": 6609, "s": 6501, "text": "sns.distplot(train[‘ApplicantIncome’])plt.show()train[‘ApplicantIncome’].plot.box(figsize=(16,5))plt.show()" }, { "code": null, "e": 6866, "s": 6609, "text": "It can be inferred that most of the data in the distribution of applicant income are towards the left which means it is not normally distributed. We will try to make it normal in later sections as algorithms work better if the data is normally distributed." }, { "code": null, "e": 7138, "s": 6866, "text": "The boxplot confirms the presence of a lot of outliers/extreme values. This can be attributed to the income disparity in the society. Part of this can be driven by the fact that we are looking at people with different education levels. Let us segregate them by Education." }, { "code": null, "e": 7213, "s": 7138, "text": "train.boxplot(column=’ApplicantIncome’, by = ‘Education’) plt.suptitle(“”)" }, { "code": null, "e": 7328, "s": 7213, "text": "We can see that there are a higher number of graduates with very high incomes, which are appearing to be outliers." }, { "code": null, "e": 7380, "s": 7328, "text": "Let’s look at the Co-applicant income distribution." }, { "code": null, "e": 7492, "s": 7380, "text": "sns.distplot(train[‘CoapplicantIncome’])plt.show()train[‘CoapplicantIncome’].plot.box(figsize=(16,5))plt.show()" }, { "code": null, "e": 7709, "s": 7492, "text": "We see a similar distribution as that of the applicant's income. The majority of co-applicants income ranges from 0 to 5000. We also see a lot of outliers in the applicant's income and it is not normally distributed." }, { "code": null, "e": 7820, "s": 7709, "text": "train.notna()sns.distplot(train[‘LoanAmount’])plt.show()train[‘LoanAmount’].plot.box(figsize=(16,5))plt.show()" }, { "code": null, "e": 7947, "s": 7820, "text": "We see a lot of outliers in this variable and the distribution is fairly normal. We will treat the outliers in later sections." }, { "code": null, "e": 8010, "s": 7947, "text": "Let’s recall some of the hypotheses that we generated earlier:" }, { "code": null, "e": 8082, "s": 8010, "text": "Applicants with high incomes should have more chances of loan approval." }, { "code": null, "e": 8175, "s": 8082, "text": "Applicants who have repaid their previous debts should have higher chances of loan approval." }, { "code": null, "e": 8301, "s": 8175, "text": "Loan approval should also depend on the loan amount. If the loan amount is less, the chances of loan approval should be high." }, { "code": null, "e": 8398, "s": 8301, "text": "Lesser the amount to be paid monthly to repay the loan, the higher the chances of loan approval." }, { "code": null, "e": 8473, "s": 8398, "text": "Let’s try to test the above-mentioned hypotheses using bivariate analysis." }, { "code": null, "e": 8610, "s": 8473, "text": "After looking at every variable individually in univariate analysis, we will now explore them again with respect to the target variable." }, { "code": null, "e": 8825, "s": 8610, "text": "First of all, we will find the relation between the target variable and categorical independent variables. Let us look at the stacked bar plot now which will give us the proportion of approved and unapproved loans." }, { "code": null, "e": 8983, "s": 8825, "text": "Gender=pd.crosstab(train[‘Gender’],train[‘Loan_Status’])Gender.div(Gender.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()" }, { "code": null, "e": 9117, "s": 8983, "text": "It can be inferred that the proportion of male and female applicants is more or less the same for both approved and unapproved loans." }, { "code": null, "e": 9194, "s": 9117, "text": "Now let us visualize the remaining categorical variables vs target variable." }, { "code": null, "e": 9883, "s": 9194, "text": "Married=pd.crosstab(train[‘Married’],train[‘Loan_Status’])Dependents=pd.crosstab(train[‘Dependents’],train[‘Loan_Status’])Education=pd.crosstab(train[‘Education’],train[‘Loan_Status’])Self_Employed=pd.crosstab(train[‘Self_Employed’],train[‘Loan_Status’])Married.div(Married.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Dependents.div(Dependents.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Education.div(Education.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Self_Employed.div(Self_Employed.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()" }, { "code": null, "e": 9950, "s": 9883, "text": "The proportion of married applicants is higher for approved loans." }, { "code": null, "e": 10055, "s": 9950, "text": "Distribution of applicants with 1 or 3+ dependents is similar across both the categories of Loan_Status." }, { "code": null, "e": 10137, "s": 10055, "text": "There is nothing significant we can infer from Self_Employed vs Loan_Status plot." }, { "code": null, "e": 10243, "s": 10137, "text": "Now we will look at the relationship between remaining categorical independent variables and Loan_Status." }, { "code": null, "e": 10604, "s": 10243, "text": "Credit_History=pd.crosstab(train[‘Credit_History’],train[‘Loan_Status’])Property_Area=pd.crosstab(train[‘Property_Area’],train[‘Loan_Status’])Credit_History.div(Credit_History.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True,figsize=(4,4))plt.show()Property_Area.div(Property_Area.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.show()" }, { "code": null, "e": 10692, "s": 10604, "text": "It seems people with a credit history as 1 are more likely to get their loans approved." }, { "code": null, "e": 10811, "s": 10692, "text": "The proportion of loans getting approved in the semi-urban area is higher as compared to that in rural or urban areas." }, { "code": null, "e": 10900, "s": 10811, "text": "Now let’s visualize numerical independent variables with respect to the target variable." }, { "code": null, "e": 11054, "s": 10900, "text": "We will try to find the mean income of people for which the loan has been approved vs the mean income of people for which the loan has not been approved." }, { "code": null, "e": 11120, "s": 11054, "text": "train.groupby(‘Loan_Status’)[‘ApplicantIncome’].mean().plot.bar()" }, { "code": null, "e": 11354, "s": 11120, "text": "Here the y-axis represents the mean applicant income. We don’t see any change in the mean income. So, let’s make bins for the applicant income variable based on the values in it and analyze the corresponding loan status for each bin." }, { "code": null, "e": 11700, "s": 11354, "text": "bins=[0,2500,4000,6000,81000]group=[‘Low’,’Average’,’High’,’Very high’]train[‘Income_bin’]=pd.cut(train[‘ApplicantIncome’],bins,labels=group)Income_bin=pd.crosstab(train[‘Income_bin’],train[‘Loan_Status’])Income_bin.div(Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘ApplicantIncome’)P=plt.ylabel(‘Percentage’)" }, { "code": null, "e": 11928, "s": 11700, "text": "It can be inferred that Applicant's income does not affect the chances of loan approval which contradicts our hypothesis in which we assumed that if the applicant's income is high the chances of loan approval will also be high." }, { "code": null, "e": 12014, "s": 11928, "text": "We will analyze the co-applicant income and loan amount variable in a similar manner." }, { "code": null, "e": 12407, "s": 12014, "text": "bins=[0,1000,3000,42000]group=[‘Low’,’Average’,’High’]train[‘Coapplicant_Income_bin’]=pd.cut(train[‘CoapplicantIncome’],bins,labels=group)Coapplicant_Income_bin=pd.crosstab(train[‘Coapplicant_Income_bin’],train[‘Loan_Status’])Coapplicant_Income_bin.div(Coapplicant_Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘CoapplicantIncome’)P=plt.ylabel(‘Percentage’)" }, { "code": null, "e": 12879, "s": 12407, "text": "It shows that if co-applicants income is less the chances of loan approval are high. But this does not look right. The possible reason behind this may be that most of the applicants don’t have any co-applicant so the co-applicant income for such applicants is 0 and hence the loan approval is not dependent on it. So, we can make a new variable in which we will combine the applicant’s and co-applicants income to visualize the combined effect of income on loan approval." }, { "code": null, "e": 13003, "s": 12879, "text": "Let us combine the Applicant Income and Co-applicant Income and see the combined effect of Total Income on the Loan_Status." }, { "code": null, "e": 13446, "s": 13003, "text": "train[‘Total_Income’]=train[‘ApplicantIncome’]+train[‘CoapplicantIncome’]bins=[0,2500,4000,6000,81000]group=[‘Low’,’Average’,’High’,’Very high’]train[‘Total_Income_bin’]=pd.cut(train[‘Total_Income’],bins,labels=group)Total_Income_bin=pd.crosstab(train[‘Total_Income_bin’],train[‘Loan_Status’])Total_Income_bin.div(Total_Income_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘Total_Income’)P=plt.ylabel(‘Percentage’)" }, { "code": null, "e": 13621, "s": 13446, "text": "We can see that Proportion of loans getting approved for applicants having low Total_Income is very less compared to that of applicants with Average, High & Very High Income." }, { "code": null, "e": 13663, "s": 13621, "text": "Let’s visualize the Loan Amount variable." }, { "code": null, "e": 13998, "s": 13663, "text": "bins=[0,100,200,700]group=[‘Low’,’Average’,’High’]train[‘LoanAmount_bin’]=pd.cut(train[‘LoanAmount’],bins,labels=group)LoanAmount_bin=pd.crosstab(train[‘LoanAmount_bin’],train[‘Loan_Status’])LoanAmount_bin.div(LoanAmount_bin.sum(1).astype(float), axis=0).plot(kind=”bar”,stacked=True)plt.xlabel(‘LoanAmount’)P=plt.ylabel(‘Percentage’)" }, { "code": null, "e": 14263, "s": 13998, "text": "It can be seen that the proportion of approved loans is higher for Low and Average Loan Amount as compared to that of High Loan Amount which supports our hypothesis in which we considered that the chances of loan approval will be high when the loan amount is less." }, { "code": null, "e": 14677, "s": 14263, "text": "Let’s drop the bins which we created for the exploration part. We will change the 3+ in dependents variable to 3 to make it a numerical variable. We will also convert the target variable’s categories into 0 and 1 so that we can find its correlation with numerical variables. One more reason to do so is few models like logistic regression takes only numeric values as input. We will replace N with 0 and Y with 1." }, { "code": null, "e": 14993, "s": 14677, "text": "train=train.drop([‘Income_bin’, ‘Coapplicant_Income_bin’, ‘LoanAmount_bin’, ‘Total_Income_bin’, ‘Total_Income’], axis=1)train[‘Dependents’].replace(‘3+’, 3,inplace=True)test[‘Dependents’].replace(‘3+’, 3,inplace=True)train[‘Loan_Status’].replace(’N’, 0,inplace=True)train[‘Loan_Status’].replace(‘Y’, 1,inplace=True)" }, { "code": null, "e": 15240, "s": 14993, "text": "Now let’s look at the correlation between all the numerical variables. We will use the heat map to visualize the correlation. Heatmaps visualize data through variations in coloring. The variables with darker color means their correlation is more." }, { "code": null, "e": 15362, "s": 15240, "text": "matrix = train.corr()f, ax = plt.subplots(figsize=(9,6))sns.heatmap(matrix,vmax=.8,square=True,cmap=”BuPu”, annot = True)" }, { "code": null, "e": 15528, "s": 15362, "text": "We see that the most correlate variables are (ApplicantIncome — LoanAmount) and (Credit_History — Loan_Status). LoanAmount is also correlated with CoapplicantIncome." }, { "code": null, "e": 15581, "s": 15528, "text": "Let’s list out feature-wise count of missing values." }, { "code": null, "e": 15913, "s": 15581, "text": "train.isnull().sum()Loan_ID 0Gender 13Married 3Dependents 15Education 0Self_Employed 32ApplicantIncome 0CoapplicantIncome 0LoanAmount 22Loan_Amount_Term 14Credit_History 50Property_Area 0Loan_Status 0dtype: int64" }, { "code": null, "e": 16044, "s": 15913, "text": "There are missing values in Gender, Married, Dependents, Self_Employed, LoanAmount, Loan_Amount_Term, and Credit_History features." }, { "code": null, "e": 16109, "s": 16044, "text": "We will treat the missing values in all the features one by one." }, { "code": null, "e": 16167, "s": 16109, "text": "We can consider these methods to fill the missing values:" }, { "code": null, "e": 16224, "s": 16167, "text": "For numerical variables: imputation using mean or median" }, { "code": null, "e": 16273, "s": 16224, "text": "For categorical variables: imputation using mode" }, { "code": null, "e": 16434, "s": 16273, "text": "There are very few missing values in Gender, Married, Dependents, Credit_History, and Self_Employed features so we can fill them using the mode of the features." }, { "code": null, "e": 16790, "s": 16434, "text": "train[‘Gender’].fillna(train[‘Gender’].mode()[0], inplace=True)train[‘Married’].fillna(train[‘Married’].mode()[0], inplace=True)train[‘Dependents’].fillna(train[‘Dependents’].mode()[0], inplace=True)train[‘Self_Employed’].fillna(train[‘Self_Employed’].mode()[0], inplace=True)train[‘Credit_History’].fillna(train[‘Credit_History’].mode()[0], inplace=True)" }, { "code": null, "e": 16932, "s": 16790, "text": "Now let’s try to find a way to fill the missing values in Loan_Amount_Term. We will look at the value count of the Loan amount term variable." }, { "code": null, "e": 17129, "s": 16932, "text": "train[‘Loan_Amount_Term’].value_counts()360.0 512180.0 44480.0 15300.0 1384.0 4240.0 4120.0 336.0 260.0 212.0 1Name: Loan_Amount_Term, dtype: int64" }, { "code": null, "e": 17311, "s": 17129, "text": "It can be seen that in the loan amount term variable, the value of 360 is repeating the most. So we will replace the missing values in this variable using the mode of this variable." }, { "code": null, "e": 17395, "s": 17311, "text": "train[‘Loan_Amount_Term’].fillna(train[‘Loan_Amount_Term’].mode()[0], inplace=True)" }, { "code": null, "e": 17720, "s": 17395, "text": "Now we will see the LoanAmount variable. As it is a numerical variable, we can use mean or median to impute the missing values. We will use the median to fill the null values as earlier we saw that the loan amount has outliers so the mean will not be the proper approach as it is highly affected by the presence of outliers." }, { "code": null, "e": 17791, "s": 17720, "text": "train[‘LoanAmount’].fillna(train[‘LoanAmount’].median(), inplace=True)" }, { "code": null, "e": 17865, "s": 17791, "text": "Now let's check whether all the missing values are filled in the dataset." }, { "code": null, "e": 18184, "s": 17865, "text": "train.isnull().sum()Loan_ID 0Gender 0Married 0Dependents 0Education 0Self_Employed 0ApplicantIncome 0CoapplicantIncome 0LoanAmount 0Loan_Amount_Term 0Credit_History 0Property_Area 0Loan_Status 0dtype: int64" }, { "code": null, "e": 18346, "s": 18184, "text": "As we can see that all the missing values have been filled in the test dataset. Let’s fill all the missing values in the test dataset too with the same approach." }, { "code": null, "e": 18848, "s": 18346, "text": "test[‘Gender’].fillna(train[‘Gender’].mode()[0], inplace=True)test[‘Married’].fillna(train[‘Married’].mode()[0], inplace=True)test[‘Dependents’].fillna(train[‘Dependents’].mode()[0], inplace=True)test[‘Self_Employed’].fillna(train[‘Self_Employed’].mode()[0], inplace=True)test[‘Credit_History’].fillna(train[‘Credit_History’].mode()[0], inplace=True)test[‘Loan_Amount_Term’].fillna(train[‘Loan_Amount_Term’].mode()[0], inplace=True)test[‘LoanAmount’].fillna(train[‘LoanAmount’].median(), inplace=True)" }, { "code": null, "e": 20063, "s": 18848, "text": "As we saw earlier in univariate analysis, LoanAmount contains outliers so we have to treat them as the presence of outliers affects the distribution of the data. Let’s examine what can happen to a data set with outliers. For the sample data set:1,1,2,2,2,2,3,3,3,4,4We find the following: mean, median, mode, and standard deviationMean = 2.58Median = 2.5Mode=2Standard Deviation = 1.08If we add an outlier to the data set:1,1,2,2,2,2,3,3,3,4,4,400The new values of our statistics are:Mean = 35.38Median = 2.5Mode=2Standard Deviation = 114.74It can be seen that having outliers often has a significant effect on the mean and standard deviation and hence affecting the distribution. We must take steps to remove outliers from our data sets.Due to these outliers bulk of the data in the loan amount is at the left and the right tail is longer. This is called right skewness. One way to remove the skewness is by doing the log transformation. As we take the log transformation, it does not affect the smaller values much but reduces the larger values. So, we get a distribution similar to normal distribution.Let’s visualize the effect of log transformation. We will do similar changes to the test file simultaneously." }, { "code": null, "e": 20201, "s": 20063, "text": "train[‘LoanAmount_log’]=np.log(train[‘LoanAmount’])train[‘LoanAmount_log’].hist(bins=20)test[‘LoanAmount_log’]=np.log(test[‘LoanAmount’])" }, { "code": null, "e": 20399, "s": 20201, "text": "Now the distribution looks much closer to normal and the effect of extreme values has been significantly subsided. Let’s build a logistic regression model and make predictions for the test dataset." }, { "code": null, "e": 20540, "s": 20399, "text": "Let us make our first model predict the target variable. We will start with Logistic Regression which is used for predicting binary outcome." }, { "code": null, "e": 20700, "s": 20540, "text": "Logistic Regression is a classification algorithm. It is used to predict a binary outcome (1 / 0, Yes / No, True / False) given a set of independent variables." }, { "code": null, "e": 20822, "s": 20700, "text": "Logistic regression is an estimation of Logit function. The logit function is simply a log of odds in favor of the event." }, { "code": null, "e": 20949, "s": 20822, "text": "This function creates an S-shaped curve with the probability estimate, which is very similar to the required stepwise function" }, { "code": null, "e": 21255, "s": 20949, "text": "To learn further on logistic regression, refer to this article: https://www.analyticsvidhya.com/blog/2015/10/basics-logistic-regression/Let's drop the Loan_ID variable as it does not have any effect on the loan status. We will do the same changes to the test dataset which we did for the training dataset." }, { "code": null, "e": 21322, "s": 21255, "text": "train=train.drop(‘Loan_ID’,axis=1)test=test.drop(‘Loan_ID’,axis=1)" }, { "code": null, "e": 21544, "s": 21322, "text": "We will use scikit-learn (sklearn) for making different models which is an open source library for Python. It is one of the most efcient tools which contains many inbuilt functions that can be used for modeling in Python." }, { "code": null, "e": 21639, "s": 21544, "text": "To learn further about sklearn, refer here: http://scikit-learn.org/stable/tutorial/index.html" }, { "code": null, "e": 21794, "s": 21639, "text": "Sklearn requires the target variable in a separate dataset. So, we will drop our target variable from the training dataset and save it in another dataset." }, { "code": null, "e": 21847, "s": 21794, "text": "X = train.drop(‘Loan_Status’,1)y = train.Loan_Status" }, { "code": null, "e": 22082, "s": 21847, "text": "Now we will make dummy variables for the categorical variables. The dummy variable turns categorical variables into a series of 0 and 1, making them a lot easier to quantify and compare. Let us understand the process of dummies first:" }, { "code": null, "e": 22151, "s": 22082, "text": "Consider the “Gender” variable. It has two classes, Male and Female." }, { "code": null, "e": 22274, "s": 22151, "text": "As logistic regression takes only the numerical values as input, we have to change male and female into a numerical value." }, { "code": null, "e": 22445, "s": 22274, "text": "Once we apply dummies to this variable, it will convert the “Gender” variable into two variables(Gender_Male and Gender_Female), one for each class, i.e. Male and Female." }, { "code": null, "e": 22544, "s": 22445, "text": "Gender_Male will have a value of 0 if the gender is Female and a value of 1 if the gender is Male." }, { "code": null, "e": 22618, "s": 22544, "text": "X = pd.get_dummies(X)train=pd.get_dummies(train)test=pd.get_dummies(test)" }, { "code": null, "e": 23095, "s": 22618, "text": "Now we will train the model on the training dataset and make predictions for the test dataset. But can we validate these predictions? One way of doing this is we can divide our train dataset into two parts: train and validation. We can train the model on this training part and using that make predictions for the validation part. In this way, we can validate our predictions as we have the true predictions for the validation part (which we do not have for the test dataset)." }, { "code": null, "e": 23222, "s": 23095, "text": "We will use the train_test_split function from sklearn to divide our train dataset. So, first, let us import train_test_split." }, { "code": null, "e": 23342, "s": 23222, "text": "from sklearn.model_selection import train_test_splitx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size=0.3)" }, { "code": null, "e": 23510, "s": 23342, "text": "The dataset has been divided into training and validation part. Let us import LogisticRegression and accuracy_score from sklearn and fit the logistic regression model." }, { "code": null, "e": 23679, "s": 23510, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoremodel = LogisticRegression()model.fit(x_train, y_train)LogisticRegression()" }, { "code": null, "e": 24061, "s": 23679, "text": "Here the C parameter represents the inverse of regularization strength. Regularization is applying a penalty to increasing the magnitude of parameter values in order to reduce overfitting. Smaller values of C specify stronger regularization. To learn about other parameters, refer here: http://scikit- learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html" }, { "code": null, "e": 24138, "s": 24061, "text": "Let’s predict the Loan_Status for validation set and calculate its accuracy." }, { "code": null, "e": 24214, "s": 24138, "text": "pred_cv = model.predict(x_cv)accuracy_score(y_cv,pred_cv)0.7891891891891892" }, { "code": null, "e": 24316, "s": 24214, "text": "So our predictions are almost 80% accurate, i.e. we have identified 80% of the loan status correctly." }, { "code": null, "e": 24361, "s": 24316, "text": "Let’s make predictions for the test dataset." }, { "code": null, "e": 24393, "s": 24361, "text": "pred_test = model.predict(test)" }, { "code": null, "e": 24475, "s": 24393, "text": "Let's import the submission file which we have to submit on the solution checker." }, { "code": null, "e": 24550, "s": 24475, "text": "submission = pd.read_csv(‘Dataset/sample_submission.csv’)submission.head()" }, { "code": null, "e": 24763, "s": 24550, "text": "We only need the Loan_ID and the corresponding Loan_Status for the final submission. we will fill these columns with the Loan_ID of the test dataset and the predictions that we made, i.e., pred_test respectively." }, { "code": null, "e": 24845, "s": 24763, "text": "submission[‘Loan_Status’]=pred_testsubmission[‘Loan_ID’]=test_original[‘Loan_ID’]" }, { "code": null, "e": 24923, "s": 24845, "text": "Remember we need predictions in Y and N. So let’s convert 1 and 0 to Y and N." }, { "code": null, "e": 25034, "s": 24923, "text": "submission[‘Loan_Status’].replace(0, ’N’, inplace=True)submission[‘Loan_Status’].replace(1, ‘Y’, inplace=True)" }, { "code": null, "e": 25090, "s": 25034, "text": "Finally, we will convert the submission to .csv format." }, { "code": null, "e": 25180, "s": 25090, "text": "pd.DataFrame(submission, columns=[‘Loan_ID’,’Loan_Status’]).to_csv(‘Output/logistic.csv’)" }, { "code": null, "e": 25488, "s": 25180, "text": "To check how robust our model is to unseen data, we can use Validation. It is a technique that involves reserving a particular sample of a dataset on which you do not train the model. Later, you test your model on this sample before finalizing it. Some of the common methods for validation are listed below:" }, { "code": null, "e": 25516, "s": 25488, "text": "The validation set approach" }, { "code": null, "e": 25540, "s": 25516, "text": "k-fold cross-validation" }, { "code": null, "e": 25579, "s": 25540, "text": "Leave one out cross-validation (LOOCV)" }, { "code": null, "e": 25614, "s": 25579, "text": "Stratified k-fold cross-validation" }, { "code": null, "e": 25804, "s": 25614, "text": "If you wish to know more about validation techniques, then please refer to this article: https://www.analyticsvidhya.com/blog/2018/05/improve-model-performance-cross-validation-in-python-r/" }, { "code": null, "e": 25909, "s": 25804, "text": "In this section, we will learn about stratified k-fold cross-validation. Let us understand how it works:" }, { "code": null, "e": 26033, "s": 25909, "text": "Stratification is the process of rearranging the data so as to ensure that each fold is a good representative of the whole." }, { "code": null, "e": 26234, "s": 26033, "text": "For example, in a binary classification problem where each class comprises of 50% of the data, it is best to arrange the data such that in every fold, each class comprises of about half the instances." }, { "code": null, "e": 26310, "s": 26234, "text": "It is generally a better approach when dealing with both bias and variance." }, { "code": null, "e": 26444, "s": 26310, "text": "A randomly selected fold might not adequately represent the minor class, particularly in cases where there is a huge class imbalance." }, { "code": null, "e": 26505, "s": 26444, "text": "Let’s import StratifiedKFold from sklearn and fit the model." }, { "code": null, "e": 26557, "s": 26505, "text": "from sklearn.model_selection import StratifiedKFold" }, { "code": null, "e": 26673, "s": 26557, "text": "Now let’s make a cross-validation logistic model with stratified 5 folds and make predictions for the test dataset." }, { "code": null, "e": 27479, "s": 26673, "text": "i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1)for train_index,test_index in kf.split(X,y): print (‘\\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = LogisticRegression(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.80487804878048792 of kfold 5 accuracy_score 0.76422764227642283 of kfold 5 accuracy_score 0.78048780487804884 of kfold 5 accuracy_score 0.84552845528455295 of kfold 5 accuracy_score 0.8032786885245902Mean Validation Accuracy 0.7996801279488205" }, { "code": null, "e": 27577, "s": 27479, "text": "The mean validation accuracy for this model turns out to be 0.80. Let us visualize the roc curve." }, { "code": null, "e": 27856, "s": 27577, "text": "from sklearn import metricsfpr, tpr, _ = metrics.roc_curve(yvl, pred)auc = metrics.roc_auc_score(yvl, pred)plt.figure(figsize=(12,8))plt.plot(fpr, tpr, label=”validation, auc=”+str(auc))plt.xlabel(‘False Positive Rate’)plt.ylabel(‘True Positive Rate’)plt.legend(loc=4)plt.show()" }, { "code": null, "e": 27884, "s": 27856, "text": "We got an auc value of 0.70" }, { "code": null, "e": 27966, "s": 27884, "text": "submission[‘Loan_Status’]=pred_testsubmission[‘Loan_ID’]=test_original[‘Loan_ID’]" }, { "code": null, "e": 28044, "s": 27966, "text": "Remember we need predictions in Y and N. So let’s convert 1 and 0 to Y and N." }, { "code": null, "e": 28240, "s": 28044, "text": "submission[‘Loan_Status’].replace(0, ’N’, inplace=True)submission[‘Loan_Status’].replace(1, ‘Y’, inplace=True)pd.DataFrame(submission, columns=[‘Loan_ID’,’Loan_Status’]).to_csv(‘Output/Log1.csv’)" }, { "code": null, "e": 28392, "s": 28240, "text": "Based on the domain knowledge, we can come up with new features that might affect the target variable. We will create the following three new features:" }, { "code": null, "e": 28586, "s": 28392, "text": "Total Income — As discussed during bivariate analysis we will combine the Applicant Income and Co-applicant Income. If the total income is high, the chances of loan approval might also be high." }, { "code": null, "e": 28885, "s": 28586, "text": "EMI — EMI is the monthly amount to be paid by the applicant to repay the loan. The idea behind making this variable is that people who have high EMI’s might find it difficult to pay back the loan. We can calculate the EMI by taking the ratio of the loan amount with respect to the loan amount term." }, { "code": null, "e": 29131, "s": 28885, "text": "Balance Income — This is the income left after the EMI has been paid. The idea behind creating this variable is that if this value is high, the chances are high that a person will repay the loan and hence increasing the chances of loan approval." }, { "code": null, "e": 29275, "s": 29131, "text": "train[‘Total_Income’]=train[‘ApplicantIncome’]+train[‘CoapplicantIncome’]test[‘Total_Income’]=test[‘ApplicantIncome’]+test[‘CoapplicantIncome’]" }, { "code": null, "e": 29321, "s": 29275, "text": "Let’s check the distribution of Total Income." }, { "code": null, "e": 29357, "s": 29321, "text": "sns.distplot(train[‘Total_Income’])" }, { "code": null, "e": 29507, "s": 29357, "text": "We can see it is shifted towards left, i.e., the distribution is right-skewed. So, let’s take the log transformation to make the distribution normal." }, { "code": null, "e": 29659, "s": 29507, "text": "train[‘Total_Income_log’] = np.log(train[‘Total_Income’])sns.distplot(train[‘Total_Income_log’])test[‘Total_Income_log’] = np.log(test[‘Total_Income’])" }, { "code": null, "e": 29808, "s": 29659, "text": "Now the distribution looks much closer to normal and the effect of extreme values has been significantly subsided. Let’s create the EMI feature now." }, { "code": null, "e": 29922, "s": 29808, "text": "train[‘EMI’]=train[‘LoanAmount’]/train[‘Loan_Amount_Term’]test[‘EMI’]=test[‘LoanAmount’]/test[‘Loan_Amount_Term’]" }, { "code": null, "e": 29972, "s": 29922, "text": "Let’s check the distribution of the EMI variable." }, { "code": null, "e": 29999, "s": 29972, "text": "sns.distplot(train[‘EMI’])" }, { "code": null, "e": 30168, "s": 29999, "text": "train[‘Balance Income’] = train[‘Total_Income’]-(train[‘EMI’]*1000)test[‘Balance Income’] = test[‘Total_Income’]-(test[‘EMI’]*1000)sns.distplot(train[‘Balance Income’])" }, { "code": null, "e": 30555, "s": 30168, "text": "Let us now drop the variables which we used to create these new features. The reason for doing this is, the correlation between those old features and these new features will be very high, and logistic regression assumes that the variables are not highly correlated. We also want to remove the noise from the dataset, so removing correlated features will help in reducing the noise too." }, { "code": null, "e": 30754, "s": 30555, "text": "train=train.drop([‘ApplicantIncome’, ‘CoapplicantIncome’, ‘LoanAmount’, ‘Loan_Amount_Term’], axis=1)test=test.drop([‘ApplicantIncome’, ‘CoapplicantIncome’, ‘LoanAmount’, ‘Loan_Amount_Term’], axis=1)" }, { "code": null, "e": 31004, "s": 30754, "text": "After creating new features, we can continue the model building process. So we will start with the logistic regression model and then move over to more complex models like RandomForest and XGBoost. We will build the following models in this section." }, { "code": null, "e": 31024, "s": 31004, "text": "Logistic Regression" }, { "code": null, "e": 31038, "s": 31024, "text": "Decision Tree" }, { "code": null, "e": 31052, "s": 31038, "text": "Random Forest" }, { "code": null, "e": 31060, "s": 31052, "text": "XGBoost" }, { "code": null, "e": 31112, "s": 31060, "text": "Let’s prepare the data for feeding into the models." }, { "code": null, "e": 31165, "s": 31112, "text": "X = train.drop(‘Loan_Status’,1)y = train.Loan_Status" }, { "code": null, "e": 32260, "s": 31165, "text": "i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print (‘\\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = LogisticRegression(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.79674796747967482 of kfold 5 accuracy_score 0.69105691056910573 of kfold 5 accuracy_score 0.66666666666666664 of kfold 5 accuracy_score 0.78048780487804885 of kfold 5 accuracy_score 0.680327868852459 Mean Validation Accuracy 0.7230574436891909submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/Log2.csv')" }, { "code": null, "e": 32584, "s": 32260, "text": "Decision tree is a type of supervised learning algorithm(having a pre-defined target variable) that is mostly used in classification problems. In this technique, we split the population or sample into two or more homogeneous sets(or sub-populations) based on the most significant splitter/differentiator in input variables." }, { "code": null, "e": 32851, "s": 32584, "text": "Decision trees use multiple algorithms to decide to split a node into two or more sub-nodes. The creation of sub-nodes increases the homogeneity of resultant sub-nodes. In other words, we can say that purity of the node increases with respect to the target variable." }, { "code": null, "e": 32990, "s": 32851, "text": "For a detailed explanation visit https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/#six" }, { "code": null, "e": 33058, "s": 32990, "text": "Let’s fit the decision tree model with 5 folds of cross-validation." }, { "code": null, "e": 34231, "s": 33058, "text": "from sklearn import treei=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print ('\\n{} of kfold {} '.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = tree.DecisionTreeClassifier(random_state=1) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print ('accuracy_score',score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print ('\\n Mean Validation Accuracy',mean/(i-1))1 of kfold 5 accuracy_score 0.73983739837398382 of kfold 5 accuracy_score 0.69918699186991873 of kfold 5 accuracy_score 0.75609756097560984 of kfold 5 accuracy_score 0.70731707317073175 of kfold 5 accuracy_score 0.6721311475409836 Mean Validation Accuracy 0.7149140343862455submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/DecisionTree.csv')" }, { "code": null, "e": 34390, "s": 34231, "text": "RandomForest is a tree-based bootstrapping algorithm wherein a certain no. of weak learners (decision trees) are combined to make a powerful prediction model." }, { "code": null, "e": 34521, "s": 34390, "text": "For every individual learner, a random sample of rows and a few randomly chosen variables are used to build a decision tree model." }, { "code": null, "e": 34612, "s": 34521, "text": "Final prediction can be a function of all the predictions made by the individual learners." }, { "code": null, "e": 34710, "s": 34612, "text": "In the case of a regression problem, the final prediction can be the mean of all the predictions." }, { "code": null, "e": 34858, "s": 34710, "text": "For a detailed explanation visit this article https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/" }, { "code": null, "e": 35747, "s": 34858, "text": "from sklearn.ensemble import RandomForestClassifieri=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print (‘\\n{} of kfold {} ‘.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = RandomForestClassifier(random_state=1, max_depth=10) model.fit(xtr,ytr) pred_test=model.predict(xvl) score=accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5 accuracy_score 0.82926829268292682 of kfold 5 accuracy_score 0.81300813008130083 of kfold 5 accuracy_score 0.77235772357723584 of kfold 5 accuracy_score 0.80487804878048795 of kfold 5 accuracy_score 0.7540983606557377 Mean Validation Accuracy 0.7947221111555378" }, { "code": null, "e": 36015, "s": 35747, "text": "We will try to improve the accuracy by tuning the hyperparameters for this model. We will use a grid search to get the optimized values of hyper parameters. Grid-search is a way to select the best of a family of hyper parameters, parametrized by a grid of parameters." }, { "code": null, "e": 36210, "s": 36015, "text": "We will tune the max_depth and n_estimators parameters. max_depth decides the maximum depth of the tree and n_estimators decides the number of trees that will be used in the random forest model." }, { "code": null, "e": 38121, "s": 36210, "text": "from sklearn.model_selection import GridSearchCVparamgrid = {‘max_depth’: list(range(1,20,2)), ‘n_estimators’: list(range(1,200,20))}grid_search=GridSearchCV(RandomForestClassifier(random_state=1),paramgrid)from sklearn.model_selection import train_test_splitx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size=0.3, random_state=1)grid_search.fit(x_train,y_train)GridSearchCV(estimator=RandomForestClassifier(random_state=1), param_grid={'max_depth': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 'n_estimators': [1, 21, 41, 61, 81, 101, 121, 141, 161, 181]})grid_search.best_estimator_RandomForestClassifier(max_depth=5, n_estimators=41, random_state=1)i=1mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True)for train_index,test_index in kf.split(X,y): print ('\\n{} of kfold {} '.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = RandomForestClassifier(random_state=1, max_depth=3, n_estimators=41) model.fit(xtr,ytr) pred_test = model.predict(xvl) score = accuracy_score(yvl,pred_test) mean += score print ('accuracy_score',score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print ('\\n Mean Validation Accuracy',mean/(i-1))1 of kfold 5 accuracy_score 0.81300813008130082 of kfold 5 accuracy_score 0.84552845528455293 of kfold 5 accuracy_score 0.80487804878048794 of kfold 5 accuracy_score 0.79674796747967485 of kfold 5 accuracy_score 0.7786885245901639 Mean Validation Accuracy 0.8077702252432362submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/RandomForest.csv')" }, { "code": null, "e": 38286, "s": 38121, "text": "Let us find the feature importance now, i.e. which features are most important for this problem. We will use the feature_importances_ attribute of sklearn to do so." }, { "code": null, "e": 38398, "s": 38286, "text": "importances=pd.Series(model.feature_importances_, index=X.columns)importances.plot(kind=’barh’, figsize=(12,8))" }, { "code": null, "e": 38575, "s": 38398, "text": "We can see that Credit_History is the most important feature followed by Balance Income, Total Income, EMI. So, feature engineering helped us in predicting our target variable." }, { "code": null, "e": 38877, "s": 38575, "text": "XGBoost is a fast and efficient algorithm and has been used by the winners of many data science competitions. It’s a boosting algorithm and you may refer the below article to know more about boosting:https://www.analyticsvidhya.com/blog/2015/11/quick-introduction-boosting-algorithms-machine-learning/" }, { "code": null, "e": 39073, "s": 38877, "text": "XGBoost works only with numeric variables and we have already replaced the categorical variables with numeric variables. Let’s have a look at the parameters that we are going to use in our model." }, { "code": null, "e": 39136, "s": 39073, "text": "n_estimator: This specifies the number of trees for the model." }, { "code": null, "e": 39212, "s": 39136, "text": "max_depth: We can specify the maximum depth of a tree using this parameter." }, { "code": null, "e": 39350, "s": 39212, "text": "GBoostError: XGBoost Library (libxgboost.dylib) could not be loaded. If you face this error in macOS, run brew install libomp in Terminal" }, { "code": null, "e": 40499, "s": 39350, "text": "from xgboost import XGBClassifieri=1 mean = 0kf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True) for train_index,test_index in kf.split(X,y): print(‘\\n{} of kfold {}’.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = XGBClassifier(n_estimators=50, max_depth=4) model.fit(xtr, ytr) pred_test = model.predict(xvl) score = accuracy_score(yvl,pred_test) mean += score print (‘accuracy_score’,score) i+=1 pred_test = model.predict(test) pred = model.predict_proba(xvl)[:,1]print (‘\\n Mean Validation Accuracy’,mean/(i-1))1 of kfold 5accuracy_score 0.78048780487804882 of kfold 5accuracy_score 0.78861788617886173 of kfold 5accuracy_score 0.76422764227642284 of kfold 5accuracy_score 0.78048780487804885 of kfold 5accuracy_score 0.7622950819672131 Mean Validation Accuracy 0.7752232440357191submission['Loan_Status']=pred_testsubmission['Loan_ID']=test_original['Loan_ID']submission['Loan_Status'].replace(0, 'N', inplace=True)submission['Loan_Status'].replace(1, 'Y', inplace=True)pd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Output/XGBoost.csv')" }, { "code": null, "e": 40605, "s": 40499, "text": "To create an SPSS Modeler Flow and build a machine learning model using it, follow the instructions here:" }, { "code": null, "e": 40623, "s": 40605, "text": "developer.ibm.com" }, { "code": null, "e": 40679, "s": 40623, "text": "Sign-up for an IBM Cloud account to try this tutorial —" }, { "code": null, "e": 40687, "s": 40679, "text": "ibm.biz" } ]
Lodash _.values() Method - GeeksforGeeks
09 Sep, 2020 The _.values() method is used to return the array of the own enumerable string keyed property values of the object. Syntax: _.values(object) Parameters: This method accepts a single parameter as mentioned above and described below: object: This parameter holds the object to query. Return Value: This method returns the array of property values of the object element. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // The source objectvar obj = { Name: "GeeksforGeeks", password: "gfg@1234", username: "your_geeks"} // Use of _.values() method console.log(_.values(obj)); Output: ["GeeksforGeeks", "gfg@1234", "your_geeks"] Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // The source functionfunction Fb() { this.id = 2045; this.username = 'fb_myself'; this.password = 'fb1234';} // This will not get included in values arrayFb.prototype.email = '[email protected]'; // Use of _.values() method console.log(_.values(new Fb)); console.log(_.values('GFG')); Output: [2045, "fb_myself", "fb1234"] ['G', 'F', 'G'] JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25398, "s": 25370, "text": "\n09 Sep, 2020" }, { "code": null, "e": 25514, "s": 25398, "text": "The _.values() method is used to return the array of the own enumerable string keyed property values of the object." }, { "code": null, "e": 25522, "s": 25514, "text": "Syntax:" }, { "code": null, "e": 25540, "s": 25522, "text": "_.values(object)\n" }, { "code": null, "e": 25631, "s": 25540, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 25681, "s": 25631, "text": "object: This parameter holds the object to query." }, { "code": null, "e": 25767, "s": 25681, "text": "Return Value: This method returns the array of property values of the object element." }, { "code": null, "e": 25778, "s": 25767, "text": "Example 1:" }, { "code": null, "e": 25789, "s": 25778, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source objectvar obj = { Name: \"GeeksforGeeks\", password: \"gfg@1234\", username: \"your_geeks\"} // Use of _.values() method console.log(_.values(obj));", "e": 26024, "s": 25789, "text": null }, { "code": null, "e": 26032, "s": 26024, "text": "Output:" }, { "code": null, "e": 26077, "s": 26032, "text": "[\"GeeksforGeeks\", \"gfg@1234\", \"your_geeks\"]\n" }, { "code": null, "e": 26090, "s": 26077, "text": "Example 2: " }, { "code": null, "e": 26101, "s": 26090, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source functionfunction Fb() { this.id = 2045; this.username = 'fb_myself'; this.password = 'fb1234';} // This will not get included in values arrayFb.prototype.email = '[email protected]'; // Use of _.values() method console.log(_.values(new Fb)); console.log(_.values('GFG'));", "e": 26458, "s": 26101, "text": null }, { "code": null, "e": 26466, "s": 26458, "text": "Output:" }, { "code": null, "e": 26513, "s": 26466, "text": "[2045, \"fb_myself\", \"fb1234\"]\n['G', 'F', 'G']\n" }, { "code": null, "e": 26531, "s": 26513, "text": "JavaScript-Lodash" }, { "code": null, "e": 26542, "s": 26531, "text": "JavaScript" }, { "code": null, "e": 26559, "s": 26542, "text": "Web Technologies" }, { "code": null, "e": 26657, "s": 26559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26697, "s": 26657, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26758, "s": 26697, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26799, "s": 26758, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26821, "s": 26799, "text": "JavaScript | Promises" }, { "code": null, "e": 26875, "s": 26821, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26915, "s": 26875, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26948, "s": 26915, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26991, "s": 26948, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27041, "s": 26991, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the sum of all Truncatable primes below N in Python
Suppose we have a given integer N; we have to find the sum of all Truncatable primes less than N. As we know the truncatable prime is a number which is left-truncatable prime (if the leading "left" digit is successively removed, then all resulting numbers are treated as prime) as well as right-truncatable prime (if the last "right" digit is successively removed, then all the resulting numbers are treated as prime). An example of truncatable prime is 9137 as this is lefttruncatable prime because 9137, 137, 37 and 7 are primes. Hence 9137 is a truncatable prime. So, if the input is like N = 55, then the output will be 130 as (2 + 3 + 5 + 7 + 23 + 37 + 53) = To solve this, we will follow these steps − N := 1000005 N := 1000005 prime := a list of size N and fill with True prime := a list of size N and fill with True Define a function sieve() . This will take Define a function sieve() . This will take prime[1] := False, prime[0] := False prime[1] := False, prime[0] := False for i in range 2 to N, doif prime[i] is same as True, thenfor j in range i * 2 to N, update in each step by i, doprime[j] := False for i in range 2 to N, do if prime[i] is same as True, thenfor j in range i * 2 to N, update in each step by i, doprime[j] := False if prime[i] is same as True, then for j in range i * 2 to N, update in each step by i, doprime[j] := False for j in range i * 2 to N, update in each step by i, do prime[j] := False prime[j] := False From the main method, do the following − From the main method, do the following − sum := 0 sum := 0 for i in range 2 to n, docurrent := if := True for i in range 2 to n, do current := i current := i f := True f := True while current is non-zero, doif prime[current] is False, thenf := Falsecome out from the loopcurrent := current / 10 while current is non-zero, do if prime[current] is False, thenf := Falsecome out from the loop if prime[current] is False, then f := False f := False come out from the loop come out from the loop current := current / 10 current := current / 10 current := i current := i power := 10 power := 10 while quotient of (current / power) is non-zero, doif prime[current mod power] is False, thenf := Falsecome out from the looppower := power * 10 while quotient of (current / power) is non-zero, do if prime[current mod power] is False, thenf := Falsecome out from the loop if prime[current mod power] is False, then f := False f := False come out from the loop come out from the loop power := power * 10 power := power * 10 if f is True, thensum := sum + i if f is True, then sum := sum + i sum := sum + i return sum return sum Let us see the following implementation to get better understanding − Live Demo N = 1000005 prime = [True for i in range(N)] def sieve(): prime[1] = False prime[0] = False for i in range(2, N): if (prime[i]==True): for j in range(i * 2, N, i): prime[j] = False def get_total_of_trunc_primes(n): sum = 0 for i in range(2, n): current = i f = True while (current): if (prime[current] == False): f = False break current //= 10 current = i power = 10 while (current // power): if (prime[current % power] == False): f = False break power *= 10 if f: sum += i return sum n = 55 sieve() print(get_total_of_trunc_primes(n)) 55 130
[ { "code": null, "e": 1629, "s": 1062, "text": "Suppose we have a given integer N; we have to find the sum of all Truncatable primes less than N. As we know the truncatable prime is a number which is left-truncatable prime (if the leading \"left\" digit is successively removed, then all resulting numbers are treated as prime) as well as right-truncatable prime (if the last \"right\" digit is successively removed, then all the resulting numbers are treated as prime). An example of truncatable prime is 9137 as this is lefttruncatable prime because 9137, 137, 37 and 7 are primes. Hence 9137 is a truncatable prime." }, { "code": null, "e": 1726, "s": 1629, "text": "So, if the input is like N = 55, then the output will be 130 as (2 + 3 + 5 + 7 + 23 + 37 + 53) =" }, { "code": null, "e": 1770, "s": 1726, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1783, "s": 1770, "text": "N := 1000005" }, { "code": null, "e": 1796, "s": 1783, "text": "N := 1000005" }, { "code": null, "e": 1841, "s": 1796, "text": "prime := a list of size N and fill with True" }, { "code": null, "e": 1886, "s": 1841, "text": "prime := a list of size N and fill with True" }, { "code": null, "e": 1929, "s": 1886, "text": "Define a function sieve() . This will take" }, { "code": null, "e": 1972, "s": 1929, "text": "Define a function sieve() . This will take" }, { "code": null, "e": 2009, "s": 1972, "text": "prime[1] := False, prime[0] := False" }, { "code": null, "e": 2046, "s": 2009, "text": "prime[1] := False, prime[0] := False" }, { "code": null, "e": 2177, "s": 2046, "text": "for i in range 2 to N, doif prime[i] is same as True, thenfor j in range i * 2 to N, update in each step by i, doprime[j] := False" }, { "code": null, "e": 2203, "s": 2177, "text": "for i in range 2 to N, do" }, { "code": null, "e": 2309, "s": 2203, "text": "if prime[i] is same as True, thenfor j in range i * 2 to N, update in each step by i, doprime[j] := False" }, { "code": null, "e": 2343, "s": 2309, "text": "if prime[i] is same as True, then" }, { "code": null, "e": 2416, "s": 2343, "text": "for j in range i * 2 to N, update in each step by i, doprime[j] := False" }, { "code": null, "e": 2472, "s": 2416, "text": "for j in range i * 2 to N, update in each step by i, do" }, { "code": null, "e": 2490, "s": 2472, "text": "prime[j] := False" }, { "code": null, "e": 2508, "s": 2490, "text": "prime[j] := False" }, { "code": null, "e": 2549, "s": 2508, "text": "From the main method, do the following −" }, { "code": null, "e": 2590, "s": 2549, "text": "From the main method, do the following −" }, { "code": null, "e": 2599, "s": 2590, "text": "sum := 0" }, { "code": null, "e": 2608, "s": 2599, "text": "sum := 0" }, { "code": null, "e": 2655, "s": 2608, "text": "for i in range 2 to n, docurrent := if := True" }, { "code": null, "e": 2681, "s": 2655, "text": "for i in range 2 to n, do" }, { "code": null, "e": 2694, "s": 2681, "text": "current := i" }, { "code": null, "e": 2707, "s": 2694, "text": "current := i" }, { "code": null, "e": 2717, "s": 2707, "text": "f := True" }, { "code": null, "e": 2727, "s": 2717, "text": "f := True" }, { "code": null, "e": 2844, "s": 2727, "text": "while current is non-zero, doif prime[current] is False, thenf := Falsecome out from the loopcurrent := current / 10" }, { "code": null, "e": 2874, "s": 2844, "text": "while current is non-zero, do" }, { "code": null, "e": 2939, "s": 2874, "text": "if prime[current] is False, thenf := Falsecome out from the loop" }, { "code": null, "e": 2972, "s": 2939, "text": "if prime[current] is False, then" }, { "code": null, "e": 2983, "s": 2972, "text": "f := False" }, { "code": null, "e": 2994, "s": 2983, "text": "f := False" }, { "code": null, "e": 3017, "s": 2994, "text": "come out from the loop" }, { "code": null, "e": 3040, "s": 3017, "text": "come out from the loop" }, { "code": null, "e": 3064, "s": 3040, "text": "current := current / 10" }, { "code": null, "e": 3088, "s": 3064, "text": "current := current / 10" }, { "code": null, "e": 3101, "s": 3088, "text": "current := i" }, { "code": null, "e": 3114, "s": 3101, "text": "current := i" }, { "code": null, "e": 3126, "s": 3114, "text": "power := 10" }, { "code": null, "e": 3138, "s": 3126, "text": "power := 10" }, { "code": null, "e": 3283, "s": 3138, "text": "while quotient of (current / power) is non-zero, doif prime[current mod power] is False, thenf := Falsecome out from the looppower := power * 10" }, { "code": null, "e": 3335, "s": 3283, "text": "while quotient of (current / power) is non-zero, do" }, { "code": null, "e": 3410, "s": 3335, "text": "if prime[current mod power] is False, thenf := Falsecome out from the loop" }, { "code": null, "e": 3453, "s": 3410, "text": "if prime[current mod power] is False, then" }, { "code": null, "e": 3464, "s": 3453, "text": "f := False" }, { "code": null, "e": 3475, "s": 3464, "text": "f := False" }, { "code": null, "e": 3498, "s": 3475, "text": "come out from the loop" }, { "code": null, "e": 3521, "s": 3498, "text": "come out from the loop" }, { "code": null, "e": 3541, "s": 3521, "text": "power := power * 10" }, { "code": null, "e": 3561, "s": 3541, "text": "power := power * 10" }, { "code": null, "e": 3594, "s": 3561, "text": "if f is True, thensum := sum + i" }, { "code": null, "e": 3613, "s": 3594, "text": "if f is True, then" }, { "code": null, "e": 3628, "s": 3613, "text": "sum := sum + i" }, { "code": null, "e": 3643, "s": 3628, "text": "sum := sum + i" }, { "code": null, "e": 3654, "s": 3643, "text": "return sum" }, { "code": null, "e": 3665, "s": 3654, "text": "return sum" }, { "code": null, "e": 3735, "s": 3665, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3746, "s": 3735, "text": " Live Demo" }, { "code": null, "e": 4414, "s": 3746, "text": "N = 1000005\nprime = [True for i in range(N)]\ndef sieve():\n prime[1] = False\n prime[0] = False\n for i in range(2, N):\n if (prime[i]==True):\n for j in range(i * 2, N, i):\n prime[j] = False\ndef get_total_of_trunc_primes(n):\n sum = 0\n for i in range(2, n):\n current = i\n f = True\n while (current):\n if (prime[current] == False):\n f = False\n break\n current //= 10\n current = i\n power = 10\n while (current // power):\n if (prime[current % power] == False):\n f = False\n break\n power *= 10\n if f:\n sum += i\n return sum\nn = 55\nsieve()\nprint(get_total_of_trunc_primes(n))" }, { "code": null, "e": 4417, "s": 4414, "text": "55" }, { "code": null, "e": 4421, "s": 4417, "text": "130" } ]
rmdir command in Linux With Examples - GeeksforGeeks
24 May, 2019 rmdir command is used remove empty directories from the filesystem in Linux. The rmdir command removes each and every directory specified in the command line only if these directories are empty. So if the specified directory has some directories or files in it then this cannot be removed by rmdir command. Syntax: rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories ... Options: –help: It will print the general syntax of the command along with the various options that can be used with the rmdir command as well as give a brief description about each option. rmdir -p: In this option each of the directory argument is treated as a pathname of which all components will be removed, if they are already empty, starting from the last component. rmdir -v, –verbose: This option displays verbose information for every directory being processed. rmdir –ignore-fail-on-non-empty: This option do not report a failure which occurs solely because a directory is non-empty. Normally, when rmdir is being instructed to remove a non-empty directory, it simply reports an error. This option consists of all those error messages. rmdir –version: This option is used to display the version information and exit. Example 1: This will first remove the child directory and then remove the parent directory. rmdir -p mydir/mydir1 Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are empty. If any of these directories are not empty, then an error message will be printed for that directory, and the other directories will be removed. rmdir mydir1 mydir2 mydir3 Example 3: Remove the directory mydir/mydir1 if it is empty. Then, remove directory mydir, if it is empty after mydir/mydir1 was removed. rmdir mydir/mydir1 mydir linux-command Linux-directory-commands Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples scp command in Linux with Examples ps command in Linux with Examples
[ { "code": null, "e": 24125, "s": 24097, "text": "\n24 May, 2019" }, { "code": null, "e": 24432, "s": 24125, "text": "rmdir command is used remove empty directories from the filesystem in Linux. The rmdir command removes each and every directory specified in the command line only if these directories are empty. So if the specified directory has some directories or files in it then this cannot be removed by rmdir command." }, { "code": null, "e": 24440, "s": 24432, "text": "Syntax:" }, { "code": null, "e": 24511, "s": 24440, "text": "rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories ..." }, { "code": null, "e": 24520, "s": 24511, "text": "Options:" }, { "code": null, "e": 24701, "s": 24520, "text": "–help: It will print the general syntax of the command along with the various options that can be used with the rmdir command as well as give a brief description about each option." }, { "code": null, "e": 24884, "s": 24701, "text": "rmdir -p: In this option each of the directory argument is treated as a pathname of which all components will be removed, if they are already empty, starting from the last component." }, { "code": null, "e": 24982, "s": 24884, "text": "rmdir -v, –verbose: This option displays verbose information for every directory being processed." }, { "code": null, "e": 25257, "s": 24982, "text": "rmdir –ignore-fail-on-non-empty: This option do not report a failure which occurs solely because a directory is non-empty. Normally, when rmdir is being instructed to remove a non-empty directory, it simply reports an error. This option consists of all those error messages." }, { "code": null, "e": 25338, "s": 25257, "text": "rmdir –version: This option is used to display the version information and exit." }, { "code": null, "e": 25430, "s": 25338, "text": "Example 1: This will first remove the child directory and then remove the parent directory." }, { "code": null, "e": 25452, "s": 25430, "text": "rmdir -p mydir/mydir1" }, { "code": null, "e": 25677, "s": 25452, "text": "Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are empty. If any of these directories are not empty, then an error message will be printed for that directory, and the other directories will be removed." }, { "code": null, "e": 25704, "s": 25677, "text": "rmdir mydir1 mydir2 mydir3" }, { "code": null, "e": 25842, "s": 25704, "text": "Example 3: Remove the directory mydir/mydir1 if it is empty. Then, remove directory mydir, if it is empty after mydir/mydir1 was removed." }, { "code": null, "e": 25867, "s": 25842, "text": "rmdir mydir/mydir1 mydir" }, { "code": null, "e": 25881, "s": 25867, "text": "linux-command" }, { "code": null, "e": 25906, "s": 25881, "text": "Linux-directory-commands" }, { "code": null, "e": 25926, "s": 25906, "text": "Linux-file-commands" }, { "code": null, "e": 25937, "s": 25926, "text": "Linux-Unix" }, { "code": null, "e": 26035, "s": 25937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26070, "s": 26035, "text": "tar command in Linux with examples" }, { "code": null, "e": 26106, "s": 26070, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26144, "s": 26106, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 26180, "s": 26144, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26218, "s": 26180, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26253, "s": 26218, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26290, "s": 26253, "text": "touch command in Linux with Examples" }, { "code": null, "e": 26326, "s": 26290, "text": "echo command in Linux with Examples" }, { "code": null, "e": 26361, "s": 26326, "text": "scp command in Linux with Examples" } ]
Python Digital Mobile Device Forensics
This chapter will explain Python digital forensics on mobile devices and the concepts involved. Mobile device forensics is that branch of digital forensics which deals with the acquisition and analysis of mobile devices to recover digital evidences of investigative interest. This branch is different from computer forensics because mobile devices have an inbuilt communication system which is useful for providing useful information related to location. Though the use of smartphones is increasing in digital forensics day-by-day, still it is considered to be non-standard due to its heterogeneity. On the other hand, computer hardware, such as hard disk, is considered to be standard and developed as a stable discipline too. In digital forensic industry, there is a lot of debate on the techniques used for non-standards devices, having transient evidences, such as smartphones. Modern mobile devices possess lot of digital information in comparison with the older phones having only a call log or SMS messages. Thus, mobile devices can supply investigators with lots of insights about its user. Some artifacts that can be extracted from mobile devices are as mentioned below − Messages − These are the useful artifacts which can reveal the state of mind of the owner and can even give some previous unknown information to the investigator. Messages − These are the useful artifacts which can reveal the state of mind of the owner and can even give some previous unknown information to the investigator. Location History− The location history data is a useful artifact which can be used by investigators to validate about the particular location of a person. Location History− The location history data is a useful artifact which can be used by investigators to validate about the particular location of a person. Applications Installed − By accessing the kind of applications installed, investigator get some insight into the habits and thinking of the mobile user. Applications Installed − By accessing the kind of applications installed, investigator get some insight into the habits and thinking of the mobile user. Smartphones have SQLite databases and PLIST files as the major sources of evidences. In this section we are going to process the sources of evidences in python. A PLIST (Property List) is a flexible and convenient format for storing application data especially on iPhone devices. It uses the extension .plist. Such kind of files used to store information about bundles and applications. It can be in two formats: XML and binary. The following Python code will open and read PLIST file. Note that before proceeding into this, we must create our own Info.plist file. First, install a third party library named biplist by the following command − Pip install biplist Now, import some useful libraries to process plist files − import biplist import os import sys Now, use the following command under main method can be used to read plist file into a variable − def main(plist): try: data = biplist.readPlist(plist) except (biplist.InvalidPlistException,biplist.NotBinaryPlistException) as e: print("[-] Invalid PLIST file - unable to be opened by biplist") sys.exit(1) Now, we can either read the data on the console or directly print it, from this variable. SQLite serves as the primary data repository on mobile devices. SQLite an in-process library that implements a self-contained, server-less, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, you need not configure it in your system, unlike other databases. If you are a novice or unfamiliar with SQLite databases, you can follow the link www.tutorialspoint.com/sqlite/index.htm Additionally, you can follow the link www.tutorialspoint.com/sqlite/sqlite_python.htm in case you want to get into detail of SQLite with Python. During mobile forensics, we can interact with the sms.db file of a mobile device and can extract valuable information from message table. Python has a built in library named sqlite3 for connecting with SQLite database. You can import the same with the following command − import sqlite3 Now, with the help of following command, we can connect with the database, say sms.db in case of mobile devices − Conn = sqlite3.connect(‘sms.db’) C = conn.cursor() Here, C is the cursor object with the help of which we can interact with the database. Now, suppose if we want to execute a particular command, say to get the details from the abc table, it can be done with the help of following command − c.execute(“Select * from abc”) c.close() The result of the above command would be stored in the cursor object. Similarly we can use fetchall() method to dump the result into a variable we can manipulate. We can use the following command to get column names data of message table in sms.db − c.execute(“pragma table_info(message)”) table_data = c.fetchall() columns = [x[1] for x in table_data Observe that here we are using SQLite PRAGMA command which is special command to be used to control various environmental variables and state flags within SQLite environment. In the above command, the fetchall() method returns a tuple of results. Each column’s name is stored in the first index of each tuple. Now, with the help of following command we can query the table for all of its data and store it in the variable named data_msg − c.execute(“Select * from message”) data_msg = c.fetchall() The above command will store the data in the variable and further we can also write the above data in CSV file by using csv.writer() method. iPhone mobile forensics can be performed on the backups made by iTunes. Forensic examiners rely on analyzing the iPhone logical backups acquired through iTunes. AFC (Apple file connection) protocol is used by iTunes to take the backup. Besides, the backup process does not modify anything on the iPhone except the escrow key records. Now, the question arises that why it is important for a digital forensic expert to understand the techniques on iTunes backups? It is important in case we get access to the suspect’s computer instead of iPhone directly because when a computer is used to sync with iPhone, then most of the information on iPhone is likely to be backed up on the computer. Whenever an Apple product is backed up to the computer, it is in sync with iTunes and there will be a specific folder with device’s unique ID. In the latest backup format, the files are stored in subfolders containing the first two hexadecimal characters of the file name. From these back up files, there are some files like info.plist which are useful along with the database named Manifest.db. The following table shows the backup locations, that vary with operating systems of iTunes backups − For processing the iTunes backup with Python, we need to first identify all the backups in backup location as per our operating system. Then we will iterate through each backup and read the database Manifest.db. Now, with the help of following Python code we can do the same − First, import the necessary libraries as follows − from __future__ import print_function import argparse import logging import os from shutil import copyfile import sqlite3 import sys logger = logging.getLogger(__name__) Now, provide two positional arguments namely INPUT_DIR and OUTPUT_DIR which is representing iTunes backup and desired output folder − if __name__ == "__main__": parser.add_argument("INPUT_DIR",help = "Location of folder containing iOS backups, ""e.g. ~\Library\Application Support\MobileSync\Backup folder") parser.add_argument("OUTPUT_DIR", help = "Output Directory") parser.add_argument("-l", help = "Log file path",default = __file__[:-2] + "log") parser.add_argument("-v", help = "Increase verbosity",action = "store_true") args = parser.parse_args() Now, setup the log as follows − if args.v: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) Now, setup the message format for this log as follows − msg_fmt = logging.Formatter("%(asctime)-15s %(funcName)-13s""%(levelname)-8s %(message)s") strhndl = logging.StreamHandler(sys.stderr) strhndl.setFormatter(fmt = msg_fmt) fhndl = logging.FileHandler(args.l, mode = 'a') fhndl.setFormatter(fmt = msg_fmt) logger.addHandler(strhndl) logger.addHandler(fhndl) logger.info("Starting iBackup Visualizer") logger.debug("Supplied arguments: {}".format(" ".join(sys.argv[1:]))) logger.debug("System: " + sys.platform) logger.debug("Python Version: " + sys.version) The following line of code will create necessary folders for the desired output directory by using os.makedirs() function − if not os.path.exists(args.OUTPUT_DIR): os.makedirs(args.OUTPUT_DIR) Now, pass the supplied input and output directories to the main() function as follows − if os.path.exists(args.INPUT_DIR) and os.path.isdir(args.INPUT_DIR): main(args.INPUT_DIR, args.OUTPUT_DIR) else: logger.error("Supplied input directory does not exist or is not ""a directory") sys.exit(1) Now, write main() function which will further call backup_summary() function to identify all the backups present in input folder − def main(in_dir, out_dir): backups = backup_summary(in_dir) def backup_summary(in_dir): logger.info("Identifying all iOS backups in {}".format(in_dir)) root = os.listdir(in_dir) backups = {} for x in root: temp_dir = os.path.join(in_dir, x) if os.path.isdir(temp_dir) and len(x) == 40: num_files = 0 size = 0 for root, subdir, files in os.walk(temp_dir): num_files += len(files) size += sum(os.path.getsize(os.path.join(root, name)) for name in files) backups[x] = [temp_dir, num_files, size] return backups Now, print the summary of each backup to the console as follows − print("Backup Summary") print("=" * 20) if len(backups) > 0: for i, b in enumerate(backups): print("Backup No.: {} \n""Backup Dev. Name: {} \n""# Files: {} \n""Backup Size (Bytes): {}\n".format(i, b, backups[b][1], backups[b][2])) Now, dump the contents of the Manifest.db file to the variable named db_items. try: db_items = process_manifest(backups[b][0]) except IOError: logger.warn("Non-iOS 10 backup encountered or " "invalid backup. Continuing to next backup.") continue Now, let us define a function that will take the directory path of the backup − def process_manifest(backup): manifest = os.path.join(backup, "Manifest.db") if not os.path.exists(manifest): logger.error("Manifest DB not found in {}".format(manifest)) raise IOError Now, using SQLite3 we will connect to the database by cursor named c − c = conn.cursor() items = {} for row in c.execute("SELECT * from Files;"): items[row[0]] = [row[2], row[1], row[3]] return items create_files(in_dir, out_dir, b, db_items) print("=" * 20) else: logger.warning("No valid backups found. The input directory should be " "the parent-directory immediately above the SHA-1 hash " "iOS device backups") sys.exit(2) Now, define the create_files() method as follows − def create_files(in_dir, out_dir, b, db_items): msg = "Copying Files for backup {} to {}".format(b, os.path.join(out_dir, b)) logger.info(msg) Now, iterate through each key in the db_items dictionary − for x, key in enumerate(db_items): if db_items[key][0] is None or db_items[key][0] == "": continue else: dirpath = os.path.join(out_dir, b, os.path.dirname(db_items[key][0])) filepath = os.path.join(out_dir, b, db_items[key][0]) if not os.path.exists(dirpath): os.makedirs(dirpath) original_dir = b + "/" + key[0:2] + "/" + key path = os.path.join(in_dir, original_dir) if os.path.exists(filepath): filepath = filepath + "_{}".format(x) Now, use shutil.copyfile() method to copy the backed-up file as follows − try: copyfile(path, filepath) except IOError: logger.debug("File not found in backup: {}".format(path)) files_not_found += 1 if files_not_found > 0: logger.warning("{} files listed in the Manifest.db not" "found in backup".format(files_not_found)) copyfile(os.path.join(in_dir, b, "Info.plist"), os.path.join(out_dir, b, "Info.plist")) copyfile(os.path.join(in_dir, b, "Manifest.db"), os.path.join(out_dir, b, "Manifest.db")) copyfile(os.path.join(in_dir, b, "Manifest.plist"), os.path.join(out_dir, b, "Manifest.plist")) copyfile(os.path.join(in_dir, b, "Status.plist"),os.path.join(out_dir, b, "Status.plist")) With the above Python script, we can get the updated back up file structure in our output folder. We can use pycrypto python library to decrypt the backups. Mobile devices can be used to connect to the outside world by connecting through Wi-Fi networks which are available everywhere. Sometimes the device gets connected to these open networks automatically. In case of iPhone, the list of open Wi-Fi connections with which the device has got connected is stored in a PLIST file named com.apple.wifi.plist. This file will contain the Wi-Fi SSID, BSSID and connection time. We need to extract Wi-Fi details from standard Cellebrite XML report using Python. For this, we need to use API from Wireless Geographic Logging Engine (WIGLE), a popular platform which can be used for finding the location of a device using the names of Wi-Fi networks. We can use Python library named requests to access the API from WIGLE. It can be installed as follows − pip install requests We need to register on WIGLE’s website https://wigle.net/account to get a free API from WIGLE. The Python script for getting the information about user device and its connection through WIGEL’s API is discussed below − First, import the following libraries for handling different things − from __future__ import print_function import argparse import csv import os import sys import xml.etree.ElementTree as ET import requests Now, provide two positional arguments namely INPUT_FILE and OUTPUT_CSV which will represent the input file with Wi-Fi MAC address and the desired output CSV file respectively − if __name__ == "__main__": parser.add_argument("INPUT_FILE", help = "INPUT FILE with MAC Addresses") parser.add_argument("OUTPUT_CSV", help = "Output CSV File") parser.add_argument("-t", help = "Input type: Cellebrite XML report or TXT file",choices = ('xml', 'txt'), default = "xml") parser.add_argument('--api', help = "Path to API key file",default = os.path.expanduser("~/.wigle_api"), type = argparse.FileType('r')) args = parser.parse_args() Now following lines of code will check if the input file exists and is a file. If not, it exits the script − if not os.path.exists(args.INPUT_FILE) or \ not os.path.isfile(args.INPUT_FILE): print("[-] {} does not exist or is not a file".format(args.INPUT_FILE)) sys.exit(1) directory = os.path.dirname(args.OUTPUT_CSV) if directory != '' and not os.path.exists(directory): os.makedirs(directory) api_key = args.api.readline().strip().split(":") Now, pass the argument to main as follows − main(args.INPUT_FILE, args.OUTPUT_CSV, args.t, api_key) def main(in_file, out_csv, type, api_key): if type == 'xml': wifi = parse_xml(in_file) else: wifi = parse_txt(in_file) query_wigle(wifi, out_csv, api_key) Now, we will parse the XML file as follows − def parse_xml(xml_file): wifi = {} xmlns = "{http://pa.cellebrite.com/report/2.0}" print("[+] Opening {} report".format(xml_file)) xml_tree = ET.parse(xml_file) print("[+] Parsing report for all connected WiFi addresses") root = xml_tree.getroot() Now, iterate through the child element of the root as follows − for child in root.iter(): if child.tag == xmlns + "model": if child.get("type") == "Location": for field in child.findall(xmlns + "field"): if field.get("name") == "TimeStamp": ts_value = field.find(xmlns + "value") try: ts = ts_value.text except AttributeError: continue Now, we will check that ‘ssid’ string is present in the value’s text or not − if "SSID" in value.text: bssid, ssid = value.text.split("\t") bssid = bssid[7:] ssid = ssid[6:] Now, we need to add BSSID, SSID and timestamp to the wifi dictionary as follows − if bssid in wifi.keys(): wifi[bssid]["Timestamps"].append(ts) wifi[bssid]["SSID"].append(ssid) else: wifi[bssid] = {"Timestamps": [ts], "SSID": [ssid],"Wigle": {}} return wifi The text parser which is much simpler that XML parser is shown below − def parse_txt(txt_file): wifi = {} print("[+] Extracting MAC addresses from {}".format(txt_file)) with open(txt_file) as mac_file: for line in mac_file: wifi[line.strip()] = {"Timestamps": ["N/A"], "SSID": ["N/A"],"Wigle": {}} return wifi Now, let us use requests module to make WIGLE APIcalls and need to move on to the query_wigle() method − def query_wigle(wifi_dictionary, out_csv, api_key): print("[+] Querying Wigle.net through Python API for {} " "APs".format(len(wifi_dictionary))) for mac in wifi_dictionary: wigle_results = query_mac_addr(mac, api_key) def query_mac_addr(mac_addr, api_key): query_url = "https://api.wigle.net/api/v2/network/search?" \ "onlymine = false&freenet = false&paynet = false" \ "&netid = {}".format(mac_addr) req = requests.get(query_url, auth = (api_key[0], api_key[1])) return req.json() Actually there is a limit per day for WIGLE API calls, if that limit exceeds then it must show an error as follows − try: if wigle_results["resultCount"] == 0: wifi_dictionary[mac]["Wigle"]["results"] = [] continue else: wifi_dictionary[mac]["Wigle"] = wigle_results except KeyError: if wigle_results["error"] == "too many queries today": print("[-] Wigle daily query limit exceeded") wifi_dictionary[mac]["Wigle"]["results"] = [] continue else: print("[-] Other error encountered for " "address {}: {}".format(mac, wigle_results['error'])) wifi_dictionary[mac]["Wigle"]["results"] = [] continue prep_output(out_csv, wifi_dictionary) Now, we will use prep_output() method to flattens the dictionary into easily writable chunks − def prep_output(output, data): csv_data = {} google_map = https://www.google.com/maps/search/ Now, access all the data we have collected so far as follows − for x, mac in enumerate(data): for y, ts in enumerate(data[mac]["Timestamps"]): for z, result in enumerate(data[mac]["Wigle"]["results"]): shortres = data[mac]["Wigle"]["results"][z] g_map_url = "{}{},{}".format(google_map, shortres["trilat"],shortres["trilong"]) Now, we can write the output in CSV file as we have done in earlier scripts in this chapter by using write_csv() function. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2049, "s": 1953, "text": "This chapter will explain Python digital forensics on mobile devices and the concepts involved." }, { "code": null, "e": 2408, "s": 2049, "text": "Mobile device forensics is that branch of digital forensics which deals with the acquisition and analysis of mobile devices to recover digital evidences of investigative interest. This branch is different from computer forensics because mobile devices have an inbuilt communication system which is useful for providing useful information related to location." }, { "code": null, "e": 2835, "s": 2408, "text": "Though the use of smartphones is increasing in digital forensics day-by-day, still it is considered to be non-standard due to its heterogeneity. On the other hand, computer hardware, such as hard disk, is considered to be standard and developed as a stable discipline too. In digital forensic industry, there is a lot of debate on the techniques used for non-standards devices, having transient evidences, such as smartphones." }, { "code": null, "e": 3134, "s": 2835, "text": "Modern mobile devices possess lot of digital information in comparison with the older phones having only a call log or SMS messages. Thus, mobile devices can supply investigators with lots of insights about its user. Some artifacts that can be extracted from mobile devices are as mentioned below −" }, { "code": null, "e": 3297, "s": 3134, "text": "Messages − These are the useful artifacts which can reveal the state of mind of the owner and can even give some previous unknown information to the investigator." }, { "code": null, "e": 3460, "s": 3297, "text": "Messages − These are the useful artifacts which can reveal the state of mind of the owner and can even give some previous unknown information to the investigator." }, { "code": null, "e": 3615, "s": 3460, "text": "Location History− The location history data is a useful artifact which can be used by investigators to validate about the particular location of a person." }, { "code": null, "e": 3770, "s": 3615, "text": "Location History− The location history data is a useful artifact which can be used by investigators to validate about the particular location of a person." }, { "code": null, "e": 3923, "s": 3770, "text": "Applications Installed − By accessing the kind of applications installed, investigator get some insight into the habits and thinking of the mobile user." }, { "code": null, "e": 4076, "s": 3923, "text": "Applications Installed − By accessing the kind of applications installed, investigator get some insight into the habits and thinking of the mobile user." }, { "code": null, "e": 4237, "s": 4076, "text": "Smartphones have SQLite databases and PLIST files as the major sources of evidences. In this section we are going to process the sources of evidences in python." }, { "code": null, "e": 4641, "s": 4237, "text": "A PLIST (Property List) is a flexible and convenient format for storing application data especially on iPhone devices. It uses the extension .plist. Such kind of files used to store information about bundles and applications. It can be in two formats: XML and binary. The following Python code will open and read PLIST file. Note that before proceeding into this, we must create our own Info.plist file." }, { "code": null, "e": 4719, "s": 4641, "text": "First, install a third party library named biplist by the following command −" }, { "code": null, "e": 4740, "s": 4719, "text": "Pip install biplist\n" }, { "code": null, "e": 4799, "s": 4740, "text": "Now, import some useful libraries to process plist files −" }, { "code": null, "e": 4835, "s": 4799, "text": "import biplist\nimport os\nimport sys" }, { "code": null, "e": 4933, "s": 4835, "text": "Now, use the following command under main method can be used to read plist file into a variable −" }, { "code": null, "e": 5153, "s": 4933, "text": "def main(plist):\n try:\n data = biplist.readPlist(plist)\n except (biplist.InvalidPlistException,biplist.NotBinaryPlistException) as e:\nprint(\"[-] Invalid PLIST file - unable to be opened by biplist\")\nsys.exit(1)" }, { "code": null, "e": 5243, "s": 5153, "text": "Now, we can either read the data on the console or directly print it, from this variable." }, { "code": null, "e": 5548, "s": 5243, "text": "SQLite serves as the primary data repository on mobile devices. SQLite an in-process library that implements a self-contained, server-less, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, you need not configure it in your system, unlike other databases." }, { "code": null, "e": 5814, "s": 5548, "text": "If you are a novice or unfamiliar with SQLite databases, you can follow the link www.tutorialspoint.com/sqlite/index.htm Additionally, you can follow the link www.tutorialspoint.com/sqlite/sqlite_python.htm in case you want to get into detail of SQLite with Python." }, { "code": null, "e": 6086, "s": 5814, "text": "During mobile forensics, we can interact with the sms.db file of a mobile device and can extract valuable information from message table. Python has a built in library named sqlite3 for connecting with SQLite database. You can import the same with the following command −" }, { "code": null, "e": 6102, "s": 6086, "text": "import sqlite3\n" }, { "code": null, "e": 6216, "s": 6102, "text": "Now, with the help of following command, we can connect with the database, say sms.db in case of mobile devices −" }, { "code": null, "e": 6267, "s": 6216, "text": "Conn = sqlite3.connect(‘sms.db’)\nC = conn.cursor()" }, { "code": null, "e": 6354, "s": 6267, "text": "Here, C is the cursor object with the help of which we can interact with the database." }, { "code": null, "e": 6506, "s": 6354, "text": "Now, suppose if we want to execute a particular command, say to get the details from the abc table, it can be done with the help of following command −" }, { "code": null, "e": 6547, "s": 6506, "text": "c.execute(“Select * from abc”)\nc.close()" }, { "code": null, "e": 6710, "s": 6547, "text": "The result of the above command would be stored in the cursor object. Similarly we can use fetchall() method to dump the result into a variable we can manipulate." }, { "code": null, "e": 6797, "s": 6710, "text": "We can use the following command to get column names data of message table in sms.db −" }, { "code": null, "e": 6899, "s": 6797, "text": "c.execute(“pragma table_info(message)”)\ntable_data = c.fetchall()\ncolumns = [x[1] for x in table_data" }, { "code": null, "e": 7209, "s": 6899, "text": "Observe that here we are using SQLite PRAGMA command which is special command to be used to control various environmental variables and state flags within SQLite environment. In the above command, the fetchall() method returns a tuple of results. Each column’s name is stored in the first index of each tuple." }, { "code": null, "e": 7338, "s": 7209, "text": "Now, with the help of following command we can query the table for all of its data and store it in the variable named data_msg −" }, { "code": null, "e": 7397, "s": 7338, "text": "c.execute(“Select * from message”)\ndata_msg = c.fetchall()" }, { "code": null, "e": 7538, "s": 7397, "text": "The above command will store the data in the variable and further we can also write the above data in CSV file by using csv.writer() method." }, { "code": null, "e": 7872, "s": 7538, "text": "iPhone mobile forensics can be performed on the backups made by iTunes. Forensic examiners rely on analyzing the iPhone logical backups acquired through iTunes. AFC (Apple file connection) protocol is used by iTunes to take the backup. Besides, the backup process does not modify anything on the iPhone except the escrow key records." }, { "code": null, "e": 8226, "s": 7872, "text": "Now, the question arises that why it is important for a digital forensic expert to understand the techniques on iTunes backups? It is important in case we get access to the suspect’s computer instead of iPhone directly because when a computer is used to sync with iPhone, then most of the information on iPhone is likely to be backed up on the computer." }, { "code": null, "e": 8723, "s": 8226, "text": "Whenever an Apple product is backed up to the computer, it is in sync with iTunes and there will be a specific folder with device’s unique ID. In the latest backup format, the files are stored in subfolders containing the first two hexadecimal characters of the file name. From these back up files, there are some files like info.plist which are useful along with the database named Manifest.db. The following table shows the backup locations, that vary with operating systems of iTunes backups −" }, { "code": null, "e": 8935, "s": 8723, "text": "For processing the iTunes backup with Python, we need to first identify all the backups in backup location as per our operating system. Then we will iterate through each backup and read the database Manifest.db." }, { "code": null, "e": 9000, "s": 8935, "text": "Now, with the help of following Python code we can do the same −" }, { "code": null, "e": 9051, "s": 9000, "text": "First, import the necessary libraries as follows −" }, { "code": null, "e": 9222, "s": 9051, "text": "from __future__ import print_function\nimport argparse\nimport logging\nimport os\n\nfrom shutil import copyfile\nimport sqlite3\nimport sys\nlogger = logging.getLogger(__name__)" }, { "code": null, "e": 9356, "s": 9222, "text": "Now, provide two positional arguments namely INPUT_DIR and OUTPUT_DIR which is representing iTunes backup and desired output folder −" }, { "code": null, "e": 9789, "s": 9356, "text": "if __name__ == \"__main__\":\n parser.add_argument(\"INPUT_DIR\",help = \"Location of folder containing iOS backups, \"\"e.g. ~\\Library\\Application Support\\MobileSync\\Backup folder\")\n parser.add_argument(\"OUTPUT_DIR\", help = \"Output Directory\")\n parser.add_argument(\"-l\", help = \"Log file path\",default = __file__[:-2] + \"log\")\n parser.add_argument(\"-v\", help = \"Increase verbosity\",action = \"store_true\") args = parser.parse_args()" }, { "code": null, "e": 9821, "s": 9789, "text": "Now, setup the log as follows −" }, { "code": null, "e": 9905, "s": 9821, "text": "if args.v:\n logger.setLevel(logging.DEBUG)\nelse:\n logger.setLevel(logging.INFO)" }, { "code": null, "e": 9961, "s": 9905, "text": "Now, setup the message format for this log as follows −" }, { "code": null, "e": 10468, "s": 9961, "text": "msg_fmt = logging.Formatter(\"%(asctime)-15s %(funcName)-13s\"\"%(levelname)-8s %(message)s\")\nstrhndl = logging.StreamHandler(sys.stderr)\nstrhndl.setFormatter(fmt = msg_fmt)\n\nfhndl = logging.FileHandler(args.l, mode = 'a')\nfhndl.setFormatter(fmt = msg_fmt)\n\nlogger.addHandler(strhndl)\nlogger.addHandler(fhndl)\nlogger.info(\"Starting iBackup Visualizer\")\nlogger.debug(\"Supplied arguments: {}\".format(\" \".join(sys.argv[1:])))\nlogger.debug(\"System: \" + sys.platform)\nlogger.debug(\"Python Version: \" + sys.version)" }, { "code": null, "e": 10592, "s": 10468, "text": "The following line of code will create necessary folders for the desired output directory by using os.makedirs() function −" }, { "code": null, "e": 10664, "s": 10592, "text": "if not os.path.exists(args.OUTPUT_DIR):\n os.makedirs(args.OUTPUT_DIR)" }, { "code": null, "e": 10752, "s": 10664, "text": "Now, pass the supplied input and output directories to the main() function as follows −" }, { "code": null, "e": 10966, "s": 10752, "text": "if os.path.exists(args.INPUT_DIR) and os.path.isdir(args.INPUT_DIR):\n main(args.INPUT_DIR, args.OUTPUT_DIR)\nelse:\n logger.error(\"Supplied input directory does not exist or is not \"\"a directory\")\n sys.exit(1)" }, { "code": null, "e": 11097, "s": 10966, "text": "Now, write main() function which will further call backup_summary() function to identify all the backups present in input folder −" }, { "code": null, "e": 11724, "s": 11097, "text": "def main(in_dir, out_dir):\n backups = backup_summary(in_dir)\ndef backup_summary(in_dir):\n logger.info(\"Identifying all iOS backups in {}\".format(in_dir))\n root = os.listdir(in_dir)\n backups = {}\n \n for x in root:\n temp_dir = os.path.join(in_dir, x)\n if os.path.isdir(temp_dir) and len(x) == 40:\n num_files = 0\n size = 0\n \n for root, subdir, files in os.walk(temp_dir):\n num_files += len(files)\n size += sum(os.path.getsize(os.path.join(root, name))\n for name in files)\n backups[x] = [temp_dir, num_files, size]\n return backups" }, { "code": null, "e": 11790, "s": 11724, "text": "Now, print the summary of each backup to the console as follows −" }, { "code": null, "e": 12031, "s": 11790, "text": "print(\"Backup Summary\")\nprint(\"=\" * 20)\n\nif len(backups) > 0:\n for i, b in enumerate(backups):\n print(\"Backup No.: {} \\n\"\"Backup Dev. Name: {} \\n\"\"# Files: {} \\n\"\"Backup Size (Bytes): {}\\n\".format(i, b, backups[b][1], backups[b][2]))" }, { "code": null, "e": 12110, "s": 12031, "text": "Now, dump the contents of the Manifest.db file to the variable named db_items." }, { "code": null, "e": 12289, "s": 12110, "text": "try:\n db_items = process_manifest(backups[b][0])\n except IOError:\n logger.warn(\"Non-iOS 10 backup encountered or \" \"invalid backup. Continuing to next backup.\")\ncontinue" }, { "code": null, "e": 12369, "s": 12289, "text": "Now, let us define a function that will take the directory path of the backup −" }, { "code": null, "e": 12576, "s": 12369, "text": "def process_manifest(backup):\n manifest = os.path.join(backup, \"Manifest.db\")\n \n if not os.path.exists(manifest):\n logger.error(\"Manifest DB not found in {}\".format(manifest))\n raise IOError" }, { "code": null, "e": 12647, "s": 12576, "text": "Now, using SQLite3 we will connect to the database by cursor named c −" }, { "code": null, "e": 13027, "s": 12647, "text": "c = conn.cursor()\nitems = {}\n\nfor row in c.execute(\"SELECT * from Files;\"):\n items[row[0]] = [row[2], row[1], row[3]]\nreturn items\n\ncreate_files(in_dir, out_dir, b, db_items)\n print(\"=\" * 20)\nelse:\n logger.warning(\"No valid backups found. The input directory should be\n \" \"the parent-directory immediately above the SHA-1 hash \" \"iOS device backups\")\n sys.exit(2)" }, { "code": null, "e": 13078, "s": 13027, "text": "Now, define the create_files() method as follows −" }, { "code": null, "e": 13227, "s": 13078, "text": "def create_files(in_dir, out_dir, b, db_items):\n msg = \"Copying Files for backup {} to {}\".format(b, os.path.join(out_dir, b))\n logger.info(msg)" }, { "code": null, "e": 13286, "s": 13227, "text": "Now, iterate through each key in the db_items dictionary −" }, { "code": null, "e": 13779, "s": 13286, "text": "for x, key in enumerate(db_items):\n if db_items[key][0] is None or db_items[key][0] == \"\":\n continue\n else:\n dirpath = os.path.join(out_dir, b,\nos.path.dirname(db_items[key][0]))\n filepath = os.path.join(out_dir, b, db_items[key][0])\n \n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n original_dir = b + \"/\" + key[0:2] + \"/\" + key\n path = os.path.join(in_dir, original_dir)\n \n if os.path.exists(filepath):\n filepath = filepath + \"_{}\".format(x)" }, { "code": null, "e": 13853, "s": 13779, "text": "Now, use shutil.copyfile() method to copy the backed-up file as follows −" }, { "code": null, "e": 14508, "s": 13853, "text": "try:\n copyfile(path, filepath)\n except IOError:\n logger.debug(\"File not found in backup: {}\".format(path))\n files_not_found += 1\n if files_not_found > 0:\n logger.warning(\"{} files listed in the Manifest.db not\" \"found in\nbackup\".format(files_not_found))\n copyfile(os.path.join(in_dir, b, \"Info.plist\"), os.path.join(out_dir, b,\n\"Info.plist\"))\n copyfile(os.path.join(in_dir, b, \"Manifest.db\"), os.path.join(out_dir, b,\n\"Manifest.db\"))\n copyfile(os.path.join(in_dir, b, \"Manifest.plist\"), os.path.join(out_dir, b,\n\"Manifest.plist\"))\n copyfile(os.path.join(in_dir, b, \"Status.plist\"),os.path.join(out_dir, b,\n\"Status.plist\"))" }, { "code": null, "e": 14665, "s": 14508, "text": "With the above Python script, we can get the updated back up file structure in our output folder. We can use pycrypto python library to decrypt the backups." }, { "code": null, "e": 14867, "s": 14665, "text": "Mobile devices can be used to connect to the outside world by connecting through Wi-Fi networks which are available everywhere. Sometimes the device gets connected to these open networks automatically." }, { "code": null, "e": 15081, "s": 14867, "text": "In case of iPhone, the list of open Wi-Fi connections with which the device has got connected is stored in a PLIST file named com.apple.wifi.plist. This file will contain the Wi-Fi SSID, BSSID and connection time." }, { "code": null, "e": 15351, "s": 15081, "text": "We need to extract Wi-Fi details from standard Cellebrite XML report using Python. For this, we need to use API from Wireless Geographic Logging Engine (WIGLE), a popular platform which can be used for finding the location of a device using the names of Wi-Fi networks." }, { "code": null, "e": 15455, "s": 15351, "text": "We can use Python library named requests to access the API from WIGLE. It can be installed as follows −" }, { "code": null, "e": 15477, "s": 15455, "text": "pip install requests\n" }, { "code": null, "e": 15696, "s": 15477, "text": "We need to register on WIGLE’s website https://wigle.net/account to get a free API from WIGLE. The Python script for getting the information about user device and its connection through WIGEL’s API is discussed below −" }, { "code": null, "e": 15766, "s": 15696, "text": "First, import the following libraries for handling different things −" }, { "code": null, "e": 15904, "s": 15766, "text": "from __future__ import print_function\n\nimport argparse\nimport csv\nimport os\nimport sys\nimport xml.etree.ElementTree as ET\nimport requests" }, { "code": null, "e": 16081, "s": 15904, "text": "Now, provide two positional arguments namely INPUT_FILE and OUTPUT_CSV which will represent the input file with Wi-Fi MAC address and the desired output CSV file respectively −" }, { "code": null, "e": 16550, "s": 16081, "text": "if __name__ == \"__main__\":\n parser.add_argument(\"INPUT_FILE\", help = \"INPUT FILE with MAC Addresses\")\n parser.add_argument(\"OUTPUT_CSV\", help = \"Output CSV File\")\n parser.add_argument(\"-t\", help = \"Input type: Cellebrite XML report or TXT\nfile\",choices = ('xml', 'txt'), default = \"xml\")\n parser.add_argument('--api', help = \"Path to API key\n file\",default = os.path.expanduser(\"~/.wigle_api\"),\n type = argparse.FileType('r'))\n args = parser.parse_args()" }, { "code": null, "e": 16659, "s": 16550, "text": "Now following lines of code will check if the input file exists and is a file. If not, it exits the script −" }, { "code": null, "e": 17004, "s": 16659, "text": "if not os.path.exists(args.INPUT_FILE) or \\ not os.path.isfile(args.INPUT_FILE):\n print(\"[-] {} does not exist or is not a\nfile\".format(args.INPUT_FILE))\n sys.exit(1)\ndirectory = os.path.dirname(args.OUTPUT_CSV)\nif directory != '' and not os.path.exists(directory):\n os.makedirs(directory)\napi_key = args.api.readline().strip().split(\":\")" }, { "code": null, "e": 17048, "s": 17004, "text": "Now, pass the argument to main as follows −" }, { "code": null, "e": 17277, "s": 17048, "text": "main(args.INPUT_FILE, args.OUTPUT_CSV, args.t, api_key)\ndef main(in_file, out_csv, type, api_key):\n if type == 'xml':\n wifi = parse_xml(in_file)\n else:\n wifi = parse_txt(in_file)\nquery_wigle(wifi, out_csv, api_key)" }, { "code": null, "e": 17322, "s": 17277, "text": "Now, we will parse the XML file as follows −" }, { "code": null, "e": 17596, "s": 17322, "text": "def parse_xml(xml_file):\n wifi = {}\n xmlns = \"{http://pa.cellebrite.com/report/2.0}\"\n print(\"[+] Opening {} report\".format(xml_file))\n \n xml_tree = ET.parse(xml_file)\n print(\"[+] Parsing report for all connected WiFi addresses\")\n \n root = xml_tree.getroot()" }, { "code": null, "e": 17660, "s": 17596, "text": "Now, iterate through the child element of the root as follows −" }, { "code": null, "e": 18022, "s": 17660, "text": "for child in root.iter():\n if child.tag == xmlns + \"model\":\n if child.get(\"type\") == \"Location\":\n for field in child.findall(xmlns + \"field\"):\n if field.get(\"name\") == \"TimeStamp\":\n ts_value = field.find(xmlns + \"value\")\n try:\n ts = ts_value.text\n except AttributeError:\ncontinue" }, { "code": null, "e": 18100, "s": 18022, "text": "Now, we will check that ‘ssid’ string is present in the value’s text or not −" }, { "code": null, "e": 18205, "s": 18100, "text": "if \"SSID\" in value.text:\n bssid, ssid = value.text.split(\"\\t\")\n bssid = bssid[7:]\n ssid = ssid[6:]" }, { "code": null, "e": 18287, "s": 18205, "text": "Now, we need to add BSSID, SSID and timestamp to the wifi dictionary as follows −" }, { "code": null, "e": 18470, "s": 18287, "text": "if bssid in wifi.keys():\n\nwifi[bssid][\"Timestamps\"].append(ts)\n wifi[bssid][\"SSID\"].append(ssid)\nelse:\n wifi[bssid] = {\"Timestamps\": [ts], \"SSID\":\n[ssid],\"Wigle\": {}}\nreturn wifi" }, { "code": null, "e": 18541, "s": 18470, "text": "The text parser which is much simpler that XML parser is shown below −" }, { "code": null, "e": 18808, "s": 18541, "text": "def parse_txt(txt_file):\n wifi = {}\n print(\"[+] Extracting MAC addresses from {}\".format(txt_file))\n \n with open(txt_file) as mac_file:\n for line in mac_file:\n wifi[line.strip()] = {\"Timestamps\": [\"N/A\"], \"SSID\":\n[\"N/A\"],\"Wigle\": {}}\nreturn wifi" }, { "code": null, "e": 18913, "s": 18808, "text": "Now, let us use requests module to make WIGLE APIcalls and need to move on to the query_wigle() method −" }, { "code": null, "e": 19416, "s": 18913, "text": "def query_wigle(wifi_dictionary, out_csv, api_key):\n print(\"[+] Querying Wigle.net through Python API for {} \"\n\"APs\".format(len(wifi_dictionary)))\n for mac in wifi_dictionary:\n\n wigle_results = query_mac_addr(mac, api_key)\ndef query_mac_addr(mac_addr, api_key):\n\n query_url = \"https://api.wigle.net/api/v2/network/search?\" \\\n\"onlymine = false&freenet = false&paynet = false\" \\ \"&netid = {}\".format(mac_addr)\n req = requests.get(query_url, auth = (api_key[0], api_key[1]))\n return req.json()" }, { "code": null, "e": 19533, "s": 19416, "text": "Actually there is a limit per day for WIGLE API calls, if that limit exceeds then it must show an error as follows −" }, { "code": null, "e": 20113, "s": 19533, "text": "try:\n if wigle_results[\"resultCount\"] == 0:\n wifi_dictionary[mac][\"Wigle\"][\"results\"] = []\n continue\n else:\n wifi_dictionary[mac][\"Wigle\"] = wigle_results\nexcept KeyError:\n if wigle_results[\"error\"] == \"too many queries today\":\n print(\"[-] Wigle daily query limit exceeded\")\n wifi_dictionary[mac][\"Wigle\"][\"results\"] = []\n continue\n else:\n print(\"[-] Other error encountered for \" \"address {}: {}\".format(mac,\nwigle_results['error']))\n wifi_dictionary[mac][\"Wigle\"][\"results\"] = []\n continue\nprep_output(out_csv, wifi_dictionary)" }, { "code": null, "e": 20208, "s": 20113, "text": "Now, we will use prep_output() method to flattens the dictionary into easily writable chunks −" }, { "code": null, "e": 20308, "s": 20208, "text": "def prep_output(output, data):\n csv_data = {}\n google_map = https://www.google.com/maps/search/" }, { "code": null, "e": 20371, "s": 20308, "text": "Now, access all the data we have collected so far as follows −" }, { "code": null, "e": 20662, "s": 20371, "text": "for x, mac in enumerate(data):\n for y, ts in enumerate(data[mac][\"Timestamps\"]):\n for z, result in enumerate(data[mac][\"Wigle\"][\"results\"]):\n shortres = data[mac][\"Wigle\"][\"results\"][z]\n g_map_url = \"{}{},{}\".format(google_map, shortres[\"trilat\"],shortres[\"trilong\"])" }, { "code": null, "e": 20785, "s": 20662, "text": "Now, we can write the output in CSV file as we have done in earlier scripts in this chapter by using write_csv() function." }, { "code": null, "e": 20822, "s": 20785, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 20838, "s": 20822, "text": " Malhar Lathkar" }, { "code": null, "e": 20871, "s": 20838, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 20890, "s": 20871, "text": " Arnab Chakraborty" }, { "code": null, "e": 20925, "s": 20890, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 20947, "s": 20925, "text": " In28Minutes Official" }, { "code": null, "e": 20981, "s": 20947, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 21009, "s": 20981, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 21044, "s": 21009, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 21058, "s": 21044, "text": " Lets Kode It" }, { "code": null, "e": 21091, "s": 21058, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 21108, "s": 21091, "text": " Abhilash Nelson" }, { "code": null, "e": 21115, "s": 21108, "text": " Print" }, { "code": null, "e": 21126, "s": 21115, "text": " Add Notes" } ]
How to export to PDF a graph based on a Pandas dataframe in Matplotlib?
To export to PDF a graph based on a Pandas dataframe, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Make a Pandas dataframe with three columns, col1, col2 and col3. Plot the dataframe using plot() method. To display the figure, use show() method. import matplotlib.pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame([[2, 1, 4], [5, 2, 1], [4, 0, 1]], columns=['col1', 'col2', 'col3']) df.plot() plt.savefig('pd_df.pdf') When we execute the code, it will save the following plot in a PDF with the name "pd_df.pdf".
[ { "code": null, "e": 1150, "s": 1062, "text": "To export to PDF a graph based on a Pandas dataframe, we can take the following steps −" }, { "code": null, "e": 1226, "s": 1150, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1291, "s": 1226, "text": "Make a Pandas dataframe with three columns, col1, col2 and col3." }, { "code": null, "e": 1331, "s": 1291, "text": "Plot the dataframe using plot() method." }, { "code": null, "e": 1373, "s": 1331, "text": "To display the figure, use show() method." }, { "code": null, "e": 1637, "s": 1373, "text": "import matplotlib.pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame([[2, 1, 4], [5, 2, 1], [4, 0, 1]], columns=['col1', 'col2', 'col3'])\ndf.plot()\n\nplt.savefig('pd_df.pdf')" }, { "code": null, "e": 1731, "s": 1637, "text": "When we execute the code, it will save the following plot in a PDF with the name \"pd_df.pdf\"." } ]
Python – How to Multiply all items in Tuple
27 Feb, 2020 Sometimes, while programming, we have a problem in which we might need to perform product among tuple elements. This is an essential utility as we come across product operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list() + loopThe above functions can be combined to perform this task. We can employ loop to accumulate the result of product logic. The list() function is used to perform interconversions. # Python3 code to demonstrate working of # Tuple Elements Multiplication# Using list() + loop # getting Product def prod(val) : res = 1 for ele in val: res *= ele return res # initializing tup test_tup = (7, 8, 9, 1, 10, 7) # printing original tuple print("The original tuple is : " + str(test_tup)) # Tuple Elements Multiplication # Using list() + loopres = prod(list(test_tup)) # printing result print("The product of tuple elements are : " + str(res)) The original tuple is : (7, 8, 9, 1, 10, 7) The product of tuple elements are : 35280 Method #2 : Using map() + loop + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform product of each using loop and again employ loop for overall product of resultant list. # Python 3 code to demonstrate working of # Tuple Elements Multiplication# Using map() + list() + loop # getting Product def prod(val) : res = 1 for ele in val: res *= ele return res # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Tuple Elements Multiplication# Using map() + list() + loop res = prod(list(map(prod, list(test_tup)))) # printing result print("The product of tuple elements are : " + str(res)) The original tuple is : (7, 8, 9, 1, 10, 7) The product of tuple elements are : 35280 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Feb, 2020" }, { "code": null, "e": 367, "s": 53, "text": "Sometimes, while programming, we have a problem in which we might need to perform product among tuple elements. This is an essential utility as we come across product operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 575, "s": 367, "text": "Method #1 : Using list() + loopThe above functions can be combined to perform this task. We can employ loop to accumulate the result of product logic. The list() function is used to perform interconversions." }, { "code": "# Python3 code to demonstrate working of # Tuple Elements Multiplication# Using list() + loop # getting Product def prod(val) : res = 1 for ele in val: res *= ele return res # initializing tup test_tup = (7, 8, 9, 1, 10, 7) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Tuple Elements Multiplication # Using list() + loopres = prod(list(test_tup)) # printing result print(\"The product of tuple elements are : \" + str(res)) ", "e": 1061, "s": 575, "text": null }, { "code": null, "e": 1148, "s": 1061, "text": "The original tuple is : (7, 8, 9, 1, 10, 7)\nThe product of tuple elements are : 35280\n" }, { "code": null, "e": 1443, "s": 1150, "text": "Method #2 : Using map() + loop + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform product of each using loop and again employ loop for overall product of resultant list." }, { "code": "# Python 3 code to demonstrate working of # Tuple Elements Multiplication# Using map() + list() + loop # getting Product def prod(val) : res = 1 for ele in val: res *= ele return res # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Tuple Elements Multiplication# Using map() + list() + loop res = prod(list(map(prod, list(test_tup)))) # printing result print(\"The product of tuple elements are : \" + str(res)) ", "e": 1969, "s": 1443, "text": null }, { "code": null, "e": 2056, "s": 1969, "text": "The original tuple is : (7, 8, 9, 1, 10, 7)\nThe product of tuple elements are : 35280\n" }, { "code": null, "e": 2077, "s": 2056, "text": "Python list-programs" }, { "code": null, "e": 2084, "s": 2077, "text": "Python" }, { "code": null, "e": 2100, "s": 2084, "text": "Python Programs" } ]
OpenCV and Keras | Traffic Sign Classification for Self-Driving Car
27 Dec, 2019 IntroductionIn this article, we will learn how to classify some common traffic signs that we occasionally encounter in our daily lives on the road. While building a self-driving car, it is necessary to make sure it identifies the traffic signs with a high degree of accuracy, unless the results might be catastrophic. While travelling, you may have come across numerous traffic signs, like the speed limit signal, the left or right turn signal, the stop signal and so on. Classifying all these precisely can be a daunting task, and that is where this post is going to help you. You can get the dataset from this link – Data. It contains 4 files – signnames.csv – It has all the labels and their descriptors. train.p – It contains all the training image pixel intensities along with the labels. valid.p – It contains all the validation image pixel intensities along with the labels. test.p – It contains all the testing image pixel intensities along with the labels. The above files with extension .p are called pickle files, which are used to serialize objects into character streams. These can be deserialized and reused later by loading them using the pickle library in python. Let’s implement a Convolutional Neural Network (CNN) using Keras in simple and easy-to-follow steps. A CNN consists of a series of Convolutional and Pooling layers in the Neural Network which map with the input to extract features. A Convolution layer will have many filters that are mainly used to detect the low-level features such as edges of a face. The Pooling layer does dimensionality reduction to decrease computation. Moreover, it also extracts the dominant features by ignoring the side pixels. To read more about CNNs, go to this link. Importing the librariesWe will be needing the following libraries. Make sure you install NumPy, Pandas, Keras, Matplotlib and OpenCV before implementing the following code. import numpy as npimport matplotlib.pyplot as pltimport kerasfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers.convolutional import Conv2D, MaxPooling2Dfrom keras.optimizers import Adamfrom keras.utils.np_utils import to_categoricalfrom keras.preprocessing.image import ImageDataGeneratorimport pickleimport pandas as pdimport randomimport cv2 np.random.seed(0) Here, we are using numpy for numerical computations, pandas for importing and managing the dataset, Keras for building the Convolutional Neural Network quickly with less code, cv2 for doing some preprocessing steps which are necessary for efficient extraction of features from the images by the CNN. Loading the datasetTime to load the data. We will use pandas to load signnames.csv, and pickle to load the train, validation and test pickle files. After extraction of data, it is then split using the dictionary labels “features” and “labels”. # Read datadata = pd.read_csv("german-traffic-signs / signnames.csv") with open('german-traffic-signs / train.p', 'rb') as f: train_data = pickle.load(f)with open('german-traffic-signs / valid.p', 'rb') as f: val_data = pickle.load(f)with open('german-traffic-signs / test.p', 'rb') as f: test_data = pickle.load(f) # Extracting the labels from the dictionariesX_train, y_train = train_data['features'], train_data['labels']X_val, y_val = val_data['features'], val_data['labels']X_test, y_test = test_data['features'], test_data['labels'] # Printing the shapesprint(X_train.shape)print(X_val.shape)print(X_test.shape) Output: (34799, 32, 32, 3) (4410, 32, 32, 3) (12630, 32, 32, 3) Preprocessing the data using OpenCVPreprocessing images before feeding into the model gives very accurate results as it helps in extracting the complex features of the image. OpenCV has some built-in functions like cvtColor() and equalizeHist() for this task. Follow the below steps for this task – First, the images are converted to grayscale images for reducing computation using the cvtColor() function. The equalizeHist() function increases the contrasts of the image by equalizing the intensities of the pixels by normalizing them with their nearby pixels. At the end, we normalize the pixel values between 0 and 1 by dividing them by 255. def preprocessing(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.equalizeHist(img) img = img / 255 return img X_train = np.array(list(map(preprocessing, X_train)))X_val = np.array(list(map(preprocessing, X_val)))X_test = np.array(list(map(preprocessing, X_test))) X_train = X_train.reshape(34799, 32, 32, 1)X_val = X_val.reshape(4410, 32, 32, 1)X_test = X_test.reshape(12630, 32, 32, 1) After reshaping the arrays, it’s time to feed them into the model for training. But to increase the accuracy of our CNN model, we will involve one more step of generating augmented images using the ImageDataGenerator. This is done to reduce overfitting the training data as getting more varied data will result in a better model. The value 0.1 is interpreted as 10%, whereas 10 is the degree of rotation. We are also converting the labels to categorical values, as we normally do. datagen = ImageDataGenerator(width_shift_range = 0.1, height_shift_range = 0.1, zoom_range = 0.2, shear_range = 0.1, rotation_range = 10)datagen.fit(X_train) y_train = to_categorical(y_train, 43)y_val = to_categorical(y_val, 43)y_test = to_categorical(y_test, 43) Building the modelAs we have 43 classes of images in the dataset, we are setting num_classes as 43. The model contains two Conv2D layers followed by one MaxPooling2D layer. This is done two times for the effective extraction of features, which is followed by the Dense layers. A dropout layer of 0.5 is added to avoid overfitting the data. num_classes = 43 def cnn_model(): model = Sequential() model.add(Conv2D(60, (5, 5), input_shape =(32, 32, 1), activation ='relu')) model.add(Conv2D(60, (5, 5), activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2))) model.add(Conv2D(30, (3, 3), activation ='relu')) model.add(Conv2D(30, (3, 3), activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2))) model.add(Flatten()) model.add(Dense(500, activation ='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation ='softmax')) # Compile model model.compile(Adam(lr = 0.001), loss ='categorical_crossentropy', metrics =['accuracy']) return model model = cnn_model()history = model.fit_generator(datagen.flow(X_train, y_train, batch_size = 50), steps_per_epoch = 2000, epochs = 10, validation_data =(X_val, y_val), shuffle = 1) Output: Epoch 1/10 2000/2000 [==============================] - 129s 65ms/step - loss: 0.9130 - acc: 0.7322 - val_loss: 0.0984 - val_acc: 0.9669 Epoch 2/10 2000/2000 [==============================] - 119s 60ms/step - loss: 0.2084 - acc: 0.9352 - val_loss: 0.0609 - val_acc: 0.9803 Epoch 3/10 2000/2000 [==============================] - 116s 58ms/step - loss: 0.1399 - acc: 0.9562 - val_loss: 0.0409 - val_acc: 0.9878 Epoch 4/10 2000/2000 [==============================] - 115s 58ms/step - loss: 0.1066 - acc: 0.9672 - val_loss: 0.0262 - val_acc: 0.9925 Epoch 5/10 2000/2000 [==============================] - 116s 58ms/step - loss: 0.0890 - acc: 0.9726 - val_loss: 0.0268 - val_acc: 0.9925 Epoch 6/10 2000/2000 [==============================] - 115s 58ms/step - loss: 0.0777 - acc: 0.9756 - val_loss: 0.0237 - val_acc: 0.9927 Epoch 7/10 2000/2000 [==============================] - 132s 66ms/step - loss: 0.0700 - acc: 0.9779 - val_loss: 0.0327 - val_acc: 0.9900 Epoch 8/10 2000/2000 [==============================] - 122s 61ms/step - loss: 0.0618 - acc: 0.9812 - val_loss: 0.0267 - val_acc: 0.9914 Epoch 9/10 2000/2000 [==============================] - 115s 57ms/step - loss: 0.0565 - acc: 0.9830 - val_loss: 0.0146 - val_acc: 0.9957 Epoch 10/10 2000/2000 [==============================] - 120s 60ms/step - loss: 0.0577 - acc: 0.9828 - val_loss: 0.0222 - val_acc: 0.9939 After successfully compiling the model, and fitting in on the train and validation data, let us evaluate it by using Matplotlib. Evaluation and testingPlotting the loss function. plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.legend(['training', 'validation'])plt.title('Loss')plt.xlabel('epoch') Output: Plotting the accuracy function. plt.plot(history.history['acc'])plt.plot(history.history['val_acc'])plt.legend(['training', 'validation'])plt.title('Accuracy')plt.xlabel('epoch') Output: As you can see, we have fitted the data well keeping both the training and validation loss at a minimum. Time to evaluate how our model performs on the test data. score = model.evaluate(X_test, y_test, verbose = 0)print('Test Loss: ', score[0])print('Test Accuracy: ', score[1]) Output: Test Loss: 0.16352852963907774 Test Accuracy: 0.9701504354899777 Let us check one test image by feeding it into the model. The model gives a prediction of class 0 (Speed limit 20), which is correct. plt.imshow(X_test[990].reshape(32, 32))print("Predicted sign: "+ str( model.predict_classes(X_test[990].reshape(1, 32, 32, 1)))) Output: Predicted sign: [0] Image-Processing Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2019" }, { "code": null, "e": 630, "s": 52, "text": "IntroductionIn this article, we will learn how to classify some common traffic signs that we occasionally encounter in our daily lives on the road. While building a self-driving car, it is necessary to make sure it identifies the traffic signs with a high degree of accuracy, unless the results might be catastrophic. While travelling, you may have come across numerous traffic signs, like the speed limit signal, the left or right turn signal, the stop signal and so on. Classifying all these precisely can be a daunting task, and that is where this post is going to help you." }, { "code": null, "e": 699, "s": 630, "text": "You can get the dataset from this link – Data. It contains 4 files –" }, { "code": null, "e": 760, "s": 699, "text": "signnames.csv – It has all the labels and their descriptors." }, { "code": null, "e": 846, "s": 760, "text": "train.p – It contains all the training image pixel intensities along with the labels." }, { "code": null, "e": 934, "s": 846, "text": "valid.p – It contains all the validation image pixel intensities along with the labels." }, { "code": null, "e": 1018, "s": 934, "text": "test.p – It contains all the testing image pixel intensities along with the labels." }, { "code": null, "e": 1232, "s": 1018, "text": "The above files with extension .p are called pickle files, which are used to serialize objects into character streams. These can be deserialized and reused later by loading them using the pickle library in python." }, { "code": null, "e": 1779, "s": 1232, "text": "Let’s implement a Convolutional Neural Network (CNN) using Keras in simple and easy-to-follow steps. A CNN consists of a series of Convolutional and Pooling layers in the Neural Network which map with the input to extract features. A Convolution layer will have many filters that are mainly used to detect the low-level features such as edges of a face. The Pooling layer does dimensionality reduction to decrease computation. Moreover, it also extracts the dominant features by ignoring the side pixels. To read more about CNNs, go to this link." }, { "code": null, "e": 1953, "s": 1779, "text": " Importing the librariesWe will be needing the following libraries. Make sure you install NumPy, Pandas, Keras, Matplotlib and OpenCV before implementing the following code." }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport kerasfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers.convolutional import Conv2D, MaxPooling2Dfrom keras.optimizers import Adamfrom keras.utils.np_utils import to_categoricalfrom keras.preprocessing.image import ImageDataGeneratorimport pickleimport pandas as pdimport randomimport cv2 np.random.seed(0)", "e": 2367, "s": 1953, "text": null }, { "code": null, "e": 2911, "s": 2367, "text": "Here, we are using numpy for numerical computations, pandas for importing and managing the dataset, Keras for building the Convolutional Neural Network quickly with less code, cv2 for doing some preprocessing steps which are necessary for efficient extraction of features from the images by the CNN. Loading the datasetTime to load the data. We will use pandas to load signnames.csv, and pickle to load the train, validation and test pickle files. After extraction of data, it is then split using the dictionary labels “features” and “labels”." }, { "code": "# Read datadata = pd.read_csv(\"german-traffic-signs / signnames.csv\") with open('german-traffic-signs / train.p', 'rb') as f: train_data = pickle.load(f)with open('german-traffic-signs / valid.p', 'rb') as f: val_data = pickle.load(f)with open('german-traffic-signs / test.p', 'rb') as f: test_data = pickle.load(f) # Extracting the labels from the dictionariesX_train, y_train = train_data['features'], train_data['labels']X_val, y_val = val_data['features'], val_data['labels']X_test, y_test = test_data['features'], test_data['labels'] # Printing the shapesprint(X_train.shape)print(X_val.shape)print(X_test.shape)", "e": 3541, "s": 2911, "text": null }, { "code": null, "e": 3549, "s": 3541, "text": "Output:" }, { "code": null, "e": 3606, "s": 3549, "text": "(34799, 32, 32, 3)\n(4410, 32, 32, 3)\n(12630, 32, 32, 3)\n" }, { "code": null, "e": 3906, "s": 3606, "text": " Preprocessing the data using OpenCVPreprocessing images before feeding into the model gives very accurate results as it helps in extracting the complex features of the image. OpenCV has some built-in functions like cvtColor() and equalizeHist() for this task. Follow the below steps for this task –" }, { "code": null, "e": 4014, "s": 3906, "text": "First, the images are converted to grayscale images for reducing computation using the cvtColor() function." }, { "code": null, "e": 4169, "s": 4014, "text": "The equalizeHist() function increases the contrasts of the image by equalizing the intensities of the pixels by normalizing them with their nearby pixels." }, { "code": null, "e": 4252, "s": 4169, "text": "At the end, we normalize the pixel values between 0 and 1 by dividing them by 255." }, { "code": "def preprocessing(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.equalizeHist(img) img = img / 255 return img X_train = np.array(list(map(preprocessing, X_train)))X_val = np.array(list(map(preprocessing, X_val)))X_test = np.array(list(map(preprocessing, X_test))) X_train = X_train.reshape(34799, 32, 32, 1)X_val = X_val.reshape(4410, 32, 32, 1)X_test = X_test.reshape(12630, 32, 32, 1)", "e": 4666, "s": 4252, "text": null }, { "code": null, "e": 4884, "s": 4666, "text": "After reshaping the arrays, it’s time to feed them into the model for training. But to increase the accuracy of our CNN model, we will involve one more step of generating augmented images using the ImageDataGenerator." }, { "code": null, "e": 5147, "s": 4884, "text": "This is done to reduce overfitting the training data as getting more varied data will result in a better model. The value 0.1 is interpreted as 10%, whereas 10 is the degree of rotation. We are also converting the labels to categorical values, as we normally do." }, { "code": "datagen = ImageDataGenerator(width_shift_range = 0.1, height_shift_range = 0.1, zoom_range = 0.2, shear_range = 0.1, rotation_range = 10)datagen.fit(X_train) y_train = to_categorical(y_train, 43)y_val = to_categorical(y_val, 43)y_test = to_categorical(y_test, 43)", "e": 5484, "s": 5147, "text": null }, { "code": null, "e": 5825, "s": 5484, "text": " Building the modelAs we have 43 classes of images in the dataset, we are setting num_classes as 43. The model contains two Conv2D layers followed by one MaxPooling2D layer. This is done two times for the effective extraction of features, which is followed by the Dense layers. A dropout layer of 0.5 is added to avoid overfitting the data." }, { "code": "num_classes = 43 def cnn_model(): model = Sequential() model.add(Conv2D(60, (5, 5), input_shape =(32, 32, 1), activation ='relu')) model.add(Conv2D(60, (5, 5), activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2))) model.add(Conv2D(30, (3, 3), activation ='relu')) model.add(Conv2D(30, (3, 3), activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2))) model.add(Flatten()) model.add(Dense(500, activation ='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation ='softmax')) # Compile model model.compile(Adam(lr = 0.001), loss ='categorical_crossentropy', metrics =['accuracy']) return model model = cnn_model()history = model.fit_generator(datagen.flow(X_train, y_train, batch_size = 50), steps_per_epoch = 2000, epochs = 10, validation_data =(X_val, y_val), shuffle = 1)", "e": 6861, "s": 5825, "text": null }, { "code": null, "e": 8241, "s": 6861, "text": "Output:\nEpoch 1/10\n2000/2000 [==============================] - 129s 65ms/step - loss: 0.9130 - acc: 0.7322 - val_loss: 0.0984 - val_acc: 0.9669\nEpoch 2/10\n2000/2000 [==============================] - 119s 60ms/step - loss: 0.2084 - acc: 0.9352 - val_loss: 0.0609 - val_acc: 0.9803\nEpoch 3/10\n2000/2000 [==============================] - 116s 58ms/step - loss: 0.1399 - acc: 0.9562 - val_loss: 0.0409 - val_acc: 0.9878\nEpoch 4/10\n2000/2000 [==============================] - 115s 58ms/step - loss: 0.1066 - acc: 0.9672 - val_loss: 0.0262 - val_acc: 0.9925\nEpoch 5/10\n2000/2000 [==============================] - 116s 58ms/step - loss: 0.0890 - acc: 0.9726 - val_loss: 0.0268 - val_acc: 0.9925\nEpoch 6/10\n2000/2000 [==============================] - 115s 58ms/step - loss: 0.0777 - acc: 0.9756 - val_loss: 0.0237 - val_acc: 0.9927\nEpoch 7/10\n2000/2000 [==============================] - 132s 66ms/step - loss: 0.0700 - acc: 0.9779 - val_loss: 0.0327 - val_acc: 0.9900\nEpoch 8/10\n2000/2000 [==============================] - 122s 61ms/step - loss: 0.0618 - acc: 0.9812 - val_loss: 0.0267 - val_acc: 0.9914\nEpoch 9/10\n2000/2000 [==============================] - 115s 57ms/step - loss: 0.0565 - acc: 0.9830 - val_loss: 0.0146 - val_acc: 0.9957\nEpoch 10/10\n2000/2000 [==============================] - 120s 60ms/step - loss: 0.0577 - acc: 0.9828 - val_loss: 0.0222 - val_acc: 0.9939\n" }, { "code": null, "e": 8420, "s": 8241, "text": "After successfully compiling the model, and fitting in on the train and validation data, let us evaluate it by using Matplotlib. Evaluation and testingPlotting the loss function." }, { "code": "plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.legend(['training', 'validation'])plt.title('Loss')plt.xlabel('epoch')", "e": 8565, "s": 8420, "text": null }, { "code": null, "e": 8573, "s": 8565, "text": "Output:" }, { "code": null, "e": 8607, "s": 8575, "text": "Plotting the accuracy function." }, { "code": "plt.plot(history.history['acc'])plt.plot(history.history['val_acc'])plt.legend(['training', 'validation'])plt.title('Accuracy')plt.xlabel('epoch')", "e": 8754, "s": 8607, "text": null }, { "code": null, "e": 8762, "s": 8754, "text": "Output:" }, { "code": null, "e": 8927, "s": 8764, "text": "As you can see, we have fitted the data well keeping both the training and validation loss at a minimum. Time to evaluate how our model performs on the test data." }, { "code": "score = model.evaluate(X_test, y_test, verbose = 0)print('Test Loss: ', score[0])print('Test Accuracy: ', score[1])", "e": 9043, "s": 8927, "text": null }, { "code": null, "e": 9051, "s": 9043, "text": "Output:" }, { "code": null, "e": 9119, "s": 9051, "text": "Test Loss: 0.16352852963907774\nTest Accuracy: 0.9701504354899777\n" }, { "code": null, "e": 9253, "s": 9119, "text": "Let us check one test image by feeding it into the model. The model gives a prediction of class 0 (Speed limit 20), which is correct." }, { "code": "plt.imshow(X_test[990].reshape(32, 32))print(\"Predicted sign: \"+ str( model.predict_classes(X_test[990].reshape(1, 32, 32, 1))))", "e": 9389, "s": 9253, "text": null }, { "code": null, "e": 9419, "s": 9389, "text": "Output:\nPredicted sign: [0]\n\n" }, { "code": null, "e": 9436, "s": 9419, "text": "Image-Processing" }, { "code": null, "e": 9453, "s": 9436, "text": "Machine Learning" }, { "code": null, "e": 9460, "s": 9453, "text": "Python" }, { "code": null, "e": 9477, "s": 9460, "text": "Machine Learning" }, { "code": null, "e": 9575, "s": 9477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9611, "s": 9575, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 9652, "s": 9611, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 9676, "s": 9652, "text": "Markov Decision Process" }, { "code": null, "e": 9709, "s": 9676, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 9760, "s": 9709, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 9788, "s": 9760, "text": "Read JSON file using Python" }, { "code": null, "e": 9810, "s": 9788, "text": "Python map() function" }, { "code": null, "e": 9860, "s": 9810, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 9878, "s": 9860, "text": "Python Dictionary" } ]
Remove First Row of DataFrame in R
23 Aug, 2021 In this article, we are going to see how to remove the first row from the dataframe. We can remove first row by indexing the dataframe. Syntax: data[-1,] where -1 is used to remove the first row which is in row position Example 1: R program to create a dataframe with 2 columns and delete the first row R # create dataframe with names and iddata=data.frame(names=c("sravan","boby","ojaswi","gnanesh", "rohith"),id=c(1,2,3,4,5)) # displaydata # remove first rowdata=data[- 1, ] print("------") # displaydata Output: Example 2: R program to create dataframe with 4 columns and delete the first row R # create dataframe with names ,id,phone and addressdata = data.frame(names=c("sravan", "boby", "ojaswi", "gnanesh", "rohith"), id=c(1, 2, 3, 4, 5), phone=c("91834567450", "2222222222", "333333333333", "5555555555555", "333333333333"), address=c("hyd", "kol", "patna", "bikat", "guntut")) # displaydata # remove first rowdata = data[- 1, ] print("------") # displaydata Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 165, "s": 28, "text": "In this article, we are going to see how to remove the first row from the dataframe. We can remove first row by indexing the dataframe. " }, { "code": null, "e": 173, "s": 165, "text": "Syntax:" }, { "code": null, "e": 183, "s": 173, "text": "data[-1,]" }, { "code": null, "e": 249, "s": 183, "text": "where -1 is used to remove the first row which is in row position" }, { "code": null, "e": 332, "s": 249, "text": "Example 1: R program to create a dataframe with 2 columns and delete the first row" }, { "code": null, "e": 334, "s": 332, "text": "R" }, { "code": "# create dataframe with names and iddata=data.frame(names=c(\"sravan\",\"boby\",\"ojaswi\",\"gnanesh\", \"rohith\"),id=c(1,2,3,4,5)) # displaydata # remove first rowdata=data[- 1, ] print(\"------\") # displaydata", "e": 565, "s": 334, "text": null }, { "code": null, "e": 573, "s": 565, "text": "Output:" }, { "code": null, "e": 654, "s": 573, "text": "Example 2: R program to create dataframe with 4 columns and delete the first row" }, { "code": null, "e": 656, "s": 654, "text": "R" }, { "code": "# create dataframe with names ,id,phone and addressdata = data.frame(names=c(\"sravan\", \"boby\", \"ojaswi\", \"gnanesh\", \"rohith\"), id=c(1, 2, 3, 4, 5), phone=c(\"91834567450\", \"2222222222\", \"333333333333\", \"5555555555555\", \"333333333333\"), address=c(\"hyd\", \"kol\", \"patna\", \"bikat\", \"guntut\")) # displaydata # remove first rowdata = data[- 1, ] print(\"------\") # displaydata", "e": 1130, "s": 656, "text": null }, { "code": null, "e": 1138, "s": 1130, "text": "Output:" }, { "code": null, "e": 1145, "s": 1138, "text": "Picked" }, { "code": null, "e": 1166, "s": 1145, "text": "R DataFrame-Programs" }, { "code": null, "e": 1178, "s": 1166, "text": "R-DataFrame" }, { "code": null, "e": 1189, "s": 1178, "text": "R Language" }, { "code": null, "e": 1200, "s": 1189, "text": "R Programs" } ]
Pre-increment and Post-increment in C/C++
09 Dec, 2021 In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable. Thus it can be classified into two types: Pre-Increment Operator Post-Increment Operator 1) Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression. Syntax: a = ++x; Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression. CPP // CPP program to demonstrate pre increment // operator #include <iostream> using namespace std; // Driver Code int main() { int x = 10, a; a = ++x; cout << "Pre Increment Operation"; // Value of a will change cout << "\na = " << a; // Value of x change before execution of a=++x; cout << "\nx = " << x; return 0; } Pre Increment Operation a = 11 x = 11 2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++; Here, suppose the value of ‘x’ is 10 then the value of variable ‘a’ will be 10 because the old value of ‘x’ is used. CPP // CPP program to demonstrate post increment // operator #include <iostream> using namespace std; // Driver Code int main() { int x = 10, a; a = x++; cout << "Post Increment Operation"; // Value of a will not change cout << "\na = " << a; // Value of x change after execution of a=x++; cout << "\nx = " << x; return 0; } Post Increment Operation a = 10 x = 11 Special Case for Post-increment operator: If we assign the post-incremented value to the same variable then the value of that variable will not get incremented i.e. it will remain the same like it was before. Syntax: a = a++; Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 10 because the value of ‘x’ gets assigned to the post-incremented value of ‘x’. C++ // CPP program to demonstrate special // case of post increment operator #include <iostream> using namespace std; int main() { int x = 10; cout << "Value of x before post-incrementing"; cout << "\nx = " << x; x = x++; cout << "\nValue of x after post-incrementing"; // Value of a will not change cout << "\nx = " << x; return 0; } Output: Value of x before post-incrementing x = 10 Value of x after post-incrementing x = 10 Note: This special case is only with post-increment and post-decrement operators, while the pre-increment and pre-decrement operators works normal in this case. Evaluating Post and Pre-Increment Together The precedence of postfix ++ is more than prefix ++ and their associativity is also different. Associativity of prefix ++ is right to left and associativity of postfix ++ is left to right. Associativity of postfix ++ is left to right Associativity of prefix ++ is right to left C++ Programming Language Tutorial | Pre and Post Increment Operators in C++ | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Pre and Post Increment Operators in C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0CwgHphzaa0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Souvik Nandi. 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. shivamdhyani15 khadirkhan5 anshikajain26 C-Operators cpp-operator C Language C++ cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 57, "s": 26, "text": " \n09 Dec, 2021\n" }, { "code": null, "e": 414, "s": 57, "text": "In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable. Thus it can be classified into two types:" }, { "code": null, "e": 437, "s": 414, "text": "Pre-Increment Operator" }, { "code": null, "e": 461, "s": 437, "text": "Post-Increment Operator" }, { "code": null, "e": 678, "s": 461, "text": "1) Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression." }, { "code": null, "e": 688, "s": 678, "text": "Syntax: " }, { "code": null, "e": 698, "s": 688, "text": " a = ++x;" }, { "code": null, "e": 837, "s": 698, "text": "Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression." }, { "code": null, "e": 841, "s": 837, "text": "CPP" }, { "code": "\n\n\n\n\n\n\n// CPP program to demonstrate pre increment\n// operator\n#include <iostream>\nusing namespace std;\n \n// Driver Code\nint main()\n{\n int x = 10, a;\n \n a = ++x;\n cout << \"Pre Increment Operation\";\n \n // Value of a will change\n cout << \"\\na = \" << a;\n \n // Value of x change before execution of a=++x;\n cout << \"\\nx = \" << x;\n \n return 0;\n}\n\n\n\n\n\n", "e": 1222, "s": 851, "text": null }, { "code": null, "e": 1260, "s": 1222, "text": "Pre Increment Operation\na = 11\nx = 11" }, { "code": null, "e": 1519, "s": 1260, "text": "2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. " }, { "code": null, "e": 1529, "s": 1519, "text": "Syntax: " }, { "code": null, "e": 1539, "s": 1529, "text": " a = x++;" }, { "code": null, "e": 1656, "s": 1539, "text": "Here, suppose the value of ‘x’ is 10 then the value of variable ‘a’ will be 10 because the old value of ‘x’ is used." }, { "code": null, "e": 1660, "s": 1656, "text": "CPP" }, { "code": "\n\n\n\n\n\n\n// CPP program to demonstrate post increment\n// operator\n#include <iostream>\nusing namespace std;\n \n// Driver Code\nint main()\n{\n int x = 10, a;\n \n a = x++;\n \n cout << \"Post Increment Operation\";\n \n // Value of a will not change\n cout << \"\\na = \" << a;\n \n // Value of x change after execution of a=x++;\n cout << \"\\nx = \" << x;\n \n return 0;\n}\n\n\n\n\n\n", "e": 2048, "s": 1670, "text": null }, { "code": null, "e": 2087, "s": 2048, "text": "Post Increment Operation\na = 10\nx = 11" }, { "code": null, "e": 2296, "s": 2087, "text": "Special Case for Post-increment operator: If we assign the post-incremented value to the same variable then the value of that variable will not get incremented i.e. it will remain the same like it was before." }, { "code": null, "e": 2304, "s": 2296, "text": "Syntax:" }, { "code": null, "e": 2313, "s": 2304, "text": "a = a++;" }, { "code": null, "e": 2455, "s": 2313, "text": "Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 10 because the value of ‘x’ gets assigned to the post-incremented value of ‘x’." }, { "code": null, "e": 2459, "s": 2455, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// CPP program to demonstrate special \n// case of post increment operator\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n \n int x = 10;\n \n cout << \"Value of x before post-incrementing\";\n \n cout << \"\\nx = \" << x;\n \n x = x++;\n \n cout << \"\\nValue of x after post-incrementing\";\n \n // Value of a will not change\n cout << \"\\nx = \" << x;\n \n return 0;\n}\n\n\n\n\n\n", "e": 2862, "s": 2469, "text": null }, { "code": null, "e": 2870, "s": 2862, "text": "Output:" }, { "code": null, "e": 2955, "s": 2870, "text": "Value of x before post-incrementing\nx = 10\nValue of x after post-incrementing\nx = 10" }, { "code": null, "e": 3116, "s": 2955, "text": "Note: This special case is only with post-increment and post-decrement operators, while the pre-increment and pre-decrement operators works normal in this case." }, { "code": null, "e": 3159, "s": 3116, "text": "Evaluating Post and Pre-Increment Together" }, { "code": null, "e": 3350, "s": 3159, "text": "The precedence of postfix ++ is more than prefix ++ and their associativity is also different. Associativity of prefix ++ is right to left and associativity of postfix ++ is left to right. " }, { "code": null, "e": 3395, "s": 3350, "text": "Associativity of postfix ++ is left to right" }, { "code": null, "e": 3439, "s": 3395, "text": "Associativity of prefix ++ is right to left" }, { "code": null, "e": 4407, "s": 3439, "text": "C++ Programming Language Tutorial | Pre and Post Increment Operators in C++ | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Pre and Post Increment Operators in C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:24•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0CwgHphzaa0\" 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": 4829, "s": 4407, "text": "This article is contributed by Souvik Nandi. 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": 4844, "s": 4829, "text": "shivamdhyani15" }, { "code": null, "e": 4856, "s": 4844, "text": "khadirkhan5" }, { "code": null, "e": 4870, "s": 4856, "text": "anshikajain26" }, { "code": null, "e": 4884, "s": 4870, "text": "\nC-Operators\n" }, { "code": null, "e": 4899, "s": 4884, "text": "\ncpp-operator\n" }, { "code": null, "e": 4912, "s": 4899, "text": "\nC Language\n" }, { "code": null, "e": 4918, "s": 4912, "text": "\nC++\n" }, { "code": null, "e": 4931, "s": 4918, "text": "cpp-operator" }, { "code": null, "e": 4935, "s": 4931, "text": "CPP" } ]
Python program to Convert a Matrix to Sparse Matrix
17 Jan, 2022 Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python. Example: Input: Matrix:1 0 0 00 2 0 00 0 3 00 0 0 45 0 0 0 Output: Sparse Matrix:0 0 11 1 22 2 33 3 44 0 5 Explanation:Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Value In the Sparse Matrix the first row is 0 1 1 indicates that the value of the Matrix at row 0 and column 1 is 1. Approach: Create an empty list which will represent the sparse matrix list.Iterate through the 2D matrix to find non zero elements.If an element is non zero, create a temporary empty list.Append the row value, column value, and the non zero element itself into the temporary list.Now append the temporary list into the sparse matrix list such that the temporary list acts as a sub-list of the sparse matrix list.After getting all the non zero elements from the matrix, display the sparse matrix. Create an empty list which will represent the sparse matrix list. Iterate through the 2D matrix to find non zero elements. If an element is non zero, create a temporary empty list. Append the row value, column value, and the non zero element itself into the temporary list. Now append the temporary list into the sparse matrix list such that the temporary list acts as a sub-list of the sparse matrix list. After getting all the non zero elements from the matrix, display the sparse matrix. The above approach has been used in convertToSparseMatrix() function in the below program: # Python program to convert a# matrix to sparse matrix # function display a matrixdef displayMatrix(matrix): for row in matrix: for element in row: print(element, end =" ") print() # function to convert the matrix # into a sparse matrixdef convertToSparseMatrix(matrix): # creating an empty sparse # matrix list sparseMatrix =[] # searching values greater # than zero for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != 0 : # creating a temporary # sublist temp = [] # appending row value, column # value and element into the # sublist temp.append(i) temp.append(j) temp.append(matrix[i][j]) # appending the sublist into # the sparse matrix list sparseMatrix.append(temp) # displaying the sparse matrix print("\nSparse Matrix: ") displayMatrix(sparseMatrix) # Driver's code# initializing a normal matrixnormalMatrix =[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4], [5, 0, 0, 0]] # displaying the matrixdisplayMatrix(normalMatrix) # converting the matrix to sparse # displayMatrix convertToSparseMatrix(normalMatrix) Output: 0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5 simmytarika5 Python list-programs Python matrix-program python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python." }, { "code": null, "e": 173, "s": 164, "text": "Example:" }, { "code": null, "e": 223, "s": 173, "text": "Input: Matrix:1 0 0 00 2 0 00 0 3 00 0 0 45 0 0 0" }, { "code": null, "e": 271, "s": 223, "text": "Output: Sparse Matrix:0 0 11 1 22 2 33 3 44 0 5" }, { "code": null, "e": 396, "s": 271, "text": "Explanation:Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Value" }, { "code": null, "e": 507, "s": 396, "text": "In the Sparse Matrix the first row is 0 1 1 indicates that the value of the Matrix at row 0 and column 1 is 1." }, { "code": null, "e": 517, "s": 507, "text": "Approach:" }, { "code": null, "e": 1003, "s": 517, "text": "Create an empty list which will represent the sparse matrix list.Iterate through the 2D matrix to find non zero elements.If an element is non zero, create a temporary empty list.Append the row value, column value, and the non zero element itself into the temporary list.Now append the temporary list into the sparse matrix list such that the temporary list acts as a sub-list of the sparse matrix list.After getting all the non zero elements from the matrix, display the sparse matrix." }, { "code": null, "e": 1069, "s": 1003, "text": "Create an empty list which will represent the sparse matrix list." }, { "code": null, "e": 1126, "s": 1069, "text": "Iterate through the 2D matrix to find non zero elements." }, { "code": null, "e": 1184, "s": 1126, "text": "If an element is non zero, create a temporary empty list." }, { "code": null, "e": 1277, "s": 1184, "text": "Append the row value, column value, and the non zero element itself into the temporary list." }, { "code": null, "e": 1410, "s": 1277, "text": "Now append the temporary list into the sparse matrix list such that the temporary list acts as a sub-list of the sparse matrix list." }, { "code": null, "e": 1494, "s": 1410, "text": "After getting all the non zero elements from the matrix, display the sparse matrix." }, { "code": null, "e": 1585, "s": 1494, "text": "The above approach has been used in convertToSparseMatrix() function in the below program:" }, { "code": "# Python program to convert a# matrix to sparse matrix # function display a matrixdef displayMatrix(matrix): for row in matrix: for element in row: print(element, end =\" \") print() # function to convert the matrix # into a sparse matrixdef convertToSparseMatrix(matrix): # creating an empty sparse # matrix list sparseMatrix =[] # searching values greater # than zero for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != 0 : # creating a temporary # sublist temp = [] # appending row value, column # value and element into the # sublist temp.append(i) temp.append(j) temp.append(matrix[i][j]) # appending the sublist into # the sparse matrix list sparseMatrix.append(temp) # displaying the sparse matrix print(\"\\nSparse Matrix: \") displayMatrix(sparseMatrix) # Driver's code# initializing a normal matrixnormalMatrix =[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4], [5, 0, 0, 0]] # displaying the matrixdisplayMatrix(normalMatrix) # converting the matrix to sparse # displayMatrix convertToSparseMatrix(normalMatrix) ", "e": 3007, "s": 1585, "text": null }, { "code": null, "e": 3015, "s": 3007, "text": "Output:" }, { "code": null, "e": 3113, "s": 3015, "text": "0 1 0 0 \n0 0 2 0 \n0 3 0 0 \n0 0 5 0 \n0 0 0 4 \n\nSparse Matrix: \n0 0 1 \n1 1 2 \n2 2 3 \n3 3 4 \n4 0 5 \n" }, { "code": null, "e": 3126, "s": 3113, "text": "simmytarika5" }, { "code": null, "e": 3147, "s": 3126, "text": "Python list-programs" }, { "code": null, "e": 3169, "s": 3147, "text": "Python matrix-program" }, { "code": null, "e": 3181, "s": 3169, "text": "python-list" }, { "code": null, "e": 3188, "s": 3181, "text": "Python" }, { "code": null, "e": 3204, "s": 3188, "text": "Python Programs" }, { "code": null, "e": 3216, "s": 3204, "text": "python-list" } ]
ES6 - Symbol
ES6 introduces a new primitive type called Symbol. They are helpful to implement metaprogramming in JavaScript programs. const mySymbol = Symbol() const mySymbol = Symbol(stringDescription) A symbol is just a piece of memory in which you can store some data. Each symbol will point to a different memory location. Values returned by a Symbol() constructor are unique and immutable. Let us understand this through an example. Initially, we created two symbols without description followed by symbols with same description. In both the cases the equality operator will return false when the symbols are compared. <script> const s1 = Symbol(); const s2 = Symbol(); console.log(typeof s1) console.log(s1===s2) const s3 = Symbol("hello");//description const s4 = Symbol("hello"); console.log(s3) console.log(s4) console.log(s3==s4) </script> The output of the above code will be as mentioned below − symbol false Symbol(hello) Symbol(hello) false searches for existing symbols in a symbol registry with the given key and returns it, if found. Otherwise, a new symbol gets created in the global symbol registry with this key. Retrieves a shared symbol key from the global symbol registry for the given symbol. A symbol can be used with classes to define the properties in the class. The advantage is that if property is a symbol as shown below, the property can be accessed outside the package only if the symbol name is known. So, data is much encapsulated when symbols are used as properties. <script> const COLOR = Symbol() const MODEL = Symbol() const MAKE = Symbol() class Bike { constructor(color ,make,model){ this[COLOR] = color; this[MAKE] = make; this[MODEL] = model; } } let bike = new Bike('red','honda','cbr') console.log(bike) //property can be accessed ony if symbol name is known console.log(bike[COLOR]) </script> The output of the above code will be as stated below − Bike {Symbol(): "red", Symbol(): "honda", Symbol(): "cbr"} red 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": 2398, "s": 2277, "text": "ES6 introduces a new primitive type called Symbol. They are helpful to implement metaprogramming in JavaScript programs." }, { "code": null, "e": 2468, "s": 2398, "text": "const mySymbol = Symbol()\nconst mySymbol = Symbol(stringDescription)\n" }, { "code": null, "e": 2660, "s": 2468, "text": "A symbol is just a piece of memory in which you can store some data. Each symbol will point to a different memory location. Values returned by a Symbol() constructor are unique and immutable." }, { "code": null, "e": 2889, "s": 2660, "text": "Let us understand this through an example. Initially, we created two symbols without description followed by symbols with same description. In both the cases the equality operator will return false when the symbols are compared." }, { "code": null, "e": 3142, "s": 2889, "text": "<script>\n const s1 = Symbol();\n const s2 = Symbol();\n console.log(typeof s1)\n console.log(s1===s2)\n const s3 = Symbol(\"hello\");//description\n const s4 = Symbol(\"hello\");\n console.log(s3)\n console.log(s4)\n console.log(s3==s4)\n</script>" }, { "code": null, "e": 3200, "s": 3142, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 3248, "s": 3200, "text": "symbol\nfalse\nSymbol(hello)\nSymbol(hello)\nfalse\n" }, { "code": null, "e": 3426, "s": 3248, "text": "searches for existing symbols in a symbol registry with the given key and returns it, if found. Otherwise, a new symbol gets created in the global symbol registry with this key." }, { "code": null, "e": 3510, "s": 3426, "text": "Retrieves a shared symbol key from the global symbol registry for the given symbol." }, { "code": null, "e": 3795, "s": 3510, "text": "A symbol can be used with classes to define the properties in the class. The advantage is that if property is a symbol as shown below, the property can be accessed outside the package only if the symbol name is known. So, data is much encapsulated when symbols are used as properties." }, { "code": null, "e": 4170, "s": 3795, "text": "<script>\n const COLOR = Symbol()\n const MODEL = Symbol()\n const MAKE = Symbol()\n class Bike {\n constructor(color ,make,model){\n this[COLOR] = color;\n this[MAKE] = make;\n this[MODEL] = model;\n }\n}\nlet bike = new Bike('red','honda','cbr')\nconsole.log(bike)\n//property can be accessed ony if symbol name is known\nconsole.log(bike[COLOR])\n</script>" }, { "code": null, "e": 4225, "s": 4170, "text": "The output of the above code will be as stated below −" }, { "code": null, "e": 4289, "s": 4225, "text": "Bike {Symbol(): \"red\", Symbol(): \"honda\", Symbol(): \"cbr\"}\nred\n" }, { "code": null, "e": 4324, "s": 4289, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4338, "s": 4324, "text": " Sharad Kumar" }, { "code": null, "e": 4371, "s": 4338, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 4389, "s": 4371, "text": " Richa Maheshwari" }, { "code": null, "e": 4422, "s": 4389, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4436, "s": 4422, "text": " Anadi Sharma" }, { "code": null, "e": 4471, "s": 4436, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4488, "s": 4471, "text": " Gowthami Swarna" }, { "code": null, "e": 4521, "s": 4488, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4537, "s": 4521, "text": " Deepti Trivedi" }, { "code": null, "e": 4572, "s": 4537, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4580, "s": 4572, "text": " Shweta" }, { "code": null, "e": 4587, "s": 4580, "text": " Print" }, { "code": null, "e": 4598, "s": 4587, "text": " Add Notes" } ]
MariaDB - Administration
Before attempting to run MariaDB, first determine its current state, running or shutdown. There are three options for starting and stopping MariaDB − Run mysqld (the MariaDB binary). Run the mysqld_safe startup script. Run the mysql.server startup script. If you installed MariaDB in a non-standard location, you may have to edit location information in the script files. Stop MariaDB by simply adding a “stop” parameter with the script. If you would like to start it automatically under Linux, add startup scripts to your init system. Each distribution has a different procedure. Refer to your system documentation. Create a new user account with the following code − CREATE USER 'newusername'@'localhost' IDENTIFIED BY 'userpassword'; This code adds a row to the user table with no privileges. You also have the option to use a hash value for the password. Grant the user privileges with the following code − GRANT SELECT, INSERT, UPDATE, DELETE ON database1 TO 'newusername'@'localhost'; Other privileges include just about every command or operation possible in MariaDB. After creating a user, execute a “FLUSH PRIVILEGES” command in order to refresh grant tables. This allows the user account to be used. After a build on Unix/Linux, the configuration file “/etc/mysql/my.cnf” should be edited to appear as follow − # Example mysql config file. # You can copy this to one of: # /etc/my.cnf to set global options, # /mysql-data-dir/my.cnf to get server specific options or # ~/my.cnf for user specific options. # # One can use all long options that the program supports. # Run the program with --help to get a list of available options # This will be passed to all mysql clients [client] #password = my_password #port = 3306 #socket = /tmp/mysql.sock # Here is entries for some specific programs # The following values assume you have at least 32M ram # The MySQL server [mysqld] #port = 3306 #socket = /tmp/mysql.sock temp-pool # The following three entries caused mysqld 10.0.1-MariaDB (and possibly other versions) to abort... # skip-locking # set-variable = key_buffer = 16M # set-variable = thread_cache = 4 loose-innodb_data_file_path = ibdata1:1000M loose-mutex-deadlock-detector gdb ######### Fix the two following paths # Where you want to have your database data = /path/to/data/dir # Where you have your mysql/MariaDB source + sql/share/english language = /path/to/src/dir/sql/share/english [mysqldump] quick MariaDB 8 set-variable = max_allowed_packet=16M [mysql] no-auto-rehash [myisamchk] set-variable = key_buffer = 128M Edit the lines “data= ” and “language= ” to match your environment. After file modification, navigate to the source directory and execute the following − ./scripts/mysql_install_db --srcdir = $PWD --datadir = /path/to/data/dir -- user = $LOGNAME Omit the “$PWD” variable if you added datadir to the configuration file. Ensure “$LOGNAME” is used when running version 10.0.1 of MariaDB. Review the following list of important commands you will regularly use when working with MariaDB − USE [database name] − Sets the current default database. USE [database name] − Sets the current default database. SHOW DATABASES − Lists the databases currently on the server. SHOW DATABASES − Lists the databases currently on the server. SHOW TABLES − Lists all non-temporary tables. SHOW TABLES − Lists all non-temporary tables. SHOW COLUMNS FROM [table name] − Provides column information pertaining to the specified table. SHOW COLUMNS FROM [table name] − Provides column information pertaining to the specified table. SHOW INDEX FROM TABLENAME [table name] − Provides table index information relating to the specified table. SHOW INDEX FROM TABLENAME [table name] − Provides table index information relating to the specified table. SHOW TABLE STATUS LIKE [table name]\G – − Provides tables with information about non-temporary tables, and the pattern that appears after the LIKE clause is used to fetch table names. SHOW TABLE STATUS LIKE [table name]\G – − Provides tables with information about non-temporary tables, and the pattern that appears after the LIKE clause is used to fetch table names. Print Add Notes Bookmark this page
[ { "code": null, "e": 2512, "s": 2362, "text": "Before attempting to run MariaDB, first determine its current state, running or shutdown. There are three options for starting and stopping MariaDB −" }, { "code": null, "e": 2545, "s": 2512, "text": "Run mysqld (the MariaDB binary)." }, { "code": null, "e": 2581, "s": 2545, "text": "Run the mysqld_safe startup script." }, { "code": null, "e": 2618, "s": 2581, "text": "Run the mysql.server startup script." }, { "code": null, "e": 2800, "s": 2618, "text": "If you installed MariaDB in a non-standard location, you may have to edit location information in the script files. Stop MariaDB by simply adding a “stop” parameter with the script." }, { "code": null, "e": 2979, "s": 2800, "text": "If you would like to start it automatically under Linux, add startup scripts to your init system. Each distribution has a different procedure. Refer to your system documentation." }, { "code": null, "e": 3031, "s": 2979, "text": "Create a new user account with the following code −" }, { "code": null, "e": 3100, "s": 3031, "text": "CREATE USER 'newusername'@'localhost' IDENTIFIED BY 'userpassword';\n" }, { "code": null, "e": 3274, "s": 3100, "text": "This code adds a row to the user table with no privileges. You also have the option to use a hash value for the password. Grant the user privileges with the following code −" }, { "code": null, "e": 3355, "s": 3274, "text": "GRANT SELECT, INSERT, UPDATE, DELETE ON database1 TO 'newusername'@'localhost';\n" }, { "code": null, "e": 3574, "s": 3355, "text": "Other privileges include just about every command or operation possible in MariaDB. After creating a user, execute a “FLUSH PRIVILEGES” command in order to refresh grant tables. This allows the user account to be used." }, { "code": null, "e": 3685, "s": 3574, "text": "After a build on Unix/Linux, the configuration file “/etc/mysql/my.cnf” should be edited to appear as follow −" }, { "code": null, "e": 4919, "s": 3685, "text": "# Example mysql config file.\n# You can copy this to one of:\n# /etc/my.cnf to set global options,\n# /mysql-data-dir/my.cnf to get server specific options or\n# ~/my.cnf for user specific options.\n\n#\n\n# One can use all long options that the program supports.\n# Run the program with --help to get a list of available options\n\n# This will be passed to all mysql clients\n[client]\n#password = my_password\n#port = 3306\n#socket = /tmp/mysql.sock\n\n# Here is entries for some specific programs\n# The following values assume you have at least 32M ram\n\n# The MySQL server\n[mysqld]\n#port = 3306\n#socket = /tmp/mysql.sock\ntemp-pool\n\n# The following three entries caused mysqld 10.0.1-MariaDB (and possibly other\n versions) to abort...\n# skip-locking\n# set-variable = key_buffer = 16M\n# set-variable = thread_cache = 4\n\nloose-innodb_data_file_path = ibdata1:1000M\nloose-mutex-deadlock-detector\ngdb\n\n######### Fix the two following paths\n\n# Where you want to have your database\ndata = /path/to/data/dir\n\n# Where you have your mysql/MariaDB source + sql/share/english\nlanguage = /path/to/src/dir/sql/share/english\n\n[mysqldump]\nquick\nMariaDB\n8\nset-variable = max_allowed_packet=16M\n[mysql]\nno-auto-rehash\n\n[myisamchk]\nset-variable = key_buffer = 128M" }, { "code": null, "e": 4987, "s": 4919, "text": "Edit the lines “data= ” and “language= ” to match your environment." }, { "code": null, "e": 5073, "s": 4987, "text": "After file modification, navigate to the source directory and execute the following −" }, { "code": null, "e": 5169, "s": 5073, "text": "./scripts/mysql_install_db --srcdir = $PWD --datadir = /path/to/data/dir --\n user = $LOGNAME\n" }, { "code": null, "e": 5308, "s": 5169, "text": "Omit the “$PWD” variable if you added datadir to the configuration file. Ensure “$LOGNAME” is used when running version 10.0.1 of MariaDB." }, { "code": null, "e": 5407, "s": 5308, "text": "Review the following list of important commands you will regularly use when working with MariaDB −" }, { "code": null, "e": 5464, "s": 5407, "text": "USE [database name] − Sets the current default database." }, { "code": null, "e": 5521, "s": 5464, "text": "USE [database name] − Sets the current default database." }, { "code": null, "e": 5583, "s": 5521, "text": "SHOW DATABASES − Lists the databases currently on the server." }, { "code": null, "e": 5645, "s": 5583, "text": "SHOW DATABASES − Lists the databases currently on the server." }, { "code": null, "e": 5691, "s": 5645, "text": "SHOW TABLES − Lists all non-temporary tables." }, { "code": null, "e": 5737, "s": 5691, "text": "SHOW TABLES − Lists all non-temporary tables." }, { "code": null, "e": 5833, "s": 5737, "text": "SHOW COLUMNS FROM [table name] − Provides column information pertaining to the specified table." }, { "code": null, "e": 5929, "s": 5833, "text": "SHOW COLUMNS FROM [table name] − Provides column information pertaining to the specified table." }, { "code": null, "e": 6036, "s": 5929, "text": "SHOW INDEX FROM TABLENAME [table name] − Provides table index information relating to the specified table." }, { "code": null, "e": 6143, "s": 6036, "text": "SHOW INDEX FROM TABLENAME [table name] − Provides table index information relating to the specified table." }, { "code": null, "e": 6327, "s": 6143, "text": "SHOW TABLE STATUS LIKE [table name]\\G – − Provides tables with information about non-temporary tables, and the pattern that appears after the LIKE clause is used to fetch table names." }, { "code": null, "e": 6511, "s": 6327, "text": "SHOW TABLE STATUS LIKE [table name]\\G – − Provides tables with information about non-temporary tables, and the pattern that appears after the LIKE clause is used to fetch table names." }, { "code": null, "e": 6518, "s": 6511, "text": " Print" }, { "code": null, "e": 6529, "s": 6518, "text": " Add Notes" } ]
How to replace a value in an R vector?
To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis. As you can see in the object x5(in examples), when we replaced 5 with 3, the previous replacement of -1 with 0 returned as in original vector. Therefore, we should save it in a new object. Live Demo > x1<-1:10 > x1 [1] 1 2 3 4 5 6 7 8 9 10 > replace(x1,x1==5,10) [1] 1 2 3 4 10 6 7 8 9 10 Live Demo > x2<-sample(0:5,50,replace=TRUE) > x2 [1] 1 4 5 3 3 0 0 3 4 2 1 1 1 1 2 0 2 1 5 3 5 2 3 0 3 0 4 2 4 1 3 2 4 2 3 1 4 4 [39] 1 0 3 2 4 2 1 1 1 2 5 1 > replace(x2,x2==0,1) [1] 1 4 5 3 3 1 1 3 4 2 1 1 1 1 2 1 2 1 5 3 5 2 3 1 3 1 4 2 4 1 3 2 4 2 3 1 4 4 [39] 1 1 3 2 4 2 1 1 1 2 5 1 Live Demo > x3<-sample(25:50,100,replace=TRUE) > x3 [1] 46 36 31 45 32 38 49 34 47 37 49 42 45 50 43 49 44 35 31 50 41 43 37 41 35 [26] 30 50 36 44 48 36 43 37 27 48 48 33 39 33 38 32 32 33 45 27 33 36 39 39 39 [51] 33 49 50 32 44 27 46 48 49 26 25 50 49 27 25 36 42 45 39 29 31 45 30 34 29 [76] 27 42 36 36 25 37 40 49 34 50 33 50 47 49 45 46 34 25 34 34 37 36 47 39 25 > replace(x3,x3==25,26) [1] 46 36 31 45 32 38 49 34 47 37 49 42 45 50 43 49 44 35 31 50 41 43 37 41 35 [26] 30 50 36 44 48 36 43 37 27 48 48 33 39 33 38 32 32 33 45 27 33 36 39 39 39 [51] 33 49 50 32 44 27 46 48 49 26 26 50 49 27 26 36 42 45 39 29 31 45 30 34 29 [76] 27 42 36 36 26 37 40 49 34 50 33 50 47 49 45 46 34 26 34 34 37 36 47 39 26 Live Demo > x4<-rpois(100,5) > x4 [1] 1 4 4 3 3 3 6 4 3 2 6 5 9 3 5 4 1 1 8 5 3 5 7 8 4 [26] 3 5 6 3 4 7 1 6 5 4 7 4 4 4 4 3 5 5 1 11 4 7 3 6 3 [51] 7 2 3 7 7 6 5 7 4 2 5 5 5 8 3 5 7 2 0 8 4 3 6 2 8 [76] 7 3 9 2 4 4 4 6 5 3 4 9 7 9 6 3 11 0 7 2 4 13 8 7 5 > replace(x4,x4==13,11) [1] 1 4 4 3 3 3 6 4 3 2 6 5 9 3 5 4 1 1 8 5 3 5 7 8 4 [26] 3 5 6 3 4 7 1 6 5 4 7 4 4 4 4 3 5 5 1 11 4 7 3 6 3 [51] 7 2 3 7 7 6 5 7 4 2 5 5 5 8 3 5 7 2 0 8 4 3 6 2 8 [76] 7 3 9 2 4 4 4 6 5 3 4 9 7 9 6 3 11 0 7 2 4 11 8 7 5 Live Demo > x5<-round(rnorm(100,2),0) > x5 [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 [26] 1 3 1 1 4 4 2 1 3 0 1 2 2 0 2 2 1 2 4 1 -1 2 0 3 3 [51] 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1 [76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4 > replace(x5,x5==-1,0) [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2 [38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 [75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4 > replace(x5,x5==5,3) [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 [26] 1 3 1 1 4 4 2 1 3 0 1 2 2 0 2 2 1 2 4 1 -1 2 0 3 3 [51] 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1 [76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 3 2 1 4 > replace(x5,x5==4,3) [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 [26] 1 3 1 1 3 3 2 1 3 0 1 2 2 0 2 2 1 2 3 1 -1 2 0 3 3 [51] 2 3 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1 [76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 3 2 2 1 5 2 1 3 Saving with a new object − > x5<-replace(x5,x5==-1,0) > x5 [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2 [38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 [75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4 -replace(x5,x5==5,3) > x5 [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2 [38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 [75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 3 2 1 4 > x5<-replace(x5,x5==4,3) > x5 [1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 3 3 2 1 3 0 1 2 [38] 2 0 2 2 1 2 3 1 0 2 0 3 3 2 3 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 [75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 3 2 2 1 3 2 1 3
[ { "code": null, "e": 1490, "s": 1062, "text": "To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis. As you can see in the object x5(in examples), when we replaced 5 with 3, the previous replacement of -1 with 0 returned as in original vector. Therefore, we should save it in a new object." }, { "code": null, "e": 1501, "s": 1490, "text": " Live Demo" }, { "code": null, "e": 1517, "s": 1501, "text": "> x1<-1:10\n> x1" }, { "code": null, "e": 1543, "s": 1517, "text": "[1] 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 1566, "s": 1543, "text": "> replace(x1,x1==5,10)" }, { "code": null, "e": 1593, "s": 1566, "text": "[1] 1 2 3 4 10 6 7 8 9 10\n" }, { "code": null, "e": 1604, "s": 1593, "text": " Live Demo" }, { "code": null, "e": 1643, "s": 1604, "text": "> x2<-sample(0:5,50,replace=TRUE)\n> x2" }, { "code": null, "e": 1752, "s": 1643, "text": "[1] 1 4 5 3 3 0 0 3 4 2 1 1 1 1 2 0 2 1 5 3 5 2 3 0 3 0 4 2 4 1 3 2 4 2 3 1 4 4\n[39] 1 0 3 2 4 2 1 1 1 2 5 1" }, { "code": null, "e": 1774, "s": 1752, "text": "> replace(x2,x2==0,1)" }, { "code": null, "e": 1883, "s": 1774, "text": "[1] 1 4 5 3 3 1 1 3 4 2 1 1 1 1 2 1 2 1 5 3 5 2 3 1 3 1 4 2 4 1 3 2 4 2 3 1 4 4\n[39] 1 1 3 2 4 2 1 1 1 2 5 1" }, { "code": null, "e": 1894, "s": 1883, "text": " Live Demo" }, { "code": null, "e": 1936, "s": 1894, "text": "> x3<-sample(25:50,100,replace=TRUE)\n> x3" }, { "code": null, "e": 2255, "s": 1936, "text": "[1] 46 36 31 45 32 38 49 34 47 37 49 42 45 50 43 49 44 35 31 50 41 43 37 41 35\n[26] 30 50 36 44 48 36 43 37 27 48 48 33 39 33 38 32 32 33 45 27 33 36 39 39 39\n[51] 33 49 50 32 44 27 46 48 49 26 25 50 49 27 25 36 42 45 39 29 31 45 30 34 29\n[76] 27 42 36 36 25 37 40 49 34 50 33 50 47 49 45 46 34 25 34 34 37 36 47 39 25" }, { "code": null, "e": 2279, "s": 2255, "text": "> replace(x3,x3==25,26)" }, { "code": null, "e": 2598, "s": 2279, "text": "[1] 46 36 31 45 32 38 49 34 47 37 49 42 45 50 43 49 44 35 31 50 41 43 37 41 35\n[26] 30 50 36 44 48 36 43 37 27 48 48 33 39 33 38 32 32 33 45 27 33 36 39 39 39\n[51] 33 49 50 32 44 27 46 48 49 26 26 50 49 27 26 36 42 45 39 29 31 45 30 34 29\n[76] 27 42 36 36 26 37 40 49 34 50 33 50 47 49 45 46 34 26 34 34 37 36 47 39 26" }, { "code": null, "e": 2609, "s": 2598, "text": " Live Demo" }, { "code": null, "e": 2633, "s": 2609, "text": "> x4<-rpois(100,5)\n> x4" }, { "code": null, "e": 2855, "s": 2633, "text": "[1] 1 4 4 3 3 3 6 4 3 2 6 5 9 3 5 4 1 1 8 5 3 5 7 8 4\n[26] 3 5 6 3 4 7 1 6 5 4 7 4 4 4 4 3 5 5 1 11 4 7 3 6 3\n[51] 7 2 3 7 7 6 5 7 4 2 5 5 5 8 3 5 7 2 0 8 4 3 6 2 8\n[76] 7 3 9 2 4 4 4 6 5 3 4 9 7 9 6 3 11 0 7 2 4 13 8 7 5" }, { "code": null, "e": 2879, "s": 2855, "text": "> replace(x4,x4==13,11)" }, { "code": null, "e": 3101, "s": 2879, "text": "[1] 1 4 4 3 3 3 6 4 3 2 6 5 9 3 5 4 1 1 8 5 3 5 7 8 4\n[26] 3 5 6 3 4 7 1 6 5 4 7 4 4 4 4 3 5 5 1 11 4 7 3 6 3\n[51] 7 2 3 7 7 6 5 7 4 2 5 5 5 8 3 5 7 2 0 8 4 3 6 2 8\n[76] 7 3 9 2 4 4 4 6 5 3 4 9 7 9 6 3 11 0 7 2 4 11 8 7 5" }, { "code": null, "e": 3112, "s": 3101, "text": " Live Demo" }, { "code": null, "e": 3145, "s": 3112, "text": "> x5<-round(rnorm(100,2),0)\n> x5" }, { "code": null, "e": 3365, "s": 3145, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3\n[26] 1 3 1 1 4 4 2 1 3 0 1 2 2 0 2 2 1 2 4 1 -1 2 0 3 3\n[51] 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1\n[76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4" }, { "code": null, "e": 3388, "s": 3365, "text": "> replace(x5,x5==-1,0)" }, { "code": null, "e": 3602, "s": 3388, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2\n[38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3\n[75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4" }, { "code": null, "e": 3624, "s": 3602, "text": "> replace(x5,x5==5,3)" }, { "code": null, "e": 3844, "s": 3624, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3\n[26] 1 3 1 1 4 4 2 1 3 0 1 2 2 0 2 2 1 2 4 1 -1 2 0 3 3\n[51] 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1\n[76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 3 2 1 4" }, { "code": null, "e": 3866, "s": 3844, "text": "> replace(x5,x5==4,3)" }, { "code": null, "e": 4086, "s": 3866, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3\n[26] 1 3 1 1 3 3 2 1 3 0 1 2 2 0 2 2 1 2 3 1 -1 2 0 3 3\n[51] 2 3 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3 1\n[76] 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 3 2 2 1 5 2 1 3" }, { "code": null, "e": 4113, "s": 4086, "text": "Saving with a new object −" }, { "code": null, "e": 4145, "s": 4113, "text": "> x5<-replace(x5,x5==-1,0)\n> x5" }, { "code": null, "e": 4359, "s": 4145, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2\n[38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3\n[75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 5 2 1 4" }, { "code": null, "e": 4385, "s": 4359, "text": "-replace(x5,x5==5,3)\n> x5" }, { "code": null, "e": 4599, "s": 4385, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 4 4 2 1 3 0 1 2\n[38] 2 0 2 2 1 2 4 1 0 2 0 3 3 2 4 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3\n[75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 4 2 2 1 3 2 1 4" }, { "code": null, "e": 4630, "s": 4599, "text": "> x5<-replace(x5,x5==4,3)\n> x5" }, { "code": null, "e": 4844, "s": 4630, "text": "[1] 2 2 0 1 2 3 2 2 1 2 3 1 1 0 1 2 2 3 3 2 2 3 3 2 3 1 3 1 1 3 3 2 1 3 0 1 2\n[38] 2 0 2 2 1 2 3 1 0 2 0 3 3 2 3 2 2 2 1 2 1 2 3 2 2 2 2 2 3 2 1 2 1 3 2 2 3\n[75] 1 1 3 2 3 2 3 3 3 2 2 1 1 0 2 2 3 0 3 2 2 1 3 2 1 3" } ]
How to set Parent State from Children Component in ReactJS? - GeeksforGeeks
27 Jan, 2021 We can set Parent State from Children Component in ReactJs using the following approach. Prerequisite: State introduction in ReactJS We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input. We will pass that function in children as a prop. Then Children will call the function with a new Value. We will set the state of the parent in the function. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder, i.e., folder name, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Step 3: Now create Parent and Children components in the src folder with the following code. Filename- Child.js: Javascript import React,{ Component } from 'react'; class Child extends Component { constructor(props) { super(props); this.handleClick.bind(this); } handleClick = () => { // We will start the process of changing // state of parent from Here... } render() { return ( <button onClick={this.handleClick}>Reveal Title</button> ); }} export default Child; Filename- Parent.js: Javascript import React,{ Component } from 'react';import "./parent_css.css" // Importing child component for renderingimport Child from './child'; class Parent extends Component { constructor(props) { super(props); this.state = {title: ""}; } render() { return ( <React.Fragment> // Rendering title of state initially empty. <h1> {this.state.title} </h1> // Rendering child component here which // contains only a button <Child /> </React.Fragment> ); }} export default Parent; Step 4: Create function setStateOfParent to set state of Parent in Parent component, also pass setStateOfParent function in children. Filename- Parent.js: Javascript import React,{ Component } from 'react';import "./parent_css.css" import Child from './child'; class Parent extends Component { constructor(props) { super(props); this.setStateOfParent.bind(this); this.state = {title: ""}; } // Creating below function to set state // of this (parent) component. setStateOfParent = (newTitle) => { this.setState({title: newTitle}); } render() { return ( <React.Fragment> <h1> {this.state.title} </h1> // Passing the setStateOfParent function // in child as a prop <Child setStateOfParent = {this.setStateOfParent}/> </React.Fragment> ); }} export default Parent; Step 5: Now access and call the setStateOfParent function in children whenever you want to set the state of the parent. Filename- Child.js: Javascript import React,{ Component } from 'react'; class Child extends Component { constructor(props) { super(props); this.handleClick.bind(this); } handleClick = () => { // Simply call the setStateOfParent function from // prop and pass required argument this.props.setStateOfParent("Geeks For Geeks"); } render() { return ( <button onClick={this.handleClick}>Reveal Title</button> ); }} export default Child; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked Technical Scripter 2020 JavaScript ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25338, "s": 25310, "text": "\n27 Jan, 2021" }, { "code": null, "e": 25427, "s": 25338, "text": "We can set Parent State from Children Component in ReactJs using the following approach." }, { "code": null, "e": 25471, "s": 25427, "text": "Prerequisite: State introduction in ReactJS" }, { "code": null, "e": 25596, "s": 25471, "text": "We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting." }, { "code": null, "e": 25671, "s": 25596, "text": "We will create a function in parent to set the state with the given input." }, { "code": null, "e": 25721, "s": 25671, "text": "We will pass that function in children as a prop." }, { "code": null, "e": 25776, "s": 25721, "text": "Then Children will call the function with a new Value." }, { "code": null, "e": 25829, "s": 25776, "text": "We will set the state of the parent in the function." }, { "code": null, "e": 25857, "s": 25829, "text": "Creating React Application:" }, { "code": null, "e": 25921, "s": 25857, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25953, "s": 25921, "text": "npx create-react-app foldername" }, { "code": null, "e": 26056, "s": 25953, "text": "Step 2: After creating your project folder, i.e., folder name, move to it using the following command:" }, { "code": null, "e": 26070, "s": 26056, "text": "cd foldername" }, { "code": null, "e": 26122, "s": 26070, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26140, "s": 26122, "text": "Project Structure" }, { "code": null, "e": 26233, "s": 26140, "text": "Step 3: Now create Parent and Children components in the src folder with the following code." }, { "code": null, "e": 26253, "s": 26233, "text": "Filename- Child.js:" }, { "code": null, "e": 26264, "s": 26253, "text": "Javascript" }, { "code": "import React,{ Component } from 'react'; class Child extends Component { constructor(props) { super(props); this.handleClick.bind(this); } handleClick = () => { // We will start the process of changing // state of parent from Here... } render() { return ( <button onClick={this.handleClick}>Reveal Title</button> ); }} export default Child;", "e": 26648, "s": 26264, "text": null }, { "code": null, "e": 26669, "s": 26648, "text": "Filename- Parent.js:" }, { "code": null, "e": 26680, "s": 26669, "text": "Javascript" }, { "code": "import React,{ Component } from 'react';import \"./parent_css.css\" // Importing child component for renderingimport Child from './child'; class Parent extends Component { constructor(props) { super(props); this.state = {title: \"\"}; } render() { return ( <React.Fragment> // Rendering title of state initially empty. <h1> {this.state.title} </h1> // Rendering child component here which // contains only a button <Child /> </React.Fragment> ); }} export default Parent;", "e": 27245, "s": 26680, "text": null }, { "code": null, "e": 27379, "s": 27245, "text": "Step 4: Create function setStateOfParent to set state of Parent in Parent component, also pass setStateOfParent function in children." }, { "code": null, "e": 27400, "s": 27379, "text": "Filename- Parent.js:" }, { "code": null, "e": 27411, "s": 27400, "text": "Javascript" }, { "code": "import React,{ Component } from 'react';import \"./parent_css.css\" import Child from './child'; class Parent extends Component { constructor(props) { super(props); this.setStateOfParent.bind(this); this.state = {title: \"\"}; } // Creating below function to set state // of this (parent) component. setStateOfParent = (newTitle) => { this.setState({title: newTitle}); } render() { return ( <React.Fragment> <h1> {this.state.title} </h1> // Passing the setStateOfParent function // in child as a prop <Child setStateOfParent = {this.setStateOfParent}/> </React.Fragment> ); }} export default Parent;", "e": 28108, "s": 27411, "text": null }, { "code": null, "e": 28228, "s": 28108, "text": "Step 5: Now access and call the setStateOfParent function in children whenever you want to set the state of the parent." }, { "code": null, "e": 28248, "s": 28228, "text": "Filename- Child.js:" }, { "code": null, "e": 28259, "s": 28248, "text": "Javascript" }, { "code": "import React,{ Component } from 'react'; class Child extends Component { constructor(props) { super(props); this.handleClick.bind(this); } handleClick = () => { // Simply call the setStateOfParent function from // prop and pass required argument this.props.setStateOfParent(\"Geeks For Geeks\"); } render() { return ( <button onClick={this.handleClick}>Reveal Title</button> ); }} export default Child;", "e": 28705, "s": 28259, "text": null }, { "code": null, "e": 28818, "s": 28705, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28828, "s": 28818, "text": "npm start" }, { "code": null, "e": 28927, "s": 28828, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28934, "s": 28927, "text": "Picked" }, { "code": null, "e": 28958, "s": 28934, "text": "Technical Scripter 2020" }, { "code": null, "e": 28969, "s": 28958, "text": "JavaScript" }, { "code": null, "e": 28977, "s": 28969, "text": "ReactJS" }, { "code": null, "e": 28996, "s": 28977, "text": "Technical Scripter" }, { "code": null, "e": 29013, "s": 28996, "text": "Web Technologies" }, { "code": null, "e": 29111, "s": 29013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29172, "s": 29111, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29213, "s": 29172, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29253, "s": 29213, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29307, "s": 29253, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29355, "s": 29307, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29398, "s": 29355, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29443, "s": 29398, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29508, "s": 29443, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 29576, "s": 29508, "text": "How to pass data from one component to other component in ReactJS ?" } ]
C program to print employee details using Structure
Here, we are given a structure containing details of employees. Our task is to create a C program to program to print employee details using structure. The details of the employee that are in the structure are name, age, phone number, salary, and our program will print these details. The details of the employees are pre-declared in the program and we will one by one print all the values. For this, we will create a function that will access the object of the structure and then print all the members of the structure using this object. // C Program to print employee details using structure − Live Demo #include <iostream> using namespace std; struct employee { int empId; string name; int age; string phone_number; int salary; }; void displayDeitals(struct employee emp[], int n) { cout<<"\n\n --- Employee "<<n+1<<" ---- \n"; cout<<"Employee ID: "<<emp[n].empId<<endl; cout<<"Employee name: "<<emp[n].name<<endl; cout<<"Employee age:"<<emp[n].age<<endl; cout<<"Employee phone number: "<<emp[n].phone_number<<endl; cout<<"Employee salary : "<<emp[n].salary<<endl; } int main() { int n = 3; struct employee emp[4]; emp[0].empId = 0121; emp[0].name = "Nupur"; emp[0].age = 22; emp[0].phone_number = "942135439"; emp[0].salary = 100000; emp[1].empId = 0322; emp[1].name = "Ramesh"; emp[1].age = 41; emp[1].phone_number = "908564363"; emp[1].salary = 50000; emp[2].empId = 023; emp[2].name = "Yash"; emp[2].age = 45; emp[2].phone_number = "943299231"; emp[2].salary = 250000; emp[3].empId = 0112; emp[3].name = "Zarin"; emp[3].age = 35; emp[3].phone_number = "796892522"; emp[3].salary = 300000; for(int i= 0; i<=n; i++) displayDeitals(emp, i); return 0; } --- Employee 1 ---- Employee ID: 81 Employee name: Nupur Employee age: 22 Employee phone number: 942135439 Employee salary: 100000 --- Employee 2 ---- Employee ID: 210 Employee name: Ramesh Employee age: 41 Employee phone number: 908564363 Employee salary: 50000 --- Employee 3 ---- Employee ID: 19 Employee name: Yash Employee age: 45 Employee phone number: 943299231 Employee salary: 250000 --- Employee 4 ---- Employee ID: 74 Employee name: Zarin Employee age: 35 Employee phone number: 796892522 Employee salary: 300000
[ { "code": null, "e": 1214, "s": 1062, "text": "Here, we are given a structure containing details of employees. Our task is to create a C program to program to print employee details using structure." }, { "code": null, "e": 1347, "s": 1214, "text": "The details of the employee that are in the structure are name, age, phone number, salary, and our program will print these details." }, { "code": null, "e": 1601, "s": 1347, "text": "The details of the employees are pre-declared in the program and we will one by one print all the values. For this, we will create a function that will access the object of the structure and then print all the members of the structure using this object." }, { "code": null, "e": 1658, "s": 1601, "text": "// C Program to print employee details using structure −" }, { "code": null, "e": 1669, "s": 1658, "text": " Live Demo" }, { "code": null, "e": 2828, "s": 1669, "text": "#include <iostream>\nusing namespace std;\nstruct employee {\n int empId;\n string name;\n int age;\n string phone_number;\n int salary;\n};\nvoid displayDeitals(struct employee emp[], int n) {\n cout<<\"\\n\\n --- Employee \"<<n+1<<\" ---- \\n\";\n cout<<\"Employee ID: \"<<emp[n].empId<<endl;\n cout<<\"Employee name: \"<<emp[n].name<<endl;\n cout<<\"Employee age:\"<<emp[n].age<<endl;\n cout<<\"Employee phone number: \"<<emp[n].phone_number<<endl;\n cout<<\"Employee salary : \"<<emp[n].salary<<endl;\n}\nint main() {\n int n = 3;\n struct employee emp[4];\n emp[0].empId = 0121;\n emp[0].name = \"Nupur\";\n emp[0].age = 22;\n emp[0].phone_number = \"942135439\";\n emp[0].salary = 100000;\n emp[1].empId = 0322;\n emp[1].name = \"Ramesh\";\n emp[1].age = 41;\n emp[1].phone_number = \"908564363\";\n emp[1].salary = 50000;\n emp[2].empId = 023;\n emp[2].name = \"Yash\";\n emp[2].age = 45;\n emp[2].phone_number = \"943299231\";\n emp[2].salary = 250000;\n emp[3].empId = 0112;\n emp[3].name = \"Zarin\";\n emp[3].age = 35;\n emp[3].phone_number = \"796892522\";\n emp[3].salary = 300000;\n for(int i= 0; i<=n; i++)\n displayDeitals(emp, i);\n return 0;\n}" }, { "code": null, "e": 3352, "s": 2828, "text": "--- Employee 1 ----\nEmployee ID: 81\nEmployee name: Nupur\nEmployee age: 22\nEmployee phone number: 942135439\nEmployee salary: 100000\n--- Employee 2 ----\nEmployee ID: 210\nEmployee name: Ramesh\nEmployee age: 41\nEmployee phone number: 908564363\nEmployee salary: 50000\n--- Employee 3 ----\nEmployee ID: 19\nEmployee name: Yash\nEmployee age: 45\nEmployee phone number: 943299231\nEmployee salary: 250000\n--- Employee 4 ----\nEmployee ID: 74\nEmployee name: Zarin\nEmployee age: 35\nEmployee phone number: 796892522\nEmployee salary: 300000" } ]
How to use for loop in Python?
The for loop in Python is used to iterate over a number of elements or some specific integer range. The elements might be of an array, string or any other iterative object in Python. The for loop is the most frequently used looping statement. Most of the programming questions we encounter make use of the for loop in its solution. Python has for an range loop. It takes the two integer values which specify the range within which the variable must iterate. If only one integer parameter is specified, then the specified integer is taken as the end of the range and the starting is 0 by default. for variable in range( starting value, end value) for variable in range( end value) Note: The for loop in Python iterates one less than the end value. This means that if the starting and end values are 1 and 5 respectively, then the loop will iterate for 1,2,3,4. The starting value is inclusive but the end value is not inclusive. Live Demo for i in range(1,5): print(i,end=" ") print() for i in range(5): print(i,end=" ") 1 2 3 4 0 1 2 3 4 The for in range loop can take a third parameter -1, which specifies that the for loop will iterate in reverse order. The loop starts from starting value and iterates in decreasing order to the end value(not inclusive). Live Demo for i in range(5,0,-1): print(i,end=" ") 5 4 3 2 1 The third parameter in the for loop can be modified to use for loop in different ways. The third parameter, in actual, specifies the steps the variable should jump. If not specified, it is 1 by default. If the third parameter is negative, it specifies that the loop will iterate in reverse order. The number of steps (jumps) backwards will be specified by this parameter. If the parameter is positive, the loop will iterate in forward order. The number of steps forward will be specified by this parameter. Let’s understand with the help of the below example. Live Demo for i in range(0,11,2): print(i,end=" ") print() for i in range(10,-1,-2): print(i,end=" ") 0 2 4 6 8 10 10 8 6 4 2 0 This loop is used to iterate over a iterable object such as string or array. It cannot be used to iterate over some specific integer range. for variable in iterable object This loop iterates over all the elements of the iterable object one by one without taking into account their index. If indexes are needed, use for in range loop. Live Demo st="Tutorials" for i in st: print(i,end=" ") print() array=[2,4,6,8,10] for i in array: print(i,end=" ") print() for i in range(len(array)): print(array[i],end=" ") T u t o r i a l s 2 4 6 8 10 2 4 6 8 10 Note: As clear from the above example, the variable in for in loop holds the elements of the iterable object one by one, whereas the variable in for in range loop holds the indexes of the elements.
[ { "code": null, "e": 1245, "s": 1062, "text": "The for loop in Python is used to iterate over a number of elements or some specific integer range. The elements might be of an array, string or any other iterative object in Python." }, { "code": null, "e": 1394, "s": 1245, "text": "The for loop is the most frequently used looping statement. Most of the programming questions we encounter make use of the for loop in its solution." }, { "code": null, "e": 1658, "s": 1394, "text": "Python has for an range loop. It takes the two integer values which specify the range within which the variable must iterate. If only one integer parameter is specified, then the specified integer is taken as the end of the range and the starting is 0 by default." }, { "code": null, "e": 1742, "s": 1658, "text": "for variable in range( starting value, end value)\nfor variable in range( end value)" }, { "code": null, "e": 1990, "s": 1742, "text": "Note: The for loop in Python iterates one less than the end value. This means that if the starting and end values are 1 and 5 respectively, then the loop will iterate for 1,2,3,4. The starting value is inclusive but the end value is not inclusive." }, { "code": null, "e": 2001, "s": 1990, "text": " Live Demo" }, { "code": null, "e": 2089, "s": 2001, "text": "for i in range(1,5):\n print(i,end=\" \")\nprint()\nfor i in range(5):\n print(i,end=\" \")" }, { "code": null, "e": 2107, "s": 2089, "text": "1 2 3 4\n0 1 2 3 4" }, { "code": null, "e": 2327, "s": 2107, "text": "The for in range loop can take a third parameter -1, which specifies that the for loop will iterate in reverse order. The loop starts from starting value and iterates in decreasing order to the end value(not inclusive)." }, { "code": null, "e": 2338, "s": 2327, "text": " Live Demo" }, { "code": null, "e": 2382, "s": 2338, "text": "for i in range(5,0,-1):\n print(i,end=\" \")" }, { "code": null, "e": 2392, "s": 2382, "text": "5 4 3 2 1" }, { "code": null, "e": 2595, "s": 2392, "text": "The third parameter in the for loop can be modified to use for loop in different ways. The third parameter, in actual, specifies the steps the variable should jump. If not specified, it is 1 by default." }, { "code": null, "e": 2689, "s": 2595, "text": "If the third parameter is negative, it specifies that the loop will iterate in reverse order." }, { "code": null, "e": 2764, "s": 2689, "text": "The number of steps (jumps) backwards will be specified by this parameter." }, { "code": null, "e": 2899, "s": 2764, "text": "If the parameter is positive, the loop will iterate in forward order. The number of steps forward will be specified by this parameter." }, { "code": null, "e": 2952, "s": 2899, "text": "Let’s understand with the help of the below example." }, { "code": null, "e": 2963, "s": 2952, "text": " Live Demo" }, { "code": null, "e": 3061, "s": 2963, "text": "for i in range(0,11,2):\n print(i,end=\" \")\nprint()\nfor i in range(10,-1,-2):\n print(i,end=\" \")" }, { "code": null, "e": 3087, "s": 3061, "text": "0 2 4 6 8 10\n10 8 6 4 2 0" }, { "code": null, "e": 3227, "s": 3087, "text": "This loop is used to iterate over a iterable object such as string or array. It cannot be used to iterate over some specific integer range." }, { "code": null, "e": 3259, "s": 3227, "text": "for variable in iterable object" }, { "code": null, "e": 3421, "s": 3259, "text": "This loop iterates over all the elements of the iterable object one by one without taking into account their index. If indexes are needed, use for in range loop." }, { "code": null, "e": 3432, "s": 3421, "text": " Live Demo" }, { "code": null, "e": 3606, "s": 3432, "text": "st=\"Tutorials\"\nfor i in st:\n print(i,end=\" \")\nprint()\narray=[2,4,6,8,10]\nfor i in array:\n print(i,end=\" \")\nprint()\nfor i in range(len(array)):\n print(array[i],end=\" \")" }, { "code": null, "e": 3646, "s": 3606, "text": "T u t o r i a l s\n2 4 6 8 10\n2 4 6 8 10" }, { "code": null, "e": 3844, "s": 3646, "text": "Note: As clear from the above example, the variable in for in loop holds the elements of the iterable object one by one, whereas the variable in for in range loop holds the indexes of the elements." } ]
SQLSERVER Tryit Editor v1.0
SELECT FORMAT(123456789, '##-##-#####'); ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 41, "s": 0, "text": "SELECT FORMAT(123456789, '##-##-#####');" }, { "code": null, "e": 43, "s": 41, "text": "​" }, { "code": null, "e": 115, "s": 52, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 175, "s": 115, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 243, "s": 175, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 281, "s": 243, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 366, "s": 281, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 540, "s": 366, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 591, "s": 540, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 659, "s": 591, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 830, "s": 659, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 930, "s": 830, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 980, "s": 930, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Java - Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface is similar to a class in the following ways − An interface can contain any number of methods. An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file. The byte code of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. However, an interface is different from a class in several ways, including − You cannot instantiate an interface. You cannot instantiate an interface. An interface does not contain any constructors. An interface does not contain any constructors. All of the methods in an interface are abstract. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. An interface can extend multiple interfaces. The interface keyword is used to declare an interface. Here is a simple example to declare an interface − Following is an example of an interface − /* File name : NameOfInterface.java */ import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ } Interfaces have the following properties − An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public. Methods in an interface are implicitly public. /* File name : Animal.java */ interface Animal { public void eat(); public void travel(); } When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } This will produce the following result − Mammal eats Mammal travels When overriding methods defined in interfaces, there are several rules to be followed − Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so, interface methods need not be implemented. An implementation class itself can be abstract and if so, interface methods need not be implemented. When implementation interfaces, there are several rules − A class can implement more than one interface at a time. A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class. An interface can extend another interface, in a similar way as a class can extend another class. An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. The following Sports interface is extended by Hockey and Football interfaces. // Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } // Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } // Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports. A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as − public interface Hockey extends Sports, Event The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as − package java.util; public interface EventListener {} An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces − Creates a common parent − As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario. Adds a data type to a class − This situation is where the term, tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism. 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": 2574, "s": 2377, "text": "An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface." }, { "code": null, "e": 2760, "s": 2574, "text": "Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods." }, { "code": null, "e": 2938, "s": 2760, "text": "Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements." }, { "code": null, "e": 3064, "s": 2938, "text": "Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class." }, { "code": null, "e": 3123, "s": 3064, "text": "An interface is similar to a class in the following ways −" }, { "code": null, "e": 3171, "s": 3123, "text": "An interface can contain any number of methods." }, { "code": null, "e": 3219, "s": 3171, "text": "An interface can contain any number of methods." }, { "code": null, "e": 3339, "s": 3219, "text": "An interface is written in a file with a .java extension, with the name of the interface matching the name of the file." }, { "code": null, "e": 3459, "s": 3339, "text": "An interface is written in a file with a .java extension, with the name of the interface matching the name of the file." }, { "code": null, "e": 3515, "s": 3459, "text": "The byte code of an interface appears in a .class file." }, { "code": null, "e": 3571, "s": 3515, "text": "The byte code of an interface appears in a .class file." }, { "code": null, "e": 3704, "s": 3571, "text": "Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name." }, { "code": null, "e": 3837, "s": 3704, "text": "Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name." }, { "code": null, "e": 3914, "s": 3837, "text": "However, an interface is different from a class in several ways, including −" }, { "code": null, "e": 3951, "s": 3914, "text": "You cannot instantiate an interface." }, { "code": null, "e": 3988, "s": 3951, "text": "You cannot instantiate an interface." }, { "code": null, "e": 4036, "s": 3988, "text": "An interface does not contain any constructors." }, { "code": null, "e": 4084, "s": 4036, "text": "An interface does not contain any constructors." }, { "code": null, "e": 4133, "s": 4084, "text": "All of the methods in an interface are abstract." }, { "code": null, "e": 4182, "s": 4133, "text": "All of the methods in an interface are abstract." }, { "code": null, "e": 4315, "s": 4182, "text": "An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final." }, { "code": null, "e": 4448, "s": 4315, "text": "An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final." }, { "code": null, "e": 4519, "s": 4448, "text": "An interface is not extended by a class; it is implemented by a class." }, { "code": null, "e": 4590, "s": 4519, "text": "An interface is not extended by a class; it is implemented by a class." }, { "code": null, "e": 4635, "s": 4590, "text": "An interface can extend multiple interfaces." }, { "code": null, "e": 4680, "s": 4635, "text": "An interface can extend multiple interfaces." }, { "code": null, "e": 4786, "s": 4680, "text": "The interface keyword is used to declare an interface. Here is a simple example to declare an interface −" }, { "code": null, "e": 4828, "s": 4786, "text": "Following is an example of an interface −" }, { "code": null, "e": 5051, "s": 4828, "text": "/* File name : NameOfInterface.java */\nimport java.lang.*;\n// Any number of import statements\n\npublic interface NameOfInterface {\n // Any number of final, static fields\n // Any number of abstract method declarations\\\n}" }, { "code": null, "e": 5094, "s": 5051, "text": "Interfaces have the following properties −" }, { "code": null, "e": 5205, "s": 5094, "text": "An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface." }, { "code": null, "e": 5316, "s": 5205, "text": "An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface." }, { "code": null, "e": 5412, "s": 5316, "text": "Each method in an interface is also implicitly abstract, so the abstract keyword is not needed." }, { "code": null, "e": 5508, "s": 5412, "text": "Each method in an interface is also implicitly abstract, so the abstract keyword is not needed." }, { "code": null, "e": 5555, "s": 5508, "text": "Methods in an interface are implicitly public." }, { "code": null, "e": 5602, "s": 5555, "text": "Methods in an interface are implicitly public." }, { "code": null, "e": 5700, "s": 5602, "text": "/* File name : Animal.java */\ninterface Animal {\n public void eat();\n public void travel();\n}" }, { "code": null, "e": 5956, "s": 5700, "text": "When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract." }, { "code": null, "e": 6125, "s": 5956, "text": "A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration." }, { "code": null, "e": 6520, "s": 6125, "text": "/* File name : MammalInt.java */\npublic class MammalInt implements Animal {\n\n public void eat() {\n System.out.println(\"Mammal eats\");\n }\n\n public void travel() {\n System.out.println(\"Mammal travels\");\n } \n\n public int noOfLegs() {\n return 0;\n }\n\n public static void main(String args[]) {\n MammalInt m = new MammalInt();\n m.eat();\n m.travel();\n }\n} " }, { "code": null, "e": 6561, "s": 6520, "text": "This will produce the following result −" }, { "code": null, "e": 6589, "s": 6561, "text": "Mammal eats\nMammal travels\n" }, { "code": null, "e": 6677, "s": 6589, "text": "When overriding methods defined in interfaces, there are several rules to be followed −" }, { "code": null, "e": 6855, "s": 6677, "text": "Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method." }, { "code": null, "e": 7033, "s": 6855, "text": "Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method." }, { "code": null, "e": 7157, "s": 7033, "text": "The signature of the interface method and the same return type or subtype should be maintained when overriding the methods." }, { "code": null, "e": 7281, "s": 7157, "text": "The signature of the interface method and the same return type or subtype should be maintained when overriding the methods." }, { "code": null, "e": 7382, "s": 7281, "text": "An implementation class itself can be abstract and if so, interface methods need not be implemented." }, { "code": null, "e": 7483, "s": 7382, "text": "An implementation class itself can be abstract and if so, interface methods need not be implemented." }, { "code": null, "e": 7541, "s": 7483, "text": "When implementation interfaces, there are several rules −" }, { "code": null, "e": 7598, "s": 7541, "text": "A class can implement more than one interface at a time." }, { "code": null, "e": 7655, "s": 7598, "text": "A class can implement more than one interface at a time." }, { "code": null, "e": 7721, "s": 7655, "text": "A class can extend only one class, but implement many interfaces." }, { "code": null, "e": 7787, "s": 7721, "text": "A class can extend only one class, but implement many interfaces." }, { "code": null, "e": 7884, "s": 7787, "text": "An interface can extend another interface, in a similar way as a class can extend another class." }, { "code": null, "e": 7981, "s": 7884, "text": "An interface can extend another interface, in a similar way as a class can extend another class." }, { "code": null, "e": 8200, "s": 7981, "text": "An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface." }, { "code": null, "e": 8278, "s": 8200, "text": "The following Sports interface is extended by Hockey and Football interfaces." }, { "code": null, "e": 8840, "s": 8278, "text": "// Filename: Sports.java\npublic interface Sports {\n public void setHomeTeam(String name);\n public void setVisitingTeam(String name);\n}\n\n// Filename: Football.java\npublic interface Football extends Sports {\n public void homeTeamScored(int points);\n public void visitingTeamScored(int points);\n public void endOfQuarter(int quarter);\n}\n\n// Filename: Hockey.java\npublic interface Hockey extends Sports {\n public void homeGoalScored();\n public void visitingGoalScored();\n public void endOfPeriod(int period);\n public void overtimePeriod(int ot);\n}" }, { "code": null, "e": 9110, "s": 8840, "text": "The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports." }, { "code": null, "e": 9291, "s": 9110, "text": "A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface." }, { "code": null, "e": 9391, "s": 9291, "text": "The extends keyword is used once, and the parent interfaces are declared in a comma-separated list." }, { "code": null, "e": 9486, "s": 9391, "text": "For example, if the Hockey interface extended both Sports and Event, it would be declared as −" }, { "code": null, "e": 9532, "s": 9486, "text": "public interface Hockey extends Sports, Event" }, { "code": null, "e": 9766, "s": 9532, "text": "The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as −" }, { "code": null, "e": 9819, "s": 9766, "text": "package java.util;\npublic interface EventListener\n{}" }, { "code": null, "e": 9953, "s": 9819, "text": "An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces −" }, { "code": null, "e": 10320, "s": 9953, "text": "Creates a common parent − As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario." }, { "code": null, "e": 10587, "s": 10320, "text": "Adds a data type to a class − This situation is where the term, tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism." }, { "code": null, "e": 10620, "s": 10587, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 10636, "s": 10620, "text": " Malhar Lathkar" }, { "code": null, "e": 10669, "s": 10636, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 10685, "s": 10669, "text": " Malhar Lathkar" }, { "code": null, "e": 10720, "s": 10685, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10734, "s": 10720, "text": " Anadi Sharma" }, { "code": null, "e": 10768, "s": 10734, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 10782, "s": 10768, "text": " Tushar Kale" }, { "code": null, "e": 10819, "s": 10782, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10834, "s": 10819, "text": " Monica Mittal" }, { "code": null, "e": 10867, "s": 10834, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 10886, "s": 10867, "text": " Arnab Chakraborty" }, { "code": null, "e": 10893, "s": 10886, "text": " Print" }, { "code": null, "e": 10904, "s": 10893, "text": " Add Notes" } ]
Difference b/w getText() and getAttribute() in Selenium WebDriver?
The differences between getText() and getAttribute() methods are described below. The getText() method returns the innerText of an element. The text which is visible on the page along with sub elements. It ignores all leading and trailing spaces. The getAttribute() method fetches the text contained by an attribute in an html document. If a value is not set for an attribute, null value is returned. The attribute is passed as a parameter to the method. So the getText() method gives the text present between the start and end html tags (which is not hidden by CSS) and the getAttribute() method identifies the key value pairs within the html tags. In the above html code, style is an attribute whose value can be obtained from getAttribute() method. If we apply the getText() method on that element, we shall get the text. Code Implementation with getText(). import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class GetTextMethd{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url ="https://www.tutorialspoint.com/videotutorials/subscription.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement l = driver.findElements(By.cssSelector("h2")); // extract text with getText() System.out.println("getText() method:" + l.getText()); driver.quit(); } } Code Implementation with getAttribute(). import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class GetAttributeMethd{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url ="https://www.tutorialspoint.com/videotutorials/subscription.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement l = driver.findElements(By.cssSelector("h2")); // get style attribute with getAttribute() System.out.println("getAttribute() method:" + l.getAttribute("style")); driver.quit(); } }
[ { "code": null, "e": 1309, "s": 1062, "text": "The differences between getText() and getAttribute() methods are described below. The getText() method returns the innerText of an element. The text which is visible on the page along with sub elements. It ignores all leading and trailing spaces." }, { "code": null, "e": 1517, "s": 1309, "text": "The getAttribute() method fetches the text contained by an attribute in an html document. If a value is not set for an attribute, null value is returned. The attribute is passed as a parameter to the method." }, { "code": null, "e": 1712, "s": 1517, "text": "So the getText() method gives the text present between the start and end html tags (which is not hidden by CSS) and the getAttribute() method identifies the key value pairs within the html tags." }, { "code": null, "e": 1887, "s": 1712, "text": "In the above html code, style is an attribute whose value can be obtained from getAttribute() method. If we apply the getText() method on that element, we shall get the text." }, { "code": null, "e": 1923, "s": 1887, "text": "Code Implementation with getText()." }, { "code": null, "e": 2734, "s": 1923, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class GetTextMethd{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url =\"https://www.tutorialspoint.com/videotutorials/subscription.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement l = driver.findElements(By.cssSelector(\"h2\"));\n // extract text with getText()\n System.out.println(\"getText() method:\" + l.getText());\n driver.quit();\n }\n}" }, { "code": null, "e": 2775, "s": 2734, "text": "Code Implementation with getAttribute()." }, { "code": null, "e": 3620, "s": 2775, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class GetAttributeMethd{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url =\"https://www.tutorialspoint.com/videotutorials/subscription.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement l = driver.findElements(By.cssSelector(\"h2\"));\n // get style attribute with getAttribute()\n System.out.println(\"getAttribute() method:\" + l.getAttribute(\"style\"));\n driver.quit();\n }\n}" } ]
UnionWith Method in C#
Use the UnionWith method in C# to get the union of i.e. unique lements from two collections. Let’s say the following are our Dictionary − Dictionary < string, int > dict1 = new Dictionary < string, int > (); dict1.Add("pencil", 1); dict1.Add("pen", 2); Dictionary < string, int > dict2 = new Dictionary < string, int > (); dict2.Add("pen", 3); Now, use HashSet and UnionWith to get the union − HashSet < string > hSet = new HashSet < string > (dict1.Keys); hSet.UnionWith(dict2.Keys); The following is the complete code − Live Demo using System; using System.Collections.Generic; public class Program { public static void Main() { Dictionary < string, int > dict1 = new Dictionary < string, int > (); dict1.Add("pencil", 1); dict1.Add("pen", 2); Dictionary < string, int > dict2 = new Dictionary < string, int > (); dict2.Add("pen", 3); HashSet < string > hSet = new HashSet <string > (dict1.Keys); hSet.UnionWith(dict2.Keys); Console.WriteLine("Merged Dictionary..."); foreach(string val in hSet) { Console.WriteLine(val); } } } Merged Dictionary... pencil pen
[ { "code": null, "e": 1155, "s": 1062, "text": "Use the UnionWith method in C# to get the union of i.e. unique lements from two collections." }, { "code": null, "e": 1200, "s": 1155, "text": "Let’s say the following are our Dictionary −" }, { "code": null, "e": 1406, "s": 1200, "text": "Dictionary < string, int > dict1 = new Dictionary < string, int > ();\ndict1.Add(\"pencil\", 1);\ndict1.Add(\"pen\", 2);\nDictionary < string, int > dict2 = new Dictionary < string, int > ();\ndict2.Add(\"pen\", 3);" }, { "code": null, "e": 1456, "s": 1406, "text": "Now, use HashSet and UnionWith to get the union −" }, { "code": null, "e": 1547, "s": 1456, "text": "HashSet < string > hSet = new HashSet < string > (dict1.Keys);\nhSet.UnionWith(dict2.Keys);" }, { "code": null, "e": 1584, "s": 1547, "text": "The following is the complete code −" }, { "code": null, "e": 1595, "s": 1584, "text": " Live Demo" }, { "code": null, "e": 2172, "s": 1595, "text": "using System;\nusing System.Collections.Generic;\n\npublic class Program {\n public static void Main() {\n Dictionary < string, int > dict1 = new Dictionary < string, int > ();\n dict1.Add(\"pencil\", 1);\n dict1.Add(\"pen\", 2);\n\n Dictionary < string, int > dict2 = new Dictionary < string, int > ();\n dict2.Add(\"pen\", 3);\n\n HashSet < string > hSet = new HashSet <string > (dict1.Keys);\n hSet.UnionWith(dict2.Keys);\n\n Console.WriteLine(\"Merged Dictionary...\");\n foreach(string val in hSet) {\n Console.WriteLine(val);\n }\n }\n}" }, { "code": null, "e": 2204, "s": 2172, "text": "Merged Dictionary...\npencil\npen" } ]
JavaScript Return an array that contains all the strings appearing in all the subarrays
We have an array of arrays like this − const arr = [ ['foo', 'bar', 'hey', 'oi'], ['foo', 'bar', 'hey'], ['foo', 'bar', 'anything'], ['bar', 'anything'] ] We are required to write a JavaScript function that takes in such array and returns an array that contains all the strings which appears in all the subarrays. Let's write the code for this function const arr = [ ['foo', 'bar', 'hey', 'oi'], ['foo', 'bar', 'hey'], ['foo', 'bar', 'anything'], ['bar', 'anything'] ] const commonArray = arr => { return arr.reduce((acc, val, index) => { return acc.filter(el => val.indexOf(el) !== -1); }); }; console.log(commonArray(arr)); The output in the console will be − ['bar']
[ { "code": null, "e": 1101, "s": 1062, "text": "We have an array of arrays like this −" }, { "code": null, "e": 1229, "s": 1101, "text": "const arr = [\n ['foo', 'bar', 'hey', 'oi'],\n ['foo', 'bar', 'hey'],\n ['foo', 'bar', 'anything'],\n ['bar', 'anything']\n]" }, { "code": null, "e": 1388, "s": 1229, "text": "We are required to write a JavaScript function that takes in such array and returns an array that\ncontains all the strings which appears in all the subarrays." }, { "code": null, "e": 1427, "s": 1388, "text": "Let's write the code for this function" }, { "code": null, "e": 1724, "s": 1427, "text": "const arr = [\n ['foo', 'bar', 'hey', 'oi'],\n ['foo', 'bar', 'hey'],\n ['foo', 'bar', 'anything'],\n ['bar', 'anything']\n]\nconst commonArray = arr => {\n return arr.reduce((acc, val, index) => {\n return acc.filter(el => val.indexOf(el) !== -1);\n });\n};\nconsole.log(commonArray(arr));" }, { "code": null, "e": 1760, "s": 1724, "text": "The output in the console will be −" }, { "code": null, "e": 1768, "s": 1760, "text": "['bar']" } ]
How to join two lists in C#?
To join two lists, use AddRange() method. Set the first list − var list1 = new List < string > (); list1.Add("Keyboard"); list1.Add("Mouse"); Set the second list − var list2 = new List < string > (); list2.Add("Hard Disk"); list2.Add("Pen Drive"); To concatenate both the lists − lists1.AddRange(lists2); The following is the complete code − using System.Collections.Generic; using System; namespace Demo { public static class Program { public static void Main() { var list1 = new List < string > (); list1.Add("Keyboard"); list1.Add("Mouse"); Console.WriteLine("Our list1...."); foreach(var p in list1) { Console.WriteLine(p); } var list2 = new List < string > (); list2.Add("Hard Disk"); list2.Add("Pen Drive"); Console.WriteLine("Our list2...."); foreach(var p in list2) { Console.WriteLine(p); } list1.AddRange(list2); Console.WriteLine("Concatenated list...."); foreach(var p in list1) { Console.WriteLine(p); } } } }
[ { "code": null, "e": 1104, "s": 1062, "text": "To join two lists, use AddRange() method." }, { "code": null, "e": 1125, "s": 1104, "text": "Set the first list −" }, { "code": null, "e": 1204, "s": 1125, "text": "var list1 = new List < string > ();\nlist1.Add(\"Keyboard\");\nlist1.Add(\"Mouse\");" }, { "code": null, "e": 1226, "s": 1204, "text": "Set the second list −" }, { "code": null, "e": 1310, "s": 1226, "text": "var list2 = new List < string > ();\nlist2.Add(\"Hard Disk\");\nlist2.Add(\"Pen Drive\");" }, { "code": null, "e": 1342, "s": 1310, "text": "To concatenate both the lists −" }, { "code": null, "e": 1367, "s": 1342, "text": "lists1.AddRange(lists2);" }, { "code": null, "e": 1404, "s": 1367, "text": "The following is the complete code −" }, { "code": null, "e": 2189, "s": 1404, "text": "using System.Collections.Generic;\nusing System;\n\nnamespace Demo {\n public static class Program {\n public static void Main() {\n var list1 = new List < string > ();\n list1.Add(\"Keyboard\");\n list1.Add(\"Mouse\");\n\n Console.WriteLine(\"Our list1....\");\n foreach(var p in list1) {\n Console.WriteLine(p);\n }\n\n var list2 = new List < string > ();\n list2.Add(\"Hard Disk\");\n list2.Add(\"Pen Drive\");\n\n Console.WriteLine(\"Our list2....\");\n foreach(var p in list2) {\n Console.WriteLine(p);\n }\n\n list1.AddRange(list2);\n\n Console.WriteLine(\"Concatenated list....\");\n foreach(var p in list1) {\n Console.WriteLine(p);\n }\n }\n }\n}" } ]
Boolean.Equals(Boolean) Method in C#
The Boolean.Equals(Boolean) method in C# returns a value indicating whether this instance is equal to a specified Boolean object. Following is the syntax − public bool Equals (bool ob); Above, ob is a Boolean value to compare to this instance. Let us now see an example to implement the Boolean.Equals(Boolean) method − using System; public class Demo { public static void Main(){ bool b1 = false; bool b2 = true; bool res = b1.Equals(b2); if (res == true) Console.Write("b1 equal to b2"); else Console.Write("b1 not equal to b2"); } } This will produce the following output − b1 not equal to b2
[ { "code": null, "e": 1192, "s": 1062, "text": "The Boolean.Equals(Boolean) method in C# returns a value indicating whether this instance is equal to a specified Boolean object." }, { "code": null, "e": 1218, "s": 1192, "text": "Following is the syntax −" }, { "code": null, "e": 1248, "s": 1218, "text": "public bool Equals (bool ob);" }, { "code": null, "e": 1306, "s": 1248, "text": "Above, ob is a Boolean value to compare to this instance." }, { "code": null, "e": 1382, "s": 1306, "text": "Let us now see an example to implement the Boolean.Equals(Boolean) method −" }, { "code": null, "e": 1652, "s": 1382, "text": "using System;\npublic class Demo {\n public static void Main(){\n bool b1 = false;\n bool b2 = true;\n bool res = b1.Equals(b2);\n if (res == true)\n Console.Write(\"b1 equal to b2\");\n else\n Console.Write(\"b1 not equal to b2\");\n }\n}" }, { "code": null, "e": 1693, "s": 1652, "text": "This will produce the following output −" }, { "code": null, "e": 1712, "s": 1693, "text": "b1 not equal to b2" } ]
Tracking Coronavirus(COVID-19) Spread in India using Python | by Pratik Nabriya | Towards Data Science
Coronavirus or COVID-19 needs no introduction. It has already been declared as a pandemic by WHO and in past couple of weeks it’s impact has been deleterious from both health perspective and an economic one. Plenty has been written about it, especially statistical reports on its exponential growth and the importance of “flattening the curve”. As of now, most of us are staying and working from home to avoid the spread of corona virus. I decided to utilize the surplus time to write a Python Script that pulls the latest Statewise data of COVID-19 cases from the official website of Ministry of Health and Family Welfare, Government of India and turn it into insightful visualizations using popular Python packages like GeoPandas, Seaborn and Matplotlib. Beautifulsoup — A library for pulling data out of html and xml files. Requests — A library for making HTTP requests in python. GeoPandas — A library for working with geospatial data in python. PrettyTable — quick and easy to represent tabular data in visually appealing ASCII tables. and other regular packages like Pandas, Matplotlib and Seaborn. If you don’t have any of the above mentioned packages installed on your system, please follow the installation instructions that are mentioned in the respective links. (Note that Geopandas further depends on fiona for file access and descartes and matplotlib for plotting) To scrape a website using Python, you need to perform these four basic steps: Sending an HTTP GET request to the URL of the webpage that you want to scrape, which will respond with the HTML content. We can do this by using the Request library of Python.Analyzing the HTML tags and their attributes, such as class, id, and other HTML tag attributes. Also, identifying your HTML tags where your content lives.Fetching and parsing the data using Beautifulsoup library and maintain the data in some data structure such as Dictionary or List.Output data in any file format such as csv, xlsx, json, etc. or use this tabulated data to make visualizations using Seaborn/Matplotlib libraries. Sending an HTTP GET request to the URL of the webpage that you want to scrape, which will respond with the HTML content. We can do this by using the Request library of Python. Analyzing the HTML tags and their attributes, such as class, id, and other HTML tag attributes. Also, identifying your HTML tags where your content lives. Fetching and parsing the data using Beautifulsoup library and maintain the data in some data structure such as Dictionary or List. Output data in any file format such as csv, xlsx, json, etc. or use this tabulated data to make visualizations using Seaborn/Matplotlib libraries. If you are new to web scraping, check this blog for the step-by-step explanation that can help you get started with web scarping using Python. www.pluralsight.com Import necessary libraries — import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport requestsfrom bs4 import BeautifulSoupimport geopandas as gpdfrom prettytable import PrettyTable Web Scraping — url = 'https://www.mohfw.gov.in/'# make a GET request to fetch the raw HTML contentweb_content = requests.get(url).content# parse the html contentsoup = BeautifulSoup(web_content, "html.parser")# remove any newlines and extra spaces from left and rightextract_contents = lambda row: [x.text.replace('\n', '') for x in row]# find all table rows and data cells withinstats = [] all_rows = soup.find_all('tr')for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat)#now convert the data into a pandas dataframe for further processingnew_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"]state_data = pd.DataFrame(data = stats, columns = new_cols)state_data.head() Output: Before we proceed further, notice that the scraped data columns are actually of ‘string’ datatype. We need to convert them into ‘int’ datatype. state_data[‘Confirmed’] = state_data[‘Confirmed’].map(int)state_data[‘Recovered’] = state_data[‘Recovered’].map(int)state_data[‘Deceased’] = state_data[‘Deceased’].map(int) You may also choose to present the data using PrettyTable table = PrettyTable()table.field_names = (new_cols)for i in stats: table.add_row(i)table.add_row([“”,”Total”, sum(state_data[‘Confirmed’]), sum(state_data[‘Recovered’]), sum(state_data[‘Deceased’])print(table) Output: (This is the latest available data at the time of writing this article) Plotting horizontal barplot to show the statewise total confirmed cases — sns.set_style(“ticks”)plt.figure(figsize = (15,10))plt.barh(state_data[“States/UT”], state_data[“Confirmed”].map(int),align = ‘center’, color = ‘lightblue’, edgecolor = ‘blue’)plt.xlabel(‘No. of Confirmed cases’, fontsize = 18)plt.ylabel(‘States/UT’, fontsize = 18)plt.gca().invert_yaxis()plt.xticks(fontsize = 14)plt.yticks(fontsize = 14)plt.title(‘Total Confirmed Cases Statewise’, fontsize = 18 )for index, value in enumerate(state_data[“Confirmed”]): plt.text(value, index, str(value), fontsize = 12)plt.show() Output: group_size = [sum(state_data[‘Confirmed’]), sum(state_data[‘Recovered’]), sum(state_data[‘Deceased’])]group_labels = [‘Confirmed\n’ + str(sum(state_data[‘Confirmed’])), ‘Recovered\n’ + str(sum(state_data[‘Recovered’])), ‘Deceased\n’ + str(sum(state_data[‘Deceased’]))]custom_colors = [‘skyblue’,’yellowgreen’,’tomato’]plt.figure(figsize = (5,5))plt.pie(group_size, labels = group_labels, colors = custom_colors)central_circle = plt.Circle((0,0), 0.5, color = ‘white’)fig = plt.gcf()fig.gca().add_artist(central_circle)plt.rc(‘font’, size = 12)plt.title(‘Nationwide total Confirmed, Recovered and Deceased Cases’, fontsize = 20)plt.show() Output: The shape files used in this article to plot the India map with state boundaries can be downloaded from here. # reading the shape file of map of India in GeoDataFramemap_data = gpd.read_file(‘Indian_States.shp’)map_data.rename(columns = {‘st_nm’:’States/UT’}, inplace = True)map_data.head() Output: I noticed that the names of some of the States and Union Territories(UT) and in the shape file were not consistent with the state names on the government website. So, I modified the State/UT names in the GeoDataFrame to match with the ones on our State dataframe. Correcting spellings of states in map_data dataframe — map_data[‘States/UT’] = map_data[‘States/UT’].str.replace(‘&’,‘and’)map_data[‘States/UT’].replace(‘Arunanchal Pradesh’, ‘Arunachal Pradesh’, inplace = True)map_data[‘States/UT’].replace(‘Telangana’, ‘Telengana’, inplace = True)map_data[‘States/UT’].replace(‘NCT of Delhi’, ‘Delhi’, inplace = True)map_data['States/UT'].replace('Andaman and Nicobar Island', 'Andaman and Nicobar Islands', inplace = True) Merge the two dataframes state_data and map_data on States/UT names — merged_data = pd.merge(map_data, state_data, how = ‘left’, on = ‘States/UT’)merged_data.fillna(0, inplace = True)merged_data.drop(‘Sr.No’, axis = 1, inplace = True)merged_data.head() Output: Display the Statewise data on the map of India — fig, ax = plt.subplots(1, figsize=(20, 12))ax.axis(‘off’)ax.set_title(‘Covid-19 Statewise Data — Confirmed Cases’, fontdict = {‘fontsize’: ‘25’, ‘fontweight’ : ‘3’})merged_data.plot(column = ‘Confirmed’, cmap=’YlOrRd’, linewidth=0.8, ax=ax, edgecolor=’0.8', legend = True)plt.show() Output: Covid-19 hasn’t yet hit India in a widespread way. The missing pieces of data are making it impossible to predict how the outbreak will unfold in the coming months. As I conclude this article, I pray for the safety and well-being of everyone in India and around the world. Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
[ { "code": null, "e": 517, "s": 172, "text": "Coronavirus or COVID-19 needs no introduction. It has already been declared as a pandemic by WHO and in past couple of weeks it’s impact has been deleterious from both health perspective and an economic one. Plenty has been written about it, especially statistical reports on its exponential growth and the importance of “flattening the curve”." }, { "code": null, "e": 929, "s": 517, "text": "As of now, most of us are staying and working from home to avoid the spread of corona virus. I decided to utilize the surplus time to write a Python Script that pulls the latest Statewise data of COVID-19 cases from the official website of Ministry of Health and Family Welfare, Government of India and turn it into insightful visualizations using popular Python packages like GeoPandas, Seaborn and Matplotlib." }, { "code": null, "e": 999, "s": 929, "text": "Beautifulsoup — A library for pulling data out of html and xml files." }, { "code": null, "e": 1056, "s": 999, "text": "Requests — A library for making HTTP requests in python." }, { "code": null, "e": 1122, "s": 1056, "text": "GeoPandas — A library for working with geospatial data in python." }, { "code": null, "e": 1213, "s": 1122, "text": "PrettyTable — quick and easy to represent tabular data in visually appealing ASCII tables." }, { "code": null, "e": 1277, "s": 1213, "text": "and other regular packages like Pandas, Matplotlib and Seaborn." }, { "code": null, "e": 1445, "s": 1277, "text": "If you don’t have any of the above mentioned packages installed on your system, please follow the installation instructions that are mentioned in the respective links." }, { "code": null, "e": 1550, "s": 1445, "text": "(Note that Geopandas further depends on fiona for file access and descartes and matplotlib for plotting)" }, { "code": null, "e": 1628, "s": 1550, "text": "To scrape a website using Python, you need to perform these four basic steps:" }, { "code": null, "e": 2234, "s": 1628, "text": "Sending an HTTP GET request to the URL of the webpage that you want to scrape, which will respond with the HTML content. We can do this by using the Request library of Python.Analyzing the HTML tags and their attributes, such as class, id, and other HTML tag attributes. Also, identifying your HTML tags where your content lives.Fetching and parsing the data using Beautifulsoup library and maintain the data in some data structure such as Dictionary or List.Output data in any file format such as csv, xlsx, json, etc. or use this tabulated data to make visualizations using Seaborn/Matplotlib libraries." }, { "code": null, "e": 2410, "s": 2234, "text": "Sending an HTTP GET request to the URL of the webpage that you want to scrape, which will respond with the HTML content. We can do this by using the Request library of Python." }, { "code": null, "e": 2565, "s": 2410, "text": "Analyzing the HTML tags and their attributes, such as class, id, and other HTML tag attributes. Also, identifying your HTML tags where your content lives." }, { "code": null, "e": 2696, "s": 2565, "text": "Fetching and parsing the data using Beautifulsoup library and maintain the data in some data structure such as Dictionary or List." }, { "code": null, "e": 2843, "s": 2696, "text": "Output data in any file format such as csv, xlsx, json, etc. or use this tabulated data to make visualizations using Seaborn/Matplotlib libraries." }, { "code": null, "e": 2986, "s": 2843, "text": "If you are new to web scraping, check this blog for the step-by-step explanation that can help you get started with web scarping using Python." }, { "code": null, "e": 3006, "s": 2986, "text": "www.pluralsight.com" }, { "code": null, "e": 3035, "s": 3006, "text": "Import necessary libraries —" }, { "code": null, "e": 3209, "s": 3035, "text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport requestsfrom bs4 import BeautifulSoupimport geopandas as gpdfrom prettytable import PrettyTable" }, { "code": null, "e": 3224, "s": 3209, "text": "Web Scraping —" }, { "code": null, "e": 4023, "s": 3224, "text": "url = 'https://www.mohfw.gov.in/'# make a GET request to fetch the raw HTML contentweb_content = requests.get(url).content# parse the html contentsoup = BeautifulSoup(web_content, \"html.parser\")# remove any newlines and extra spaces from left and rightextract_contents = lambda row: [x.text.replace('\\n', '') for x in row]# find all table rows and data cells withinstats = [] all_rows = soup.find_all('tr')for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat)#now convert the data into a pandas dataframe for further processingnew_cols = [\"Sr.No\", \"States/UT\",\"Confirmed\",\"Recovered\",\"Deceased\"]state_data = pd.DataFrame(data = stats, columns = new_cols)state_data.head()" }, { "code": null, "e": 4031, "s": 4023, "text": "Output:" }, { "code": null, "e": 4175, "s": 4031, "text": "Before we proceed further, notice that the scraped data columns are actually of ‘string’ datatype. We need to convert them into ‘int’ datatype." }, { "code": null, "e": 4348, "s": 4175, "text": "state_data[‘Confirmed’] = state_data[‘Confirmed’].map(int)state_data[‘Recovered’] = state_data[‘Recovered’].map(int)state_data[‘Deceased’] = state_data[‘Deceased’].map(int)" }, { "code": null, "e": 4406, "s": 4348, "text": "You may also choose to present the data using PrettyTable" }, { "code": null, "e": 4663, "s": 4406, "text": "table = PrettyTable()table.field_names = (new_cols)for i in stats: table.add_row(i)table.add_row([“”,”Total”, sum(state_data[‘Confirmed’]), sum(state_data[‘Recovered’]), sum(state_data[‘Deceased’])print(table)" }, { "code": null, "e": 4671, "s": 4663, "text": "Output:" }, { "code": null, "e": 4743, "s": 4671, "text": "(This is the latest available data at the time of writing this article)" }, { "code": null, "e": 4817, "s": 4743, "text": "Plotting horizontal barplot to show the statewise total confirmed cases —" }, { "code": null, "e": 5338, "s": 4817, "text": "sns.set_style(“ticks”)plt.figure(figsize = (15,10))plt.barh(state_data[“States/UT”], state_data[“Confirmed”].map(int),align = ‘center’, color = ‘lightblue’, edgecolor = ‘blue’)plt.xlabel(‘No. of Confirmed cases’, fontsize = 18)plt.ylabel(‘States/UT’, fontsize = 18)plt.gca().invert_yaxis()plt.xticks(fontsize = 14)plt.yticks(fontsize = 14)plt.title(‘Total Confirmed Cases Statewise’, fontsize = 18 )for index, value in enumerate(state_data[“Confirmed”]): plt.text(value, index, str(value), fontsize = 12)plt.show()" }, { "code": null, "e": 5346, "s": 5338, "text": "Output:" }, { "code": null, "e": 6040, "s": 5346, "text": "group_size = [sum(state_data[‘Confirmed’]), sum(state_data[‘Recovered’]), sum(state_data[‘Deceased’])]group_labels = [‘Confirmed\\n’ + str(sum(state_data[‘Confirmed’])), ‘Recovered\\n’ + str(sum(state_data[‘Recovered’])), ‘Deceased\\n’ + str(sum(state_data[‘Deceased’]))]custom_colors = [‘skyblue’,’yellowgreen’,’tomato’]plt.figure(figsize = (5,5))plt.pie(group_size, labels = group_labels, colors = custom_colors)central_circle = plt.Circle((0,0), 0.5, color = ‘white’)fig = plt.gcf()fig.gca().add_artist(central_circle)plt.rc(‘font’, size = 12)plt.title(‘Nationwide total Confirmed, Recovered and Deceased Cases’, fontsize = 20)plt.show()" }, { "code": null, "e": 6048, "s": 6040, "text": "Output:" }, { "code": null, "e": 6158, "s": 6048, "text": "The shape files used in this article to plot the India map with state boundaries can be downloaded from here." }, { "code": null, "e": 6339, "s": 6158, "text": "# reading the shape file of map of India in GeoDataFramemap_data = gpd.read_file(‘Indian_States.shp’)map_data.rename(columns = {‘st_nm’:’States/UT’}, inplace = True)map_data.head()" }, { "code": null, "e": 6347, "s": 6339, "text": "Output:" }, { "code": null, "e": 6611, "s": 6347, "text": "I noticed that the names of some of the States and Union Territories(UT) and in the shape file were not consistent with the state names on the government website. So, I modified the State/UT names in the GeoDataFrame to match with the ones on our State dataframe." }, { "code": null, "e": 6666, "s": 6611, "text": "Correcting spellings of states in map_data dataframe —" }, { "code": null, "e": 7220, "s": 6666, "text": "map_data[‘States/UT’] = map_data[‘States/UT’].str.replace(‘&’,‘and’)map_data[‘States/UT’].replace(‘Arunanchal Pradesh’, ‘Arunachal Pradesh’, inplace = True)map_data[‘States/UT’].replace(‘Telangana’, ‘Telengana’, inplace = True)map_data[‘States/UT’].replace(‘NCT of Delhi’, ‘Delhi’, inplace = True)map_data['States/UT'].replace('Andaman and Nicobar Island', 'Andaman and Nicobar Islands', inplace = True)" }, { "code": null, "e": 7290, "s": 7220, "text": "Merge the two dataframes state_data and map_data on States/UT names —" }, { "code": null, "e": 7496, "s": 7290, "text": "merged_data = pd.merge(map_data, state_data, how = ‘left’, on = ‘States/UT’)merged_data.fillna(0, inplace = True)merged_data.drop(‘Sr.No’, axis = 1, inplace = True)merged_data.head()" }, { "code": null, "e": 7504, "s": 7496, "text": "Output:" }, { "code": null, "e": 7553, "s": 7504, "text": "Display the Statewise data on the map of India —" }, { "code": null, "e": 7884, "s": 7553, "text": "fig, ax = plt.subplots(1, figsize=(20, 12))ax.axis(‘off’)ax.set_title(‘Covid-19 Statewise Data — Confirmed Cases’, fontdict = {‘fontsize’: ‘25’, ‘fontweight’ : ‘3’})merged_data.plot(column = ‘Confirmed’, cmap=’YlOrRd’, linewidth=0.8, ax=ax, edgecolor=’0.8', legend = True)plt.show()" }, { "code": null, "e": 7892, "s": 7884, "text": "Output:" }, { "code": null, "e": 8165, "s": 7892, "text": "Covid-19 hasn’t yet hit India in a widespread way. The missing pieces of data are making it impossible to predict how the outbreak will unfold in the coming months. As I conclude this article, I pray for the safety and well-being of everyone in India and around the world." } ]
Difference between JavaScript and PHP - GeeksforGeeks
18 Apr, 2022 In this article, we will know about Javascript & PHP, along with understanding their significant differences. A long time before, most people used to think PHP is a server-side language and Javascript as client-side language as it was only executed in web browsers. But after V8, Node and other frameworks came, Javascript is capable of doing a lot of things Php used to. Since we can handle both front-end and back-end through Javascript now, It’s considered as more powerful than PHP. JavaScript: It is the most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. Syntax: <script> document.write("JavaScript syntax"); </script> You can place the tags, anywhere within your web page, but it is normally recommended to keep it within the <head> tag. This tag tells the browser to start interpreting all the text between these tags as JavaScript code. Example 1: This example describes the Javascript basic example to print the text for the specified time using the for loop. HTML <!DOCTYPE html><html><title>Basic JavaScript Example</title><body> <h2>A simple JavaScript program</h2> <script> var n; n = 5; // JavaScript uses the var keyword to declare variables. // An equal sign is used to assign values to variables. for(var i = 0; i < n; i++) { document.write("GeeksforGeeks " + "<br>"); } </script></body> </html> Output: A simple JavaScript program GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Example 2: This example illustrates Javascript getElementById() method where element_id is used to get the text. HTML <!DOCTYPE html><html><title>Javascript Example</title><style> #gfg { font-size: 40px; color: #006400; }</style> <body> <h2 id="gfg">GeeksforGeeks</h2> <button onclick="myFunction()">Click Me!</button> <script> function myFunction() { document.getElementById("gfg").innerHTML = "Hello Geeks!"; } </script></body> </html> Output: Getting the element using getElementById Method PHP: PHP is an acronym for Hypertext Preprocessor, which is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. Like Javascript, PHP can also be written in HTML code and in the .php file extension itself too. But it requires a server to run, so you won’t be able to see an output of the code. in a simple manner. Syntax: <?php echo "Hello Geeks!!!"; ?> Steps to run the PHP code: You can install Xampp or any other local server app. After installing Xampp, name your code file with the extension .php and move your Html or Php file to htdocs folder of xampp. Now, open xampp, run apache, and SQL server, & now go to localhost with your file URL (type localhost/folder name/filename.php or localhost/filename.php in your browser) and there you can see the output. PHP code starts with <?php and ends with ?>. This is to tell the compiler/server that the PHP language starts here. Example 1: This example describes the PHP for loop to display the repeated output. HTML <!DOCTYPE html><html><title>PHP Code inside the HTML</title><body> <?php // Declare variables using $ symbol $str= "GeeksforGeeks"; $x = 5; // PHP for loop for( $i = 0; $i< $x; $i++ ) { echo ("GeeksforGeeks"); } ?> <!--This code will print GeeksforGeeks 5 times on front end--></body> </html> Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Difference between Javascript vs PHP: thor98571 bhaskargeeksforgeeks itskawal2000 JavaScript-Misc JavaScript PHP Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 24540, "s": 24512, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24650, "s": 24540, "text": "In this article, we will know about Javascript & PHP, along with understanding their significant differences." }, { "code": null, "e": 25027, "s": 24650, "text": "A long time before, most people used to think PHP is a server-side language and Javascript as client-side language as it was only executed in web browsers. But after V8, Node and other frameworks came, Javascript is capable of doing a lot of things Php used to. Since we can handle both front-end and back-end through Javascript now, It’s considered as more powerful than PHP." }, { "code": null, "e": 25357, "s": 25027, "text": "JavaScript: It is the most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments." }, { "code": null, "e": 25366, "s": 25357, "text": "Syntax: " }, { "code": null, "e": 25426, "s": 25366, "text": "<script>\n document.write(\"JavaScript syntax\");\n</script>" }, { "code": null, "e": 25648, "s": 25426, "text": "You can place the tags, anywhere within your web page, but it is normally recommended to keep it within the <head> tag. This tag tells the browser to start interpreting all the text between these tags as JavaScript code. " }, { "code": null, "e": 25772, "s": 25648, "text": "Example 1: This example describes the Javascript basic example to print the text for the specified time using the for loop." }, { "code": null, "e": 25777, "s": 25772, "text": "HTML" }, { "code": "<!DOCTYPE html><html><title>Basic JavaScript Example</title><body> <h2>A simple JavaScript program</h2> <script> var n; n = 5; // JavaScript uses the var keyword to declare variables. // An equal sign is used to assign values to variables. for(var i = 0; i < n; i++) { document.write(\"GeeksforGeeks \" + \"<br>\"); } </script></body> </html>", "e": 26196, "s": 25777, "text": null }, { "code": null, "e": 26204, "s": 26196, "text": "Output:" }, { "code": null, "e": 26307, "s": 26204, "text": "A simple JavaScript program\nGeeksforGeeks \nGeeksforGeeks \nGeeksforGeeks \nGeeksforGeeks \nGeeksforGeeks " }, { "code": null, "e": 26420, "s": 26307, "text": "Example 2: This example illustrates Javascript getElementById() method where element_id is used to get the text." }, { "code": null, "e": 26425, "s": 26420, "text": "HTML" }, { "code": "<!DOCTYPE html><html><title>Javascript Example</title><style> #gfg { font-size: 40px; color: #006400; }</style> <body> <h2 id=\"gfg\">GeeksforGeeks</h2> <button onclick=\"myFunction()\">Click Me!</button> <script> function myFunction() { document.getElementById(\"gfg\").innerHTML = \"Hello Geeks!\"; } </script></body> </html>", "e": 26802, "s": 26425, "text": null }, { "code": null, "e": 26810, "s": 26802, "text": "Output:" }, { "code": null, "e": 26858, "s": 26810, "text": "Getting the element using getElementById Method" }, { "code": null, "e": 27286, "s": 26858, "text": "PHP: PHP is an acronym for Hypertext Preprocessor, which is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. Like Javascript, PHP can also be written in HTML code and in the .php file extension itself too. But it requires a server to run, so you won’t be able to see an output of the code. in a simple manner." }, { "code": null, "e": 27294, "s": 27286, "text": "Syntax:" }, { "code": null, "e": 27331, "s": 27294, "text": "<?php\n echo \"Hello Geeks!!!\";\n?> " }, { "code": null, "e": 27359, "s": 27331, "text": "Steps to run the PHP code: " }, { "code": null, "e": 27860, "s": 27359, "text": "You can install Xampp or any other local server app. After installing Xampp, name your code file with the extension .php and move your Html or Php file to htdocs folder of xampp. Now, open xampp, run apache, and SQL server, & now go to localhost with your file URL (type localhost/folder name/filename.php or localhost/filename.php in your browser) and there you can see the output. PHP code starts with <?php and ends with ?>. This is to tell the compiler/server that the PHP language starts here. " }, { "code": null, "e": 27943, "s": 27860, "text": "Example 1: This example describes the PHP for loop to display the repeated output." }, { "code": null, "e": 27948, "s": 27943, "text": "HTML" }, { "code": "<!DOCTYPE html><html><title>PHP Code inside the HTML</title><body> <?php // Declare variables using $ symbol $str= \"GeeksforGeeks\"; $x = 5; // PHP for loop for( $i = 0; $i< $x; $i++ ) { echo (\"GeeksforGeeks\"); } ?> <!--This code will print GeeksforGeeks 5 times on front end--></body> </html>", "e": 28287, "s": 27948, "text": null }, { "code": null, "e": 28295, "s": 28287, "text": "Output:" }, { "code": null, "e": 28365, "s": 28295, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks" }, { "code": null, "e": 28403, "s": 28365, "text": "Difference between Javascript vs PHP:" }, { "code": null, "e": 28413, "s": 28403, "text": "thor98571" }, { "code": null, "e": 28434, "s": 28413, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28447, "s": 28434, "text": "itskawal2000" }, { "code": null, "e": 28463, "s": 28447, "text": "JavaScript-Misc" }, { "code": null, "e": 28474, "s": 28463, "text": "JavaScript" }, { "code": null, "e": 28478, "s": 28474, "text": "PHP" }, { "code": null, "e": 28505, "s": 28478, "text": "Web technologies Questions" }, { "code": null, "e": 28509, "s": 28505, "text": "PHP" }, { "code": null, "e": 28607, "s": 28509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28652, "s": 28607, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28713, "s": 28652, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28785, "s": 28713, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28837, "s": 28785, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28883, "s": 28837, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28928, "s": 28883, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 28978, "s": 28928, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29002, "s": 28978, "text": "PHP in_array() Function" }, { "code": null, "e": 29042, "s": 29002, "text": "How to convert array to string in PHP ?" } ]
How to sort an array with customized Comparator in Java?
Let’s say the following is our string array and we need to sort it: String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" }; Within the sort() method, create a customized comparator to sort the above string. Here, two strings are compared with each other and the process goes on: Arrays.sort(str, new Comparator < String > () { public int compare(String one, String two) { int val = two.length() - one.length(); if (val == 0) val = one.compareToIgnoreCase(two); return val; } }); import java.util.Arrays; import java.util.Comparator; public class Demo { public static void main(String[] args) { String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" }; System.out.println("Array..."); for (String res : str) System.out.print(res + " "); Arrays.sort(str, new Comparator<String>() { public int compare(String one, String two) { int val = two.length() - one.length(); if (val == 0) val = one.compareToIgnoreCase(two); return val; } }); System.out.println("\nSorted array..."); for (String res : str) System.out.print(res + " "); } } Array... Tom Jack Harry Zen Tim David Sorted array... David Harry Jack Tim Tom Zen
[ { "code": null, "e": 1130, "s": 1062, "text": "Let’s say the following is our string array and we need to sort it:" }, { "code": null, "e": 1196, "s": 1130, "text": "String[] str = { \"Tom\", \"Jack\", \"Harry\", \"Zen\", \"Tim\", \"David\" };" }, { "code": null, "e": 1351, "s": 1196, "text": "Within the sort() method, create a customized comparator to sort the above string. Here, two strings are compared with each other and the process goes on:" }, { "code": null, "e": 1581, "s": 1351, "text": "Arrays.sort(str, new Comparator < String > () {\n public int compare(String one, String two) {\n int val = two.length() - one.length();\n if (val == 0)\n val = one.compareToIgnoreCase(two);\n return val;\n }\n});" }, { "code": null, "e": 2271, "s": 1581, "text": "import java.util.Arrays;\nimport java.util.Comparator;\npublic class Demo {\n public static void main(String[] args) {\n String[] str = { \"Tom\", \"Jack\", \"Harry\", \"Zen\", \"Tim\", \"David\" };\n System.out.println(\"Array...\");\n for (String res : str)\n System.out.print(res + \" \");\n Arrays.sort(str, new Comparator<String>() {\n public int compare(String one, String two) {\n int val = two.length() - one.length();\n if (val == 0)\n val = one.compareToIgnoreCase(two);\n return val;\n }\n });\n System.out.println(\"\\nSorted array...\");\n for (String res : str)\n System.out.print(res + \" \");\n }\n}" }, { "code": null, "e": 2354, "s": 2271, "text": "Array...\nTom Jack Harry Zen Tim David\nSorted array...\nDavid Harry Jack Tim Tom Zen" } ]
Groovy - XML
XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications. The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQLbased backbone. The Groovy language also provides a rich support of the XML language. The two most basic XML classes used are − XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node. XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node. XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently. <collection shelf = "New Arrivals"> <movie title = "Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = "Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = "Trigun"> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>10</stars> <description>Vash the Stam pede!</description> </movie> <movie title = "Ishtar"> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom </description> </movie> </collection> public MarkupBuilder() The MarkupBuilder is used to construct the entire XML document. The XML document is created by first creating an object of the XML document class. Once the object is created, a pseudomethod can be called to create the various elements of the XML document. Let’s look at an example of how to create one block, that is, one movie element from the above XML document − import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mB = new MarkupBuilder() // Compose the builder mB.collection(shelf : 'New Arrivals') { movie(title : 'Enemy Behind') type('War, Thriller') format('DVD') year('2003') rating('PG') stars(10) description('Talk about a US-Japan war') } } } In the above example, the following things need to be noted − mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection> mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection> movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element. movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element. A closure is provided to the pseudomethod to create the remaining elements of the XML document. A closure is provided to the pseudomethod to create the remaining elements of the XML document. The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream When we run the above program, we will get the following result − <collection shelf = 'New Arrivals'> <movie title = 'Enemy Behind' /> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> </collection> In order to create the entire XML document, the following things need to be done. A map entry needs to be created to store the different values of the elements. For each element of the map, we are assigning the value to each element. import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003', 'PG', '10','Talk about a US-Japan war'], 2 : ['Transformers','Anime, Science Fiction','DVD','1989', 'R', '8','A scientific fiction'], 3 : ['Trigun','Anime, Action','DVD','1986', 'PG', '10','Vash the Stam pede'], 4 : ['Ishtar','Comedy','VHS','1987', 'PG', '2','Viewable boredom ']] def mB = new MarkupBuilder() // Compose the builder def MOVIEDB = mB.collection('shelf': 'New Arrivals') { mp.each { sd -> mB.movie('title': sd.value[0]) { type(sd.value[1]) format(sd.value[2]) year(sd.value[3]) rating(sd.value[4]) stars(sd.value[4]) description(sd.value[5]) } } } } } When we run the above program, we will get the following result − <collection shelf = 'New Arrivals'> <movie title = 'Enemy Behind'> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = 'Transformers'> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>R</stars> <description>8</description> </movie> <movie title = 'Trigun'> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = 'Ishtar'> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>PG</stars> <description>2</description> </movie> </collection> The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. public XmlParser() throws ParserConfigurationException, SAXException The following codeshows an example of how the XML parser can be used to read an XML document. Let’s assume we have the same document called Movies.xml and we wanted to parse the XML document and display a proper output to the user. The following codeis a snippet of how we can traverse through the entire content of the XML document and display a proper response to the user. import groovy.xml.MarkupBuilder import groovy.util.* class Example { static void main(String[] args) { def parser = new XmlParser() def doc = parser.parse("D:\\Movies.xml"); doc.movie.each{ bk-> print("Movie Name:") println "${bk['@title']}" print("Movie Type:") println "${bk.type[0].text()}" print("Movie Format:") println "${bk.format[0].text()}" print("Movie year:") println "${bk.year[0].text()}" print("Movie rating:") println "${bk.rating[0].text()}" print("Movie stars:") println "${bk.stars[0].text()}" print("Movie description:") println "${bk.description[0].text()}" println("*******************************") } } } When we run the above program, we will get the following result − Movie Name:Enemy Behind Movie Type:War, Thriller Movie Format:DVD Movie year:2003 Movie rating:PG Movie stars:10 Movie description:Talk about a US-Japan war ******************************* Movie Name:Transformers Movie Type:Anime, Science Fiction Movie Format:DVD Movie year:1989 Movie rating:R Movie stars:8 Movie description:A schientific fiction ******************************* Movie Name:Trigun Movie Type:Anime, Action Movie Format:DVD Movie year:1986 Movie rating:PG Movie stars:10 Movie description:Vash the Stam pede! ******************************* Movie Name:Ishtar Movie Type:Comedy Movie Format:VHS Movie year:1987 Movie rating:PG Movie stars:2 Movie description:Viewable boredom The important things to note about the above code. An object of the class XmlParser is being formed so that it can be used to parse the XML document. An object of the class XmlParser is being formed so that it can be used to parse the XML document. The parser is given the location of the XML file. The parser is given the location of the XML file. For each movie element, we are using a closure to browse through each child node and display the relevant information. For each movie element, we are using a closure to browse through each child node and display the relevant information. For the movie element itself, we are using the @ symbol to display the title attribute attached to the movie element. 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2238, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications." }, { "code": null, "e": 2800, "s": 2516, "text": "The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQLbased backbone." }, { "code": null, "e": 2912, "s": 2800, "text": "The Groovy language also provides a rich support of the XML language. The two most basic XML classes used are −" }, { "code": null, "e": 3446, "s": 2912, "text": "XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node." }, { "code": null, "e": 3980, "s": 3446, "text": "XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node." }, { "code": null, "e": 4268, "s": 3980, "text": "XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 4556, "s": 4268, "text": "XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 4706, "s": 4556, "text": "For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently." }, { "code": null, "e": 5723, "s": 4706, "text": "<collection shelf = \"New Arrivals\"> \n\n <movie title = \"Enemy Behind\"> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Talk about a US-Japan war</description> \n </movie> \n\t\n <movie title = \"Transformers\"> \n <type>Anime, Science Fiction</type>\n <format>DVD</format> \n <year>1989</year> \n <rating>R</rating> \n <stars>8</stars> \n <description>A schientific fiction</description> \n </movie> \n\t\n <movie title = \"Trigun\"> \n <type>Anime, Action</type> \n <format>DVD</format> \n <year>1986</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Vash the Stam pede!</description> \n </movie> \n\t\n <movie title = \"Ishtar\"> \n <type>Comedy</type> \n <format>VHS</format> \n <year>1987</year> \n <rating>PG</rating> \n <stars>2</stars> \n <description>Viewable boredom </description> \n </movie> \n\t\n</collection> " }, { "code": null, "e": 5747, "s": 5723, "text": "public MarkupBuilder()\n" }, { "code": null, "e": 6003, "s": 5747, "text": "The MarkupBuilder is used to construct the entire XML document. The XML document is created by first creating an object of the XML document class. Once the object is created, a pseudomethod can be called to create the various elements of the XML document." }, { "code": null, "e": 6113, "s": 6003, "text": "Let’s look at an example of how to create one block, that is, one movie element from the above XML document −" }, { "code": null, "e": 6536, "s": 6113, "text": "import groovy.xml.MarkupBuilder \n\nclass Example {\n static void main(String[] args) {\n def mB = new MarkupBuilder()\n\t\t\n // Compose the builder\n mB.collection(shelf : 'New Arrivals') {\n movie(title : 'Enemy Behind')\n type('War, Thriller')\n format('DVD')\n year('2003')\n rating('PG')\n stars(10)\n description('Talk about a US-Japan war') \n }\n } \n}" }, { "code": null, "e": 6598, "s": 6536, "text": "In the above example, the following things need to be noted −" }, { "code": null, "e": 6702, "s": 6598, "text": "mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection>" }, { "code": null, "e": 6806, "s": 6702, "text": "mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection>" }, { "code": null, "e": 7046, "s": 6806, "text": "movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element." }, { "code": null, "e": 7286, "s": 7046, "text": "movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element." }, { "code": null, "e": 7382, "s": 7286, "text": "A closure is provided to the pseudomethod to create the remaining elements of the XML document." }, { "code": null, "e": 7478, "s": 7382, "text": "A closure is provided to the pseudomethod to create the remaining elements of the XML document." }, { "code": null, "e": 7611, "s": 7478, "text": "The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream" }, { "code": null, "e": 7744, "s": 7611, "text": "The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream" }, { "code": null, "e": 7810, "s": 7744, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 8111, "s": 7810, "text": "<collection shelf = 'New Arrivals'> \n <movie title = 'Enemy Behind' /> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Talk about a US-Japan war</description> \n </movie> \n</collection>\n" }, { "code": null, "e": 8193, "s": 8111, "text": "In order to create the entire XML document, the following things need to be done." }, { "code": null, "e": 8272, "s": 8193, "text": "A map entry needs to be created to store the different values of the elements." }, { "code": null, "e": 8345, "s": 8272, "text": "For each element of the map, we are assigning the value to each element." }, { "code": null, "e": 9322, "s": 8345, "text": "import groovy.xml.MarkupBuilder \n\nclass Example {\n static void main(String[] args) {\n def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003', \n 'PG', '10','Talk about a US-Japan war'],\n 2 : ['Transformers','Anime, Science Fiction','DVD','1989', \n 'R', '8','A scientific fiction'],\n 3 : ['Trigun','Anime, Action','DVD','1986', \n 'PG', '10','Vash the Stam pede'],\n 4 : ['Ishtar','Comedy','VHS','1987', 'PG', \n '2','Viewable boredom ']] \n\t\t\t\n def mB = new MarkupBuilder() \n\t\t\n // Compose the builder\n def MOVIEDB = mB.collection('shelf': 'New Arrivals') {\n mp.each {\n sd -> \n mB.movie('title': sd.value[0]) { \n type(sd.value[1])\n format(sd.value[2])\n year(sd.value[3]) \n rating(sd.value[4])\n stars(sd.value[4]) \n description(sd.value[5]) \n }\n }\n }\n } \n} " }, { "code": null, "e": 9388, "s": 9322, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 10319, "s": 9388, "text": "<collection shelf = 'New Arrivals'> \n <movie title = 'Enemy Behind'> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>10</description> \n </movie> \n <movie title = 'Transformers'> \n <type>Anime, Science Fiction</type> \n <format>DVD</format> \n <year>1989</year>\n\t <rating>R</rating> \n <stars>R</stars> \n <description>8</description> \n </movie> \n <movie title = 'Trigun'> \n <type>Anime, Action</type> \n <format>DVD</format> \n <year>1986</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>10</description> \n </movie> \n <movie title = 'Ishtar'> \n <type>Comedy</type> \n <format>VHS</format> \n <year>1987</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>2</description> \n </movie> \n</collection> \n" }, { "code": null, "e": 10594, "s": 10319, "text": "The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 10675, "s": 10594, "text": "public XmlParser() \n throws ParserConfigurationException, \n SAXException\n" }, { "code": null, "e": 10769, "s": 10675, "text": "The following codeshows an example of how the XML parser can be used to read an XML document." }, { "code": null, "e": 11051, "s": 10769, "text": "Let’s assume we have the same document called Movies.xml and we wanted to parse the XML document and display a proper output to the user. The following codeis a snippet of how we can traverse through the entire content of the XML document and display a proper response to the user." }, { "code": null, "e": 11886, "s": 11051, "text": "import groovy.xml.MarkupBuilder \nimport groovy.util.*\n\nclass Example {\n\n static void main(String[] args) { \n\t\n def parser = new XmlParser()\n def doc = parser.parse(\"D:\\\\Movies.xml\");\n\t\t\n doc.movie.each{\n bk->\n print(\"Movie Name:\")\n println \"${bk['@title']}\"\n\t\t\t\n print(\"Movie Type:\")\n println \"${bk.type[0].text()}\"\n\t\t\t\n print(\"Movie Format:\")\n println \"${bk.format[0].text()}\"\n\t\t\t\n print(\"Movie year:\")\n println \"${bk.year[0].text()}\"\n\t\t\t\n print(\"Movie rating:\")\n println \"${bk.rating[0].text()}\"\n\t\t\t\n print(\"Movie stars:\")\n println \"${bk.stars[0].text()}\"\n\t\t\t\n print(\"Movie description:\")\n println \"${bk.description[0].text()}\"\n println(\"*******************************\")\n }\n }\n} " }, { "code": null, "e": 11952, "s": 11886, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 12674, "s": 11952, "text": "Movie Name:Enemy Behind \nMovie Type:War, Thriller \nMovie Format:DVD \nMovie year:2003 \nMovie rating:PG \nMovie stars:10 \nMovie description:Talk about a US-Japan war \n******************************* \nMovie Name:Transformers \nMovie Type:Anime, Science Fiction \nMovie Format:DVD \nMovie year:1989 \nMovie rating:R \nMovie stars:8 \nMovie description:A schientific fiction \n******************************* \nMovie Name:Trigun \nMovie Type:Anime, Action\nMovie Format:DVD \nMovie year:1986 \nMovie rating:PG \nMovie stars:10 \nMovie description:Vash the Stam pede! \n******************************* \nMovie Name:Ishtar \nMovie Type:Comedy \nMovie Format:VHS \nMovie year:1987 \nMovie rating:PG \nMovie stars:2 \nMovie description:Viewable boredom\n" }, { "code": null, "e": 12725, "s": 12674, "text": "The important things to note about the above code." }, { "code": null, "e": 12824, "s": 12725, "text": "An object of the class XmlParser is being formed so that it can be used to parse the XML document." }, { "code": null, "e": 12923, "s": 12824, "text": "An object of the class XmlParser is being formed so that it can be used to parse the XML document." }, { "code": null, "e": 12973, "s": 12923, "text": "The parser is given the location of the XML file." }, { "code": null, "e": 13023, "s": 12973, "text": "The parser is given the location of the XML file." }, { "code": null, "e": 13142, "s": 13023, "text": "For each movie element, we are using a closure to browse through each child node and display the relevant information." }, { "code": null, "e": 13261, "s": 13142, "text": "For each movie element, we are using a closure to browse through each child node and display the relevant information." }, { "code": null, "e": 13379, "s": 13261, "text": "For the movie element itself, we are using the @ symbol to display the title attribute attached to the movie element." }, { "code": null, "e": 13412, "s": 13379, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 13430, "s": 13412, "text": " Krishna Sakinala" }, { "code": null, "e": 13465, "s": 13430, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13483, "s": 13465, "text": " Packt Publishing" }, { "code": null, "e": 13490, "s": 13483, "text": " Print" }, { "code": null, "e": 13501, "s": 13490, "text": " Add Notes" } ]
Best meeting point in 2D binary array - GeeksforGeeks
03 Sep, 2021 You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in a group. And the group of two or more people wants to meet and minimize the total travel distance. They can meet anywhere means that there might be a home or not. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x – p1.x| + |p2.y – p1.y|. Find the total distance that needs to be traveled to reach the best meeting point (Total distance traveled is minimum). Examples: Input : grid[][] = {{1, 0, 0, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}}; Output : 6 Best meeting point is (0, 2). Total distance traveled is 2 + 2 + 2 = 6 Input : grid[3][5] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; Output : 11 Steps :- 1) Store all horizontal and vertical positions of all group member. 2) Now sort it to find minimum middle position, which will be the best meeting point. 3) Find the distance of all members from best meeting point.For example in above diagram, horizontal positions are {0, 2, 0} and vertical positions are {0, 2, 4}. After sorting both, we get {0, 0, 2} and {0, 2, 4}. Middle point is (0, 2).Note : Even no. of 1’s have two middle points, then also it works. Two middle points means it have two best meeting points always. Both cases will give same distance. So we will consider only one best meeting point to avoid the more overhead, Because our aim is to find the distance only. C++ Java Python3 C# Javascript /* C++ program to find best meeting point in 2D array*/#include <bits/stdc++.h>using namespace std;#define ROW 3#define COL 5 int minTotalDistance(int grid[][COL]) { if (ROW == 0 || COL == 0) return 0; vector<int> vertical; vector<int> horizontal; // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.push_back(i); horizontal.push_back(j); } } } // Sort positions so we can find most // beneficial point sort(vertical.begin(),vertical.end()); sort(horizontal.begin(),horizontal.end()); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.size()/2; int x = vertical[size]; int y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i][j] == 1) distance += abs(x - i) + abs(y - j); return distance;} // Driver program to test above functionsint main() { int grid[ROW][COL] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0},{0, 1, 1, 0, 0}}; cout << minTotalDistance(grid); return 0;} /* Java program to find bestmeeting point in 2D array*/import java.util.*; class GFG{ static int ROW = 3;static int COL =5 ; static int minTotalDistance(int grid[][]){ if (ROW == 0 || COL == 0) return 0; Vector<Integer> vertical = new Vector<Integer>(); Vector<Integer> horizontal = new Vector<Integer>(); // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.add(i); horizontal.add(j); } } } // Sort positions so we can find most // beneficial point Collections.sort(vertical); Collections.sort(horizontal); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.size() / 2; int x = vertical.get(size); int y = horizontal.get(size); // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i][j] == 1) distance += Math.abs(x - i) + Math.abs(y - j); return distance;} // Driver codepublic static void main(String[] args){ int grid[][] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; System.out.println(minTotalDistance(grid));}} // This code is contributed by 29AjayKumar # Python program to find best meeting point in 2D arrayROW = 3COL = 5 def minTotalDistance(grid: list) -> int: if ROW == 0 or COL == 0: return 0 vertical = [] horizontal = [] # Find all members home's position for i in range(ROW): for j in range(COL): if grid[i][j] == 1: vertical.append(i) horizontal.append(j) # Sort positions so we can find most # beneficial point vertical.sort() horizontal.sort() # middle position will always beneficial # for all group members but it will be # sorted which we have already done size = len(vertical) // 2 x = vertical[size] y = horizontal[size] # Now find total distance from best meeting # point (x,y) using Manhattan Distance formula distance = 0 for i in range(ROW): for j in range(COL): if grid[i][j] == 1: distance += abs(x - i) + abs(y - j) return distance # Driver Codeif __name__ == "__main__": grid = [[1, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0]] print(minTotalDistance(grid)) # This code is contributed by# sanjeev2552 /* C# program to find bestmeeting point in 2D array*/using System;using System.Collections.Generic; class GFG{ static int ROW = 3;static int COL = 5 ; static int minTotalDistance(int [,]grid){ if (ROW == 0 || COL == 0) return 0; List<int> vertical = new List<int>(); List<int> horizontal = new List<int>(); // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i, j] == 1) { vertical.Add(i); horizontal.Add(j); } } } // Sort positions so we can find most // beneficial point vertical.Sort(); horizontal.Sort(); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.Count / 2; int x = vertical[size]; int y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i, j] == 1) distance += Math.Abs(x - i) + Math.Abs(y - j); return distance;} // Driver codepublic static void Main(String[] args){ int [,]grid = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; Console.WriteLine(minTotalDistance(grid));}} // This code is contributed by PrinciRaj1992 <script>/* Javascript program to find bestmeeting point in 2D array*/ let ROW = 3;let COL =5 ; function minTotalDistance(grid){ if (ROW == 0 || COL == 0) return 0; let vertical = []; let horizontal = []; // Find all members home's position for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.push(i); horizontal.push(j); } } } // Sort positions so we can find most // beneficial point (vertical).sort(function(a,b){return a-b;}); (horizontal).sort(function(a,b){return a-b;}); // middle position will always beneficial // for all group members but it will be // sorted which we have already done let size = vertical.length / 2; let x = vertical[size]; let y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula let distance = 0; for (let i = 0; i < ROW; i++) for (let j = 0; j < COL; j++) if (grid[i][j] == 1) distance += Math.abs(x - i) + Math.abs(y - j); return distance;} // Driver codelet grid = [[1, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0]];document.write(minTotalDistance(grid)); // This code is contributed by rag2127</script> Output: 11 Time Complexity : O(M*N) Auxiliary Space : O(N) This article is contributed by Harshit 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. 29AjayKumar sanjeev2552 princiraj1992 rag2127 surindertarika1234 Matrix Misc Searching Misc Searching Misc Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flood fill Algorithm - how to implement fill() in paint? Breadth First Traversal ( BFS ) on a 2D array Program to find the Sum of each Row and each Column of a Matrix Python program to add two Matrices Efficiently compute sums of diagonals of a matrix Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? fgets() and gets() in C language
[ { "code": null, "e": 24922, "s": 24894, "text": "\n03 Sep, 2021" }, { "code": null, "e": 25170, "s": 24922, "text": "You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in a group. And the group of two or more people wants to meet and minimize the total travel distance. They can meet anywhere means that there might be a home or not. " }, { "code": null, "e": 25279, "s": 25170, "text": "The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x – p1.x| + |p2.y – p1.y|." }, { "code": null, "e": 25399, "s": 25279, "text": "Find the total distance that needs to be traveled to reach the best meeting point (Total distance traveled is minimum)." }, { "code": null, "e": 25413, "s": 25401, "text": "Examples: " }, { "code": null, "e": 25736, "s": 25413, "text": "Input : grid[][] = {{1, 0, 0, 0, 1}, \n {0, 0, 0, 0, 0},\n {0, 0, 1, 0, 0}};\nOutput : 6\nBest meeting point is (0, 2).\nTotal distance traveled is 2 + 2 + 2 = 6\n\nInput : grid[3][5] = {{1, 0, 1, 0, 1},\n {0, 1, 0, 0, 0}, \n {0, 1, 1, 0, 0}};\nOutput : 11" }, { "code": null, "e": 26430, "s": 25738, "text": "Steps :- 1) Store all horizontal and vertical positions of all group member. 2) Now sort it to find minimum middle position, which will be the best meeting point. 3) Find the distance of all members from best meeting point.For example in above diagram, horizontal positions are {0, 2, 0} and vertical positions are {0, 2, 4}. After sorting both, we get {0, 0, 2} and {0, 2, 4}. Middle point is (0, 2).Note : Even no. of 1’s have two middle points, then also it works. Two middle points means it have two best meeting points always. Both cases will give same distance. So we will consider only one best meeting point to avoid the more overhead, Because our aim is to find the distance only. " }, { "code": null, "e": 26434, "s": 26430, "text": "C++" }, { "code": null, "e": 26439, "s": 26434, "text": "Java" }, { "code": null, "e": 26447, "s": 26439, "text": "Python3" }, { "code": null, "e": 26450, "s": 26447, "text": "C#" }, { "code": null, "e": 26461, "s": 26450, "text": "Javascript" }, { "code": "/* C++ program to find best meeting point in 2D array*/#include <bits/stdc++.h>using namespace std;#define ROW 3#define COL 5 int minTotalDistance(int grid[][COL]) { if (ROW == 0 || COL == 0) return 0; vector<int> vertical; vector<int> horizontal; // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.push_back(i); horizontal.push_back(j); } } } // Sort positions so we can find most // beneficial point sort(vertical.begin(),vertical.end()); sort(horizontal.begin(),horizontal.end()); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.size()/2; int x = vertical[size]; int y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i][j] == 1) distance += abs(x - i) + abs(y - j); return distance;} // Driver program to test above functionsint main() { int grid[ROW][COL] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0},{0, 1, 1, 0, 0}}; cout << minTotalDistance(grid); return 0;}", "e": 27851, "s": 26461, "text": null }, { "code": "/* Java program to find bestmeeting point in 2D array*/import java.util.*; class GFG{ static int ROW = 3;static int COL =5 ; static int minTotalDistance(int grid[][]){ if (ROW == 0 || COL == 0) return 0; Vector<Integer> vertical = new Vector<Integer>(); Vector<Integer> horizontal = new Vector<Integer>(); // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.add(i); horizontal.add(j); } } } // Sort positions so we can find most // beneficial point Collections.sort(vertical); Collections.sort(horizontal); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.size() / 2; int x = vertical.get(size); int y = horizontal.get(size); // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i][j] == 1) distance += Math.abs(x - i) + Math.abs(y - j); return distance;} // Driver codepublic static void main(String[] args){ int grid[][] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; System.out.println(minTotalDistance(grid));}} // This code is contributed by 29AjayKumar", "e": 29398, "s": 27851, "text": null }, { "code": "# Python program to find best meeting point in 2D arrayROW = 3COL = 5 def minTotalDistance(grid: list) -> int: if ROW == 0 or COL == 0: return 0 vertical = [] horizontal = [] # Find all members home's position for i in range(ROW): for j in range(COL): if grid[i][j] == 1: vertical.append(i) horizontal.append(j) # Sort positions so we can find most # beneficial point vertical.sort() horizontal.sort() # middle position will always beneficial # for all group members but it will be # sorted which we have already done size = len(vertical) // 2 x = vertical[size] y = horizontal[size] # Now find total distance from best meeting # point (x,y) using Manhattan Distance formula distance = 0 for i in range(ROW): for j in range(COL): if grid[i][j] == 1: distance += abs(x - i) + abs(y - j) return distance # Driver Codeif __name__ == \"__main__\": grid = [[1, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0]] print(minTotalDistance(grid)) # This code is contributed by# sanjeev2552", "e": 30555, "s": 29398, "text": null }, { "code": "/* C# program to find bestmeeting point in 2D array*/using System;using System.Collections.Generic; class GFG{ static int ROW = 3;static int COL = 5 ; static int minTotalDistance(int [,]grid){ if (ROW == 0 || COL == 0) return 0; List<int> vertical = new List<int>(); List<int> horizontal = new List<int>(); // Find all members home's position for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i, j] == 1) { vertical.Add(i); horizontal.Add(j); } } } // Sort positions so we can find most // beneficial point vertical.Sort(); horizontal.Sort(); // middle position will always beneficial // for all group members but it will be // sorted which we have already done int size = vertical.Count / 2; int x = vertical[size]; int y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula int distance = 0; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (grid[i, j] == 1) distance += Math.Abs(x - i) + Math.Abs(y - j); return distance;} // Driver codepublic static void Main(String[] args){ int [,]grid = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; Console.WriteLine(minTotalDistance(grid));}} // This code is contributed by PrinciRaj1992", "e": 32072, "s": 30555, "text": null }, { "code": "<script>/* Javascript program to find bestmeeting point in 2D array*/ let ROW = 3;let COL =5 ; function minTotalDistance(grid){ if (ROW == 0 || COL == 0) return 0; let vertical = []; let horizontal = []; // Find all members home's position for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { if (grid[i][j] == 1) { vertical.push(i); horizontal.push(j); } } } // Sort positions so we can find most // beneficial point (vertical).sort(function(a,b){return a-b;}); (horizontal).sort(function(a,b){return a-b;}); // middle position will always beneficial // for all group members but it will be // sorted which we have already done let size = vertical.length / 2; let x = vertical[size]; let y = horizontal[size]; // Now find total distance from best meeting // point (x,y) using Manhattan Distance formula let distance = 0; for (let i = 0; i < ROW; i++) for (let j = 0; j < COL; j++) if (grid[i][j] == 1) distance += Math.abs(x - i) + Math.abs(y - j); return distance;} // Driver codelet grid = [[1, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0]];document.write(minTotalDistance(grid)); // This code is contributed by rag2127</script>", "e": 33502, "s": 32072, "text": null }, { "code": null, "e": 33512, "s": 33502, "text": "Output: " }, { "code": null, "e": 33515, "s": 33512, "text": "11" }, { "code": null, "e": 33987, "s": 33515, "text": "Time Complexity : O(M*N) Auxiliary Space : O(N) This article is contributed by Harshit 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": 33999, "s": 33987, "text": "29AjayKumar" }, { "code": null, "e": 34011, "s": 33999, "text": "sanjeev2552" }, { "code": null, "e": 34025, "s": 34011, "text": "princiraj1992" }, { "code": null, "e": 34033, "s": 34025, "text": "rag2127" }, { "code": null, "e": 34052, "s": 34033, "text": "surindertarika1234" }, { "code": null, "e": 34059, "s": 34052, "text": "Matrix" }, { "code": null, "e": 34064, "s": 34059, "text": "Misc" }, { "code": null, "e": 34074, "s": 34064, "text": "Searching" }, { "code": null, "e": 34079, "s": 34074, "text": "Misc" }, { "code": null, "e": 34089, "s": 34079, "text": "Searching" }, { "code": null, "e": 34094, "s": 34089, "text": "Misc" }, { "code": null, "e": 34101, "s": 34094, "text": "Matrix" }, { "code": null, "e": 34199, "s": 34101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34256, "s": 34199, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 34302, "s": 34256, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 34366, "s": 34302, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 34401, "s": 34366, "text": "Python program to add two Matrices" }, { "code": null, "e": 34451, "s": 34401, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 34492, "s": 34451, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 34546, "s": 34492, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 34607, "s": 34546, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 34641, "s": 34607, "text": "How to write Regular Expressions?" } ]
Data analysis using Pandas - GeeksforGeeks
15 Oct, 2020 Pandas is the most popular python library that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python. We can analyze data in pandas with: SeriesDataFrames SeriesDataFrames Series DataFrames Series is one dimensional(1-D) array defined in pandas that can be used to store any data type. Code #1: Creating Series # Program to create series # Import Panda Libraryimport pandas as pd # Create series with Data, and Indexa = pd.Series(Data, index = Index) Here, Data can be: A Scalar value which can be integerValue, stringA Python Dictionary which can be Key, Value pairA Ndarray A Scalar value which can be integerValue, string A Python Dictionary which can be Key, Value pair A Ndarray Note: Index by default is from 0, 1, 2, ...(n-1) where n is length of data. Code #2: When Data contains scalar values # Program to Create series with scalar values # Numeric dataData =[1, 3, 4, 5, 6, 2, 9] # Creating series with default index valuess = pd.Series(Data) # predefined index valuesIndex =['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Creating series with predefined index valuessi = pd.Series(Data, Index) Output: Scalar Data with default Index Scalar Data with Index Scalar Data with default Index Scalar Data with Index Code #3: When Data contains Dictionary # Program to Create Dictionary seriesdictionary ={'a':1, 'b':2, 'c':3, 'd':4, 'e':5} # Creating series of Dictionary typesd = pd.Series(dictionary) Output: Dictionary type data Dictionary type data Code #4:When Data contains Ndarray # Program to Create ndarray series # Defining 2darrayData =[[2, 3, 4], [5, 6, 7]] # Creating series of 2darraysnd = pd.Series(Data) Output: Data as Ndarray Data as Ndarray DataFrames is two-dimensional(2-D) data structure defined in pandas which consists of rows and columns. Code #1: Creation of DataFrame # Program to Create DataFrame # Import Libraryimport pandas as pd # Create DataFrame with Dataa = pd.DataFrame(Data) Here, Data can be: One or more dictionariesOne or more Series2D-numpy Ndarray One or more dictionaries One or more Series 2D-numpy Ndarray Code #2: When Data is Dictionaries # Program to Create Data Frame with two dictionaries # Define Dictionary 1dict1 ={'a':1, 'b':2, 'c':3, 'd':4} # Define Dictionary 2 dict2 ={'a':5, 'b':6, 'c':7, 'd':8, 'e':9} # Define Data with dict1 and dict2Data = {'first':dict1, 'second':dict2} # Create DataFrame df = pd.DataFrame(Data) Output: DataFrame with two dictionaries DataFrame with two dictionaries Code #3: When Data is Series # Program to create Dataframe of three series import pandas as pd # Define series 1s1 = pd.Series([1, 3, 4, 5, 6, 2, 9]) # Define series 2 s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3]) # Define series 3s3 = pd.Series(['a', 'b', 'c', 'd', 'e']) # Define DataData ={'first':s1, 'second':s2, 'third':s3} # Create DataFramedfseries = pd.DataFrame(Data) Output: DataFrame with three series DataFrame with three series Code #4: When Data is 2D-numpy ndarrayNote: One constraint has to be maintained while creating DataFrame of 2D arrays – Dimensions of 2D array must be same. # Program to create DataFrame from 2D array # Import Libraryimport pandas as pd # Define 2d array 1d1 =[[2, 3, 4], [5, 6, 7]] # Define 2d array 2d2 =[[2, 4, 8], [1, 3, 9]] # Define DataData ={'first': d1, 'second': d2} # Create DataFramedf2d = pd.DataFrame(Data) Output: DataFrame with 2d ndarray DataFrame with 2d ndarray python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24960, "s": 24932, "text": "\n15 Oct, 2020" }, { "code": null, "e": 25135, "s": 24960, "text": "Pandas is the most popular python library that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python." }, { "code": null, "e": 25189, "s": 25135, "text": "We can analyze data in pandas with:\n\nSeriesDataFrames" }, { "code": null, "e": 25206, "s": 25189, "text": "SeriesDataFrames" }, { "code": null, "e": 25213, "s": 25206, "text": "Series" }, { "code": null, "e": 25224, "s": 25213, "text": "DataFrames" }, { "code": null, "e": 25320, "s": 25224, "text": "Series is one dimensional(1-D) array defined in pandas that can be used to store any data type." }, { "code": null, "e": 25345, "s": 25320, "text": "Code #1: Creating Series" }, { "code": "# Program to create series # Import Panda Libraryimport pandas as pd # Create series with Data, and Indexa = pd.Series(Data, index = Index) ", "e": 25491, "s": 25345, "text": null }, { "code": null, "e": 25510, "s": 25491, "text": "Here, Data can be:" }, { "code": null, "e": 25616, "s": 25510, "text": "A Scalar value which can be integerValue, stringA Python Dictionary which can be Key, Value pairA Ndarray" }, { "code": null, "e": 25665, "s": 25616, "text": "A Scalar value which can be integerValue, string" }, { "code": null, "e": 25714, "s": 25665, "text": "A Python Dictionary which can be Key, Value pair" }, { "code": null, "e": 25724, "s": 25714, "text": "A Ndarray" }, { "code": null, "e": 25842, "s": 25724, "text": "Note: Index by default is from 0, 1, 2, ...(n-1) where n is length of data. Code #2: When Data contains scalar values" }, { "code": "# Program to Create series with scalar values # Numeric dataData =[1, 3, 4, 5, 6, 2, 9] # Creating series with default index valuess = pd.Series(Data) # predefined index valuesIndex =['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Creating series with predefined index valuessi = pd.Series(Data, Index) ", "e": 26148, "s": 25842, "text": null }, { "code": null, "e": 26156, "s": 26148, "text": "Output:" }, { "code": null, "e": 26211, "s": 26156, "text": "Scalar Data with default Index\nScalar Data with Index\n" }, { "code": null, "e": 26242, "s": 26211, "text": "Scalar Data with default Index" }, { "code": null, "e": 26265, "s": 26242, "text": "Scalar Data with Index" }, { "code": null, "e": 26305, "s": 26265, "text": " Code #3: When Data contains Dictionary" }, { "code": "# Program to Create Dictionary seriesdictionary ={'a':1, 'b':2, 'c':3, 'd':4, 'e':5} # Creating series of Dictionary typesd = pd.Series(dictionary) ", "e": 26456, "s": 26305, "text": null }, { "code": null, "e": 26464, "s": 26456, "text": "Output:" }, { "code": null, "e": 26486, "s": 26464, "text": "Dictionary type data\n" }, { "code": null, "e": 26507, "s": 26486, "text": "Dictionary type data" }, { "code": null, "e": 26544, "s": 26509, "text": "Code #4:When Data contains Ndarray" }, { "code": "# Program to Create ndarray series # Defining 2darrayData =[[2, 3, 4], [5, 6, 7]] # Creating series of 2darraysnd = pd.Series(Data) ", "e": 26684, "s": 26544, "text": null }, { "code": null, "e": 26692, "s": 26684, "text": "Output:" }, { "code": null, "e": 26709, "s": 26692, "text": "Data as Ndarray\n" }, { "code": null, "e": 26725, "s": 26709, "text": "Data as Ndarray" }, { "code": null, "e": 26831, "s": 26727, "text": "DataFrames is two-dimensional(2-D) data structure defined in pandas which consists of rows and columns." }, { "code": null, "e": 26862, "s": 26831, "text": "Code #1: Creation of DataFrame" }, { "code": "# Program to Create DataFrame # Import Libraryimport pandas as pd # Create DataFrame with Dataa = pd.DataFrame(Data) ", "e": 26986, "s": 26862, "text": null }, { "code": null, "e": 27005, "s": 26986, "text": "Here, Data can be:" }, { "code": null, "e": 27064, "s": 27005, "text": "One or more dictionariesOne or more Series2D-numpy Ndarray" }, { "code": null, "e": 27089, "s": 27064, "text": "One or more dictionaries" }, { "code": null, "e": 27108, "s": 27089, "text": "One or more Series" }, { "code": null, "e": 27125, "s": 27108, "text": "2D-numpy Ndarray" }, { "code": null, "e": 27161, "s": 27125, "text": " Code #2: When Data is Dictionaries" }, { "code": "# Program to Create Data Frame with two dictionaries # Define Dictionary 1dict1 ={'a':1, 'b':2, 'c':3, 'd':4} # Define Dictionary 2 dict2 ={'a':5, 'b':6, 'c':7, 'd':8, 'e':9} # Define Data with dict1 and dict2Data = {'first':dict1, 'second':dict2} # Create DataFrame df = pd.DataFrame(Data) ", "e": 27467, "s": 27161, "text": null }, { "code": null, "e": 27475, "s": 27467, "text": "Output:" }, { "code": null, "e": 27508, "s": 27475, "text": "DataFrame with two dictionaries\n" }, { "code": null, "e": 27540, "s": 27508, "text": "DataFrame with two dictionaries" }, { "code": null, "e": 27570, "s": 27540, "text": " Code #3: When Data is Series" }, { "code": "# Program to create Dataframe of three series import pandas as pd # Define series 1s1 = pd.Series([1, 3, 4, 5, 6, 2, 9]) # Define series 2 s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3]) # Define series 3s3 = pd.Series(['a', 'b', 'c', 'd', 'e']) # Define DataData ={'first':s1, 'second':s2, 'third':s3} # Create DataFramedfseries = pd.DataFrame(Data) ", "e": 27955, "s": 27570, "text": null }, { "code": null, "e": 27963, "s": 27955, "text": "Output:" }, { "code": null, "e": 27992, "s": 27963, "text": "DataFrame with three series\n" }, { "code": null, "e": 28020, "s": 27992, "text": "DataFrame with three series" }, { "code": null, "e": 28178, "s": 28020, "text": " Code #4: When Data is 2D-numpy ndarrayNote: One constraint has to be maintained while creating DataFrame of 2D arrays – Dimensions of 2D array must be same." }, { "code": "# Program to create DataFrame from 2D array # Import Libraryimport pandas as pd # Define 2d array 1d1 =[[2, 3, 4], [5, 6, 7]] # Define 2d array 2d2 =[[2, 4, 8], [1, 3, 9]] # Define DataData ={'first': d1, 'second': d2} # Create DataFramedf2d = pd.DataFrame(Data) ", "e": 28455, "s": 28178, "text": null }, { "code": null, "e": 28463, "s": 28455, "text": "Output:" }, { "code": null, "e": 28490, "s": 28463, "text": "DataFrame with 2d ndarray\n" }, { "code": null, "e": 28516, "s": 28490, "text": "DataFrame with 2d ndarray" }, { "code": null, "e": 28531, "s": 28516, "text": "python-modules" }, { "code": null, "e": 28538, "s": 28531, "text": "Python" }, { "code": null, "e": 28636, "s": 28538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28645, "s": 28636, "text": "Comments" }, { "code": null, "e": 28658, "s": 28645, "text": "Old Comments" }, { "code": null, "e": 28676, "s": 28658, "text": "Python Dictionary" }, { "code": null, "e": 28711, "s": 28676, "text": "Read a file line by line in Python" }, { "code": null, "e": 28743, "s": 28711, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28765, "s": 28743, "text": "Enumerate() in Python" }, { "code": null, "e": 28795, "s": 28765, "text": "Iterate over a list in Python" }, { "code": null, "e": 28837, "s": 28795, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28863, "s": 28837, "text": "Python String | replace()" }, { "code": null, "e": 28906, "s": 28863, "text": "Python program to convert a list to string" }, { "code": null, "e": 28943, "s": 28906, "text": "Create a Pandas DataFrame from Lists" } ]
Adding an element in an array using Javascript
Adding an element to an array can be done using different functions for different positions. This can be accomplished using the push method. For example, let veggies = ["Onion", "Raddish"]; veggies.push("Cabbage"); console.log(veggies); This will give the output − ["Onion", "Raddish", "Cabbage"] You can also use this to push multiple items at the same time as it supports a variable number of arguments. For example, let veggies = ["Onion", "Raddish"]; veggies.push("Cabbage", "Carrot", "Broccoli"); console.log(veggies); This will give the output − ["Onion", "Raddish", "Cabbage", "Carrot", "Broccoli"] This can be accomplished using the unshift method. For example, let veggies = ["Onion", "Raddish"]; veggies.unshift("Cabbage"); console.log(veggies); This will give the output − ["Cabbage", "Onion", "Raddish"] You can also use this to unshift multiple items at the same time as it supports a variable number of arguments. For example, let veggies = ["Onion", "Raddish"]; veggies.unshift("Cabbage", "Carrot", "Broccoli"); console.log(veggies); This will give the output − ["Cabbage", "Carrot", "Broccoli", "Onion", "Raddish"] Sometimes you need to add an element to a given position in an array. JavaScript doesn't support it out of the box. So we need to create a function to be able to do that. We can add it to the Array prototype so that we can use it directly on the object. Array.prototype.insert = function(data, position) { if (position >= this.length) { this.push(data) // Put at the end if position is more than total length of array } else if (position <= 0) { this.unshift(data) // Put at the start if position is less than or equal to 0 } else { // Shift all elements to right for (let i = this.length; i >= position; i--) { this[i] = this[i - 1]; } this[position] = data; } } let arr = [1, 2, 3, 4]; arr.insert(-1, 2); console.log(arr); This will give the output − [1, 2, -1, 3, 4] Now the insert method is available on every array object you create. You can also use the splice method to insert elements at given positions. For example, var months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); console.log(months); This will give the output: ['Jan', 'Feb', 'March', 'April', 'June'] The first argument of the method is the index we want to remove elements from or insert elements into. The second argument is the number of elements we want to remove. And the third argument onwards are the values we would like to insert into the array.
[ { "code": null, "e": 1155, "s": 1062, "text": "Adding an element to an array can be done using different functions for different positions." }, { "code": null, "e": 1216, "s": 1155, "text": "This can be accomplished using the push method. For example," }, { "code": null, "e": 1299, "s": 1216, "text": "let veggies = [\"Onion\", \"Raddish\"];\nveggies.push(\"Cabbage\");\nconsole.log(veggies);" }, { "code": null, "e": 1327, "s": 1299, "text": "This will give the output −" }, { "code": null, "e": 1359, "s": 1327, "text": "[\"Onion\", \"Raddish\", \"Cabbage\"]" }, { "code": null, "e": 1457, "s": 1359, "text": "You can also use this to push multiple items at the same time as it supports a variable number of" }, { "code": null, "e": 1481, "s": 1457, "text": "arguments. For example," }, { "code": null, "e": 1586, "s": 1481, "text": "let veggies = [\"Onion\", \"Raddish\"];\nveggies.push(\"Cabbage\", \"Carrot\", \"Broccoli\");\nconsole.log(veggies);" }, { "code": null, "e": 1614, "s": 1586, "text": "This will give the output −" }, { "code": null, "e": 1668, "s": 1614, "text": "[\"Onion\", \"Raddish\", \"Cabbage\", \"Carrot\", \"Broccoli\"]" }, { "code": null, "e": 1732, "s": 1668, "text": "This can be accomplished using the unshift method. For example," }, { "code": null, "e": 1818, "s": 1732, "text": "let veggies = [\"Onion\", \"Raddish\"];\nveggies.unshift(\"Cabbage\");\nconsole.log(veggies);" }, { "code": null, "e": 1846, "s": 1818, "text": "This will give the output −" }, { "code": null, "e": 1878, "s": 1846, "text": "[\"Cabbage\", \"Onion\", \"Raddish\"]" }, { "code": null, "e": 1979, "s": 1878, "text": "You can also use this to unshift multiple items at the same time as it supports a variable number of" }, { "code": null, "e": 2003, "s": 1979, "text": "arguments. For example," }, { "code": null, "e": 2111, "s": 2003, "text": "let veggies = [\"Onion\", \"Raddish\"];\nveggies.unshift(\"Cabbage\", \"Carrot\", \"Broccoli\");\nconsole.log(veggies);" }, { "code": null, "e": 2139, "s": 2111, "text": "This will give the output −" }, { "code": null, "e": 2193, "s": 2139, "text": "[\"Cabbage\", \"Carrot\", \"Broccoli\", \"Onion\", \"Raddish\"]" }, { "code": null, "e": 2447, "s": 2193, "text": "Sometimes you need to add an element to a given position in an array. JavaScript doesn't support it out of the box. So we need to create a function to be able to do that. We can add it to the Array prototype so that we can use it directly on the object." }, { "code": null, "e": 2988, "s": 2447, "text": "Array.prototype.insert = function(data, position) {\n if (position >= this.length) {\n this.push(data)\n // Put at the end if position is more than total length of array\n } else if (position <= 0) {\n this.unshift(data)\n // Put at the start if position is less than or equal to 0\n } else {\n // Shift all elements to right\n for (let i = this.length; i >= position; i--) {\n this[i] = this[i - 1];\n }\n this[position] = data;\n }\n}\n\nlet arr = [1, 2, 3, 4];\narr.insert(-1, 2);\nconsole.log(arr);" }, { "code": null, "e": 3016, "s": 2988, "text": "This will give the output −" }, { "code": null, "e": 3033, "s": 3016, "text": "[1, 2, -1, 3, 4]" }, { "code": null, "e": 3102, "s": 3033, "text": "Now the insert method is available on every array object you create." }, { "code": null, "e": 3189, "s": 3102, "text": "You can also use the splice method to insert elements at given positions. For example," }, { "code": null, "e": 3286, "s": 3189, "text": "var months = ['Jan', 'March', 'April', 'June'];\nmonths.splice(1, 0, 'Feb');\nconsole.log(months);" }, { "code": null, "e": 3313, "s": 3286, "text": "This will give the output:" }, { "code": null, "e": 3354, "s": 3313, "text": "['Jan', 'Feb', 'March', 'April', 'June']" }, { "code": null, "e": 3608, "s": 3354, "text": "The first argument of the method is the index we want to remove elements from or insert elements into. The second argument is the number of elements we want to remove. And the third argument onwards are the values we would like to insert into the array." } ]
What is the usage of zerofill in a MySQL field?
Zerofill pads the displayed value of the field with zeros up to the display width specified in the column definition. For example, if column is set int(8), therefore the width is 8. If the number is let’s say 4376, then zero will be padded on the left for total width i.e. 8 − 00004376 Let us first create a table − mysql> create table DemoTable -> ( -> Number int(8) zerofill -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(1234); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable values(678965); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----------+ | Number | +----------+ | 00000010 | | 00001234 | | 00000001 | | 00678965 | +----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1339, "s": 1062, "text": "Zerofill pads the displayed value of the field with zeros up to the display width specified in the column definition. For example, if column is set int(8), therefore the width is 8. If the number is let’s say 4376, then zero will be padded on the left for total width i.e. 8 −" }, { "code": null, "e": 1348, "s": 1339, "text": "00004376" }, { "code": null, "e": 1378, "s": 1348, "text": "Let us first create a table −" }, { "code": null, "e": 1482, "s": 1378, "text": "mysql> create table DemoTable\n-> (\n-> Number int(8) zerofill\n-> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1538, "s": 1482, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1854, "s": 1538, "text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable values(1234);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values(1);\nQuery OK, 1 row affected (0.47 sec)\n\nmysql> insert into DemoTable values(678965);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1914, "s": 1854, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1945, "s": 1914, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1986, "s": 1945, "text": "This will produce the following output −" }, { "code": null, "e": 2115, "s": 1986, "text": "+----------+\n| Number |\n+----------+\n| 00000010 |\n| 00001234 |\n| 00000001 |\n| 00678965 |\n+----------+\n4 rows in set (0.00 sec)" } ]
Charset forName() method in Java with Examples - GeeksforGeeks
29 Mar, 2019 The forName() method is a built-in method of the java.nio.charset returns a charset object for the named charset. In this function we pass a canonical name or an alias and its respective charset name is returned. Syntax: public static Charset forName?(String charsetName) Parameters: The function accepts a single mandatory parameter charsetName which specifies the canonical name or the alias name whose object name is to be returned. Return Value: The function returns a charset object for the named charset. Errors and Exceptions: The function throws three exceptions as shown below: IllegalCharsetNameException: It is thrown if the given charset name is illegal IllegalArgumentException : It is thrown if the given charsetName is null UnsupportedCharsetException : It is thrown if no support for the named charset is available in this instance of the Java virtual machine Below is the implementation of the above function: Program 1: // Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Gets the charset Charset first = Charset.forName("ISO-2022-CN"); // Prints the object System.out.println("The name for ISO-2022-CN is " + first); }} The name for ISO-2022-CN is ISO-2022-CN Program 2: // Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Gets the charset Charset first = Charset.forName("UTF16"); // Prints the object System.out.println("The name for UTF16 is " + first); }} The name for UTF16 is UTF-16 Program 3 // Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { try { // Gets the charset Charset first = Charset.forName(""); // Prints the object System.out.println("The name for null is " + first); } catch (Exception e) { // Prints the exception System.out.println("The exception is: " + e); } }} The exception is: java.nio.charset.IllegalCharsetNameException: Program 4 // Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { try { // Gets the charset Charset first = Charset.forName("gopal"); // Prints the object System.out.println("The name for gopal is " + first); } catch (Exception e) { // Prints the exception System.out.println("The exception is: " + e); } }} The exception is: java.nio.charset.UnsupportedCharsetException: gopal Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/Charset.html#forName(java.lang.String) Java-Charset Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25471, "s": 25443, "text": "\n29 Mar, 2019" }, { "code": null, "e": 25684, "s": 25471, "text": "The forName() method is a built-in method of the java.nio.charset returns a charset object for the named charset. In this function we pass a canonical name or an alias and its respective charset name is returned." }, { "code": null, "e": 25692, "s": 25684, "text": "Syntax:" }, { "code": null, "e": 25743, "s": 25692, "text": "public static Charset forName?(String charsetName)" }, { "code": null, "e": 25907, "s": 25743, "text": "Parameters: The function accepts a single mandatory parameter charsetName which specifies the canonical name or the alias name whose object name is to be returned." }, { "code": null, "e": 25982, "s": 25907, "text": "Return Value: The function returns a charset object for the named charset." }, { "code": null, "e": 26058, "s": 25982, "text": "Errors and Exceptions: The function throws three exceptions as shown below:" }, { "code": null, "e": 26137, "s": 26058, "text": "IllegalCharsetNameException: It is thrown if the given charset name is illegal" }, { "code": null, "e": 26210, "s": 26137, "text": "IllegalArgumentException : It is thrown if the given charsetName is null" }, { "code": null, "e": 26347, "s": 26210, "text": "UnsupportedCharsetException : It is thrown if no support for the named charset is available in this instance of the Java virtual machine" }, { "code": null, "e": 26398, "s": 26347, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 26409, "s": 26398, "text": "Program 1:" }, { "code": "// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Gets the charset Charset first = Charset.forName(\"ISO-2022-CN\"); // Prints the object System.out.println(\"The name for ISO-2022-CN is \" + first); }}", "e": 26796, "s": 26409, "text": null }, { "code": null, "e": 26837, "s": 26796, "text": "The name for ISO-2022-CN is ISO-2022-CN\n" }, { "code": null, "e": 26848, "s": 26837, "text": "Program 2:" }, { "code": "// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Gets the charset Charset first = Charset.forName(\"UTF16\"); // Prints the object System.out.println(\"The name for UTF16 is \" + first); }}", "e": 27223, "s": 26848, "text": null }, { "code": null, "e": 27253, "s": 27223, "text": "The name for UTF16 is UTF-16\n" }, { "code": null, "e": 27263, "s": 27253, "text": "Program 3" }, { "code": "// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { try { // Gets the charset Charset first = Charset.forName(\"\"); // Prints the object System.out.println(\"The name for null is \" + first); } catch (Exception e) { // Prints the exception System.out.println(\"The exception is: \" + e); } }}", "e": 27804, "s": 27263, "text": null }, { "code": null, "e": 27869, "s": 27804, "text": "The exception is: java.nio.charset.IllegalCharsetNameException:\n" }, { "code": null, "e": 27879, "s": 27869, "text": "Program 4" }, { "code": "// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { try { // Gets the charset Charset first = Charset.forName(\"gopal\"); // Prints the object System.out.println(\"The name for gopal is \" + first); } catch (Exception e) { // Prints the exception System.out.println(\"The exception is: \" + e); } }}", "e": 28426, "s": 27879, "text": null }, { "code": null, "e": 28497, "s": 28426, "text": "The exception is: java.nio.charset.UnsupportedCharsetException: gopal\n" }, { "code": null, "e": 28607, "s": 28497, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/Charset.html#forName(java.lang.String)" }, { "code": null, "e": 28620, "s": 28607, "text": "Java-Charset" }, { "code": null, "e": 28635, "s": 28620, "text": "Java-Functions" }, { "code": null, "e": 28652, "s": 28635, "text": "Java-NIO package" }, { "code": null, "e": 28657, "s": 28652, "text": "Java" }, { "code": null, "e": 28662, "s": 28657, "text": "Java" }, { "code": null, "e": 28760, "s": 28662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28811, "s": 28760, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28841, "s": 28811, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28860, "s": 28841, "text": "Interfaces in Java" }, { "code": null, "e": 28891, "s": 28860, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28923, "s": 28891, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28941, "s": 28923, "text": "ArrayList in Java" }, { "code": null, "e": 28961, "s": 28941, "text": "Stack Class in Java" }, { "code": null, "e": 28985, "s": 28961, "text": "Singleton Class in Java" }, { "code": null, "e": 29017, "s": 28985, "text": "Multidimensional Arrays in Java" } ]
How to automate gmail login process using selenium webdriver in java?
We can automate the Gmail login process using Selenium webdriver in Java. To perform this task, first we have to launch the Gmail login page and locate the email, password and other elements with the findElement method and then perform actions on them. Let us have the look at the Gmail login page − import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; public class GmailLogin{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://accounts.google.com/signin"); //identify email WebElement l = driver .findElement(By.name("identifier")); l.sendKeys("[email protected]"); WebElement b = driver .findElement(By.className("VfPpkd-LgbsSe")); b.click(); //identify password WebElement p = driver .findElement(By.name("password")); p.sendKeys("123456"); b.click(); //close browser driver.close(); } }
[ { "code": null, "e": 1315, "s": 1062, "text": "We can automate the Gmail login process using Selenium webdriver in Java. To perform this task, first we have to launch the Gmail login page and locate the email, password and other elements with the findElement method and then perform actions on them." }, { "code": null, "e": 1362, "s": 1315, "text": "Let us have the look at the Gmail login page −" }, { "code": null, "e": 2368, "s": 1362, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.By;\npublic class GmailLogin{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://accounts.google.com/signin\");\n //identify email\n WebElement l = driver\n .findElement(By.name(\"identifier\"));\n l.sendKeys(\"[email protected]\");\n WebElement b = driver\n .findElement(By.className(\"VfPpkd-LgbsSe\"));\n b.click();\n //identify password\n WebElement p = driver\n .findElement(By.name(\"password\"));\n p.sendKeys(\"123456\");\n b.click();\n //close browser\n driver.close();\n }\n}" } ]
CRUD Operation in MySQL Using PHP, Volley Android - Insert Data - GeeksforGeeks
27 Dec, 2021 It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications. MySQL provides a set of some basic but most essential operations that will help you to easily interact with the MySQL database and these operations are known as CRUD operations. In the previous article, we have seen creating a new SQL database in the PhpMydmin service. In this article, we will perform the Insert data operation. Before performing this operation first of all we have to create a new PHP script for adding new data to that database in our SQL Database. Prerequisite: You should be having Postman installed in your system to test this PHP script. We will be building a simple PHP script in which we will be used to add data to our SQL table which we have created in our previous article. Using this script we will be adding data to our SQL table. Step 1: Start your XAMPP server which we have seen starting in the previous article In the previous article, we have seen starting our XAMPP server and we also have created our database. In this article, we will be creating a script for adding data to our database. Step 2: Navigate to xampp folder Now we have to navigate to C drive in your pc and inside that check for the folder name as xampp. Inside that folder navigate to htdocs folder and create a new folder in that and name it as courseApp. Inside this folder, we will be storing all our PHP scripts. Now for writing your PHP script we can use any simple text editor. I am using VS code. After creating this folder we simply have to open this folder in VS code. Step 3: Creating a new PHP file After you open your folder in VS code, inside that folder we have to press a shortcut key as Ctrl+N our new file will be created. We have to save this file with the name addCourses.php and add the below code to it. Comments are added in the code to get to know in more detail. PHP <?php $servername = "localhost"; // for testing the user name is root.$username = "root"; // the password for testing is "blank"$password = ""; // below is the name for our// database which we have added.$dbname = "id16310745_gfgdatabase"; // Create connection$conn = new mysqli($servername, $username, $password, $dbname); // an array to display response $response = array(); // on below line we are checking if the body provided by user contains // this keys as course name,course description and course duration if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){ // if above three parameters are present then we are extravting values // from it and storing it in new variables. $courseName = $_POST['courseName']; $courseDuration = $_POST['courseDuration']; $courseDescription = $_POST['courseDescription']; // after that we are writing an sql query to // add this data to our database. // on below line make sure to add your table name // in previous article we have created our table name // as courseDb and add all column headers to it except our id. $stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`, `courseDescription`) VALUES (?,?,?)"); $stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription); // on below line we are checking if our sql query is executed successfully. if($stmt->execute() == TRUE){ // if the script is executed successfully we are // passing data to our response object // with a success message. $response['error'] = false; $response['message'] = "course created successfully!"; } else{ // if we get any error we are passing error to our object. $response['error'] = true; $response['message'] = "failed\n ".$conn->error; } } else{ // this msethod is called when user // donot enter sufficient parameters. $response['error'] = true; $response['message'] = "Insufficient parameters"; } // at last we are prinintg our response which we get. echo json_encode($response); ?> Step 4: Getting URL for our PHP script For getting the URL for our PHP script we simply have to type localhost in our browser and we have to append it with our folder name and file name. You will get to see the URL highlighted below: http://localhost/courseApp/addCourses.php Now we will be adding data in our SQL table with this URL in postman. Step 5: Testing our PHP Script in Postman For testing your PHP script select the POST method in postman as we will be posting data to our SQL table and inside the URL section add the above URL. After adding the URL. Now click on the Body tab which is shown in the below screenshot and inside that select x-www-form-urlencoded and after that add the parameters in the below section as shown in the screenshot. Make sure the key which you are entering must be the same as that we have used for naming our columns in our SQL table. After adding all the data. Now click on Send option to send data to our SQL table. After sending this request our data has been added to our SQL table. You can get to see the data added in the PhpMyAdmin console in the below screenshot. In the upper part, we have created a PHP script for adding data to our SQL table. Along with that we have also tested that script by adding data to it. In this part, we will integrate that in our Android App and add data to our SQL table from our Android app. We will be building a simple application in which we will be simply adding course details from a simple form in our SQL table which we have created. For performing this operation we will be using the Volley library which is used for JSON parsing in Android. Below is the video in which we will get to see what we are going to build in this article. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. implementation ‘com.android.volley:volley:1.1.1’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part. Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it. XML <!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Edit text for getting course Name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Name" android:importantForAutofill="no" android:inputType="text" /> <!--Edittext for getting course Duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Duration in min" android:importantForAutofill="no" android:inputType="time" /> <!--Edittext for getting course Description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Description" android:importantForAutofill="no" android:inputType="text" /> <!--Button for adding your course to Firebase--> <Button android:id="@+id/idBtnSubmitCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Submit Course Details" android:textAllCaps="false" /> </LinearLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button submitCourseBtn; // creating a strings for storing our values from edittext fields. private String courseName, courseDuration, courseDescription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edittext and buttons courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); submitCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError("Please enter Course Name"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course Description"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration"); } else { // calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription, courseDuration); } } }); } private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) { // url to post our data String url = "http://localhost/courseApp/addCourses.php"; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are calling a string // request method to post the data to our API // in this we are calling a post method. StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("TAG", "RESPONSE IS " + response); try { JSONObject jsonObject = new JSONObject(response); // on below line we are displaying a success toast message. Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } // and setting data to edit text as empty courseNameEdt.setText(""); courseDescriptionEdt.setText(""); courseDurationEdt.setText(""); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show(); } }) { @Override public String getBodyContentType() { // as we are passing data in the form of url encoded // so we are passing the content type below return "application/x-www-form-urlencoded; charset=UTF-8"; } @Override protected Map<String, String> getParams() { // below line we are creating a map for storing // our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our // key and value pair to our parameters. params.put("courseName", courseName); params.put("courseDuration", courseDuration); params.put("courseDescription", courseDescription); // at last we are returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }} Now run your app and see the output of the code. Output: You can get to see the data that has been added to your SQL table in the below screenshot. kapoorsagar226 as5853535 Android Java PHP SQL Java Android SQL PHP 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? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 26701, "s": 26673, "text": "\n27 Dec, 2021" }, { "code": null, "e": 27289, "s": 26701, "text": "It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications. MySQL provides a set of some basic but most essential operations that will help you to easily interact with the MySQL database and these operations are known as CRUD operations." }, { "code": null, "e": 27581, "s": 27289, "text": "In the previous article, we have seen creating a new SQL database in the PhpMydmin service. In this article, we will perform the Insert data operation. Before performing this operation first of all we have to create a new PHP script for adding new data to that database in our SQL Database. " }, { "code": null, "e": 27675, "s": 27581, "text": "Prerequisite: You should be having Postman installed in your system to test this PHP script. " }, { "code": null, "e": 27876, "s": 27675, "text": "We will be building a simple PHP script in which we will be used to add data to our SQL table which we have created in our previous article. Using this script we will be adding data to our SQL table. " }, { "code": null, "e": 27961, "s": 27876, "text": "Step 1: Start your XAMPP server which we have seen starting in the previous article " }, { "code": null, "e": 28144, "s": 27961, "text": "In the previous article, we have seen starting our XAMPP server and we also have created our database. In this article, we will be creating a script for adding data to our database. " }, { "code": null, "e": 28178, "s": 28144, "text": "Step 2: Navigate to xampp folder " }, { "code": null, "e": 28601, "s": 28178, "text": "Now we have to navigate to C drive in your pc and inside that check for the folder name as xampp. Inside that folder navigate to htdocs folder and create a new folder in that and name it as courseApp. Inside this folder, we will be storing all our PHP scripts. Now for writing your PHP script we can use any simple text editor. I am using VS code. After creating this folder we simply have to open this folder in VS code. " }, { "code": null, "e": 28634, "s": 28601, "text": "Step 3: Creating a new PHP file " }, { "code": null, "e": 28914, "s": 28634, "text": "After you open your folder in VS code, inside that folder we have to press a shortcut key as Ctrl+N our new file will be created. We have to save this file with the name addCourses.php and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 28918, "s": 28914, "text": "PHP" }, { "code": "<?php $servername = \"localhost\"; // for testing the user name is root.$username = \"root\"; // the password for testing is \"blank\"$password = \"\"; // below is the name for our// database which we have added.$dbname = \"id16310745_gfgdatabase\"; // Create connection$conn = new mysqli($servername, $username, $password, $dbname); // an array to display response $response = array(); // on below line we are checking if the body provided by user contains // this keys as course name,course description and course duration if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){ // if above three parameters are present then we are extravting values // from it and storing it in new variables. $courseName = $_POST['courseName']; $courseDuration = $_POST['courseDuration']; $courseDescription = $_POST['courseDescription']; // after that we are writing an sql query to // add this data to our database. // on below line make sure to add your table name // in previous article we have created our table name // as courseDb and add all column headers to it except our id. $stmt = $conn->prepare(\"INSERT INTO `courseDb`(`courseName`, `courseDuration`, `courseDescription`) VALUES (?,?,?)\"); $stmt->bind_param(\"sss\",$courseName,$courseDuration,$courseDescription); // on below line we are checking if our sql query is executed successfully. if($stmt->execute() == TRUE){ // if the script is executed successfully we are // passing data to our response object // with a success message. $response['error'] = false; $response['message'] = \"course created successfully!\"; } else{ // if we get any error we are passing error to our object. $response['error'] = true; $response['message'] = \"failed\\n \".$conn->error; } } else{ // this msethod is called when user // donot enter sufficient parameters. $response['error'] = true; $response['message'] = \"Insufficient parameters\"; } // at last we are prinintg our response which we get. echo json_encode($response); ?>", "e": 31035, "s": 28918, "text": null }, { "code": null, "e": 31076, "s": 31035, "text": " Step 4: Getting URL for our PHP script " }, { "code": null, "e": 31273, "s": 31076, "text": "For getting the URL for our PHP script we simply have to type localhost in our browser and we have to append it with our folder name and file name. You will get to see the URL highlighted below: " }, { "code": null, "e": 31315, "s": 31273, "text": "http://localhost/courseApp/addCourses.php" }, { "code": null, "e": 31387, "s": 31315, "text": "Now we will be adding data in our SQL table with this URL in postman. " }, { "code": null, "e": 31430, "s": 31387, "text": "Step 5: Testing our PHP Script in Postman " }, { "code": null, "e": 32002, "s": 31430, "text": "For testing your PHP script select the POST method in postman as we will be posting data to our SQL table and inside the URL section add the above URL. After adding the URL. Now click on the Body tab which is shown in the below screenshot and inside that select x-www-form-urlencoded and after that add the parameters in the below section as shown in the screenshot. Make sure the key which you are entering must be the same as that we have used for naming our columns in our SQL table. After adding all the data. Now click on Send option to send data to our SQL table. " }, { "code": null, "e": 32158, "s": 32002, "text": "After sending this request our data has been added to our SQL table. You can get to see the data added in the PhpMyAdmin console in the below screenshot. " }, { "code": null, "e": 32419, "s": 32158, "text": "In the upper part, we have created a PHP script for adding data to our SQL table. Along with that we have also tested that script by adding data to it. In this part, we will integrate that in our Android App and add data to our SQL table from our Android app. " }, { "code": null, "e": 32769, "s": 32419, "text": "We will be building a simple application in which we will be simply adding course details from a simple form in our SQL table which we have created. For performing this operation we will be using the Volley library which is used for JSON parsing in Android. Below is the video in which we will get to see what we are going to build in this article. " }, { "code": null, "e": 32798, "s": 32769, "text": "Step 1: Create a New Project" }, { "code": null, "e": 32961, "s": 32798, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 33020, "s": 32961, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 33248, "s": 33020, "text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 33297, "s": 33248, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 33398, "s": 33297, "text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. " }, { "code": null, "e": 33473, "s": 33398, "text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file" }, { "code": null, "e": 33548, "s": 33473, "text": "Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 33552, "s": 33548, "text": "XML" }, { "code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 33645, "s": 33552, "text": null }, { "code": null, "e": 33694, "s": 33645, "text": " Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 33838, "s": 33694, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 33842, "s": 33838, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Edit text for getting course Name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Name\" android:importantForAutofill=\"no\" android:inputType=\"text\" /> <!--Edittext for getting course Duration--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Duration in min\" android:importantForAutofill=\"no\" android:inputType=\"time\" /> <!--Edittext for getting course Description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Description\" android:importantForAutofill=\"no\" android:inputType=\"text\" /> <!--Button for adding your course to Firebase--> <Button android:id=\"@+id/idBtnSubmitCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Submit Course Details\" android:textAllCaps=\"false\" /> </LinearLayout>", "e": 35768, "s": 33842, "text": null }, { "code": null, "e": 35817, "s": 35768, "text": " Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 36008, "s": 35817, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 36013, "s": 36008, "text": "Java" }, { "code": "import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button submitCourseBtn; // creating a strings for storing our values from edittext fields. private String courseName, courseDuration, courseDescription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edittext and buttons courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); submitCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError(\"Please enter Course Name\"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError(\"Please enter Course Description\"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError(\"Please enter Course Duration\"); } else { // calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription, courseDuration); } } }); } private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) { // url to post our data String url = \"http://localhost/courseApp/addCourses.php\"; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are calling a string // request method to post the data to our API // in this we are calling a post method. StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { Log.e(\"TAG\", \"RESPONSE IS \" + response); try { JSONObject jsonObject = new JSONObject(response); // on below line we are displaying a success toast message. Toast.makeText(MainActivity.this, jsonObject.getString(\"message\"), Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } // and setting data to edit text as empty courseNameEdt.setText(\"\"); courseDescriptionEdt.setText(\"\"); courseDurationEdt.setText(\"\"); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(MainActivity.this, \"Fail to get response = \" + error, Toast.LENGTH_SHORT).show(); } }) { @Override public String getBodyContentType() { // as we are passing data in the form of url encoded // so we are passing the content type below return \"application/x-www-form-urlencoded; charset=UTF-8\"; } @Override protected Map<String, String> getParams() { // below line we are creating a map for storing // our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our // key and value pair to our parameters. params.put(\"courseName\", courseName); params.put(\"courseDuration\", courseDuration); params.put(\"courseDescription\", courseDescription); // at last we are returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }}", "e": 41323, "s": 36013, "text": null }, { "code": null, "e": 41374, "s": 41323, "text": " Now run your app and see the output of the code. " }, { "code": null, "e": 41384, "s": 41374, "text": "Output: " }, { "code": null, "e": 41477, "s": 41384, "text": "You can get to see the data that has been added to your SQL table in the below screenshot. " }, { "code": null, "e": 41494, "s": 41479, "text": "kapoorsagar226" }, { "code": null, "e": 41504, "s": 41494, "text": "as5853535" }, { "code": null, "e": 41512, "s": 41504, "text": "Android" }, { "code": null, "e": 41517, "s": 41512, "text": "Java" }, { "code": null, "e": 41521, "s": 41517, "text": "PHP" }, { "code": null, "e": 41525, "s": 41521, "text": "SQL" }, { "code": null, "e": 41530, "s": 41525, "text": "Java" }, { "code": null, "e": 41538, "s": 41530, "text": "Android" }, { "code": null, "e": 41542, "s": 41538, "text": "SQL" }, { "code": null, "e": 41546, "s": 41542, "text": "PHP" }, { "code": null, "e": 41644, "s": 41546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41682, "s": 41644, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 41721, "s": 41682, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 41771, "s": 41721, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 41797, "s": 41771, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 41848, "s": 41797, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 41863, "s": 41848, "text": "Arrays in Java" }, { "code": null, "e": 41907, "s": 41863, "text": "Split() String method in Java with examples" }, { "code": null, "e": 41929, "s": 41907, "text": "For-each loop in Java" }, { "code": null, "e": 41980, "s": 41929, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Does Java support default parameter values for a method?
Java does not support the concept of default parameter however, you can achieve this using Using method overloading if you define method with no arguments along with parametrized methods. Then you can call a method with zero arguments. In Java methods parameters accept arguments with three dots. These are known as variable arguments. Once you use variable arguments as a parameter method, while calling you can pass as many number of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments. Live Demo public class Sample { void demoMethod(String... args) { for (String arg : args) { System.out.println(arg); } } public static void main(String args[] ) { new Sample().demoMethod("ram", "rahim", "robert"); new Sample().demoMethod("krishna", "kasyap"); new Sample().demoMethod(); } } ram rahim robert krishna kasyap
[ { "code": null, "e": 1153, "s": 1062, "text": "Java does not support the concept of default parameter however, you can achieve this using" }, { "code": null, "e": 1298, "s": 1153, "text": "Using method overloading if you define method with no arguments along with parametrized methods. Then you can call a method with zero arguments." }, { "code": null, "e": 1621, "s": 1298, "text": "In Java methods parameters accept arguments with three dots. These are known as variable arguments. Once you use variable arguments as a parameter method, while calling you can pass as many number of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments." }, { "code": null, "e": 1631, "s": 1621, "text": "Live Demo" }, { "code": null, "e": 1963, "s": 1631, "text": "public class Sample {\n void demoMethod(String... args) {\n for (String arg : args) {\n System.out.println(arg);\n }\n }\n public static void main(String args[] ) {\n new Sample().demoMethod(\"ram\", \"rahim\", \"robert\");\n new Sample().demoMethod(\"krishna\", \"kasyap\");\n new Sample().demoMethod();\n }\n}" }, { "code": null, "e": 1995, "s": 1963, "text": "ram\nrahim\nrobert\nkrishna\nkasyap" } ]
Python string | hexdigits - GeeksforGeeks
16 Oct, 2018 In Python3, string.hexdigits is a pre-initialized string used as string constant. In Python, string.hexdigits will give the hexadecimal letters ‘0123456789abcdefABCDEF’. Syntax : string.hexdigits Parameters : Doesn’t take any parameter, since it’s not a function. Returns : Return all hexadecimal digit letters. Note : Make sure to import string library function inorder to use string.hexdigits Code #1 : # import string library function import string # Storing the value in variable result result = string.hexdigits # Printing the value print(result) Output : 0123456789abcdefABCDEF Code #2 : Given code checks if the string input has only hexadecimal digit letters # importing string library function import string # Function checks if input string # has only hexdigits or not def check(value): for letter in value: # If anything other than hexdigit # letter is present, then return # False, else return True if letter not in string.hexdigits: return False return True # Driver Code input1 = "0123456789abcdef"print(input1, "--> ", check(input1)) input2 = "abcdefABCDEF"print(input2, "--> ", check(input2)) input3 = "abcdefghGEEK"print(input3, "--> ", check(input3)) Output: 0123456789abcdef --> True abcdefABCDEF --> True abcdefghGEEK --> False Applications :The string constant hexdigits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size. # Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # string.hexdigits generate_pass = ''.join([random.choice(string.hexdigits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password) Output: e497FEe2bC python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26075, "s": 26047, "text": "\n16 Oct, 2018" }, { "code": null, "e": 26245, "s": 26075, "text": "In Python3, string.hexdigits is a pre-initialized string used as string constant. In Python, string.hexdigits will give the hexadecimal letters ‘0123456789abcdefABCDEF’." }, { "code": null, "e": 26271, "s": 26245, "text": "Syntax : string.hexdigits" }, { "code": null, "e": 26339, "s": 26271, "text": "Parameters : Doesn’t take any parameter, since it’s not a function." }, { "code": null, "e": 26387, "s": 26339, "text": "Returns : Return all hexadecimal digit letters." }, { "code": null, "e": 26470, "s": 26387, "text": "Note : Make sure to import string library function inorder to use string.hexdigits" }, { "code": null, "e": 26480, "s": 26470, "text": "Code #1 :" }, { "code": "# import string library function import string # Storing the value in variable result result = string.hexdigits # Printing the value print(result) ", "e": 26636, "s": 26480, "text": null }, { "code": null, "e": 26645, "s": 26636, "text": "Output :" }, { "code": null, "e": 26668, "s": 26645, "text": "0123456789abcdefABCDEF" }, { "code": null, "e": 26753, "s": 26670, "text": "Code #2 : Given code checks if the string input has only hexadecimal digit letters" }, { "code": "# importing string library function import string # Function checks if input string # has only hexdigits or not def check(value): for letter in value: # If anything other than hexdigit # letter is present, then return # False, else return True if letter not in string.hexdigits: return False return True # Driver Code input1 = \"0123456789abcdef\"print(input1, \"--> \", check(input1)) input2 = \"abcdefABCDEF\"print(input2, \"--> \", check(input2)) input3 = \"abcdefghGEEK\"print(input3, \"--> \", check(input3)) ", "e": 27340, "s": 26753, "text": null }, { "code": null, "e": 27348, "s": 27340, "text": "Output:" }, { "code": null, "e": 27422, "s": 27348, "text": "0123456789abcdef --> True\nabcdefABCDEF --> True\nabcdefghGEEK --> False" }, { "code": null, "e": 27607, "s": 27422, "text": "Applications :The string constant hexdigits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size." }, { "code": "# Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # string.hexdigits generate_pass = ''.join([random.choice(string.hexdigits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password) ", "e": 28042, "s": 27607, "text": null }, { "code": null, "e": 28050, "s": 28042, "text": "Output:" }, { "code": null, "e": 28061, "s": 28050, "text": "e497FEe2bC" }, { "code": null, "e": 28075, "s": 28061, "text": "python-string" }, { "code": null, "e": 28082, "s": 28075, "text": "Python" }, { "code": null, "e": 28180, "s": 28082, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28198, "s": 28180, "text": "Python Dictionary" }, { "code": null, "e": 28230, "s": 28198, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28252, "s": 28230, "text": "Enumerate() in Python" }, { "code": null, "e": 28294, "s": 28252, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28324, "s": 28294, "text": "Iterate over a list in Python" }, { "code": null, "e": 28353, "s": 28324, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28397, "s": 28353, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28434, "s": 28397, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28476, "s": 28434, "text": "Check if element exists in list in Python" } ]
Program to calculate distance between two points in 3 D - GeeksforGeeks
01 Apr, 2021 Given two coordinates (x1, y1, z1) and (x2, y2, z2) in 3 dimension. The task is to find the distance between them.Examples : Input: x1, y1, z1 = (2, -5, 7) x2, y2, z1 = (3, 4, 5) Output: 9.2736184955 Input: x1, y1, z1 = (0, 0, 0) x2, y2, z1 = (1, 1, 1) Output: 1.73205080757 Approach: The formula for distance between two points in 3 dimension i.e (x1, y1, z1) and (x2, y2, z2) has been derived from Pythagorean theorem which is:Distance = Below is the implementation of above formulae: C++ C Java Python C# PHP Javascript // C++ program to find// distance between// two points in 3 D.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // function to print distancevoid distance(float x1, float y1, float z1, float x2, float y2, float z2){ float d = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0); std::cout << std::fixed; std::cout << std::setprecision(2); cout << " Distance is " << d; return;} // Driver Codeint main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call for distance distance(x1, y1, z1, x2, y2, z2); return 0;} // This code is contributed// by Amber_Saxena. // C program to find// distance between// two points in 3 D.#include <stdio.h>#include<math.h> // function to print distancevoid distance(float x1, float y1, float z1, float x2, float y2, float z2){ float d = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0); printf("Distance is %f", d); return;} // Driver Codeint main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call for distance distance(x1, y1, z1, x2, y2, z2); return 0;} // This code is contributed// by Amber_Saxena. // Java program to find// distance between// two points in 3 D.import java .io.*;import java.lang.Math; class GFG{ // Function for// distancestatic void distance(float x1, float y1, float z1, float x2, float y2, float z2){ double d = Math.pow((Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2) * 1.0), 0.5); System.out.println("Distance is "+ d); return;} // Driver codepublic static void main(String[] args){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2);}} // This code is contributed// by Amber_Saxena. # Python program to find distance between# two points in 3 D. import math # Function to find distancedef distance(x1, y1, z1, x2, y2, z2): d = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) + math.pow(z2 - z1, 2)* 1.0) print("Distance is ") print(d) # Driver Codex1 = 2y1 = -5z1 = 7x2 = 3y2 = 4z2 = 5 # function call for distancedistance(x1, y1, z1, x2, y2, z2) // C# program to find// distance between// two points in 3 D.using System; class GFG{ // Function for// distancestatic void distance(float x1, float y1, float z1, float x2, float y2, float z2){ double d = Math.Pow((Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2) + Math.Pow(z2 - z1, 2) * 1.0), 0.5); Console.WriteLine("Distance is \n" + d); return;} // Driver codepublic static void Main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2);}} // This code is contributed// by chandan_jnu. <?php// PHP program to find// distance between// two points in 3 D. // function to print distancefunction distance($x1, $y1, $z1, $x2, $y2, $z2){ $d = sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2) + pow($z2 - $z1, 2) * 1.0); echo "Distance is ". $d;} // Driver Code$x1 = 2;$y1 = -5;$z1 = 7;$x2 = 3;$y2 = 4;$z2 = 5; // function call for distancedistance($x1, $y1, $z1, $x2, $y2, $z2); // This code is contributed// by Mahadev.?> <script> // javascript program to find// distance between// two points in 3 D. // Function for distance function distance(x1 , y1 , z1 , x2 , y2 , z2) { var d = Math.pow((Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2) * 1.0), 0.5); document.write("Distance is " + d.toFixed(10)); return; } // Driver code var x1 = 2; var y1 = -5; var z1 = 7; var x2 = 3; var y2 = 4; var z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2); // This code contributed by aashish1995 </script> Distance is 9.2736184955 Amber_Saxena Chandan_Kumar Mahadev99 aashish1995 school-programming Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26213, "s": 26185, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26340, "s": 26213, "text": "Given two coordinates (x1, y1, z1) and (x2, y2, z2) in 3 dimension. The task is to find the distance between them.Examples : " }, { "code": null, "e": 26505, "s": 26340, "text": "Input: x1, y1, z1 = (2, -5, 7)\n x2, y2, z1 = (3, 4, 5)\nOutput: 9.2736184955\n\nInput: x1, y1, z1 = (0, 0, 0)\n x2, y2, z1 = (1, 1, 1)\nOutput: 1.73205080757" }, { "code": null, "e": 26721, "s": 26507, "text": "Approach: The formula for distance between two points in 3 dimension i.e (x1, y1, z1) and (x2, y2, z2) has been derived from Pythagorean theorem which is:Distance = Below is the implementation of above formulae: " }, { "code": null, "e": 26725, "s": 26721, "text": "C++" }, { "code": null, "e": 26727, "s": 26725, "text": "C" }, { "code": null, "e": 26732, "s": 26727, "text": "Java" }, { "code": null, "e": 26739, "s": 26732, "text": "Python" }, { "code": null, "e": 26742, "s": 26739, "text": "C#" }, { "code": null, "e": 26746, "s": 26742, "text": "PHP" }, { "code": null, "e": 26757, "s": 26746, "text": "Javascript" }, { "code": "// C++ program to find// distance between// two points in 3 D.#include <bits/stdc++.h>#include <iomanip>#include <iostream>#include <math.h>using namespace std; // function to print distancevoid distance(float x1, float y1, float z1, float x2, float y2, float z2){ float d = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0); std::cout << std::fixed; std::cout << std::setprecision(2); cout << \" Distance is \" << d; return;} // Driver Codeint main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call for distance distance(x1, y1, z1, x2, y2, z2); return 0;} // This code is contributed// by Amber_Saxena.", "e": 27539, "s": 26757, "text": null }, { "code": "// C program to find// distance between// two points in 3 D.#include <stdio.h>#include<math.h> // function to print distancevoid distance(float x1, float y1, float z1, float x2, float y2, float z2){ float d = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0); printf(\"Distance is %f\", d); return;} // Driver Codeint main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call for distance distance(x1, y1, z1, x2, y2, z2); return 0;} // This code is contributed// by Amber_Saxena.", "e": 28202, "s": 27539, "text": null }, { "code": "// Java program to find// distance between// two points in 3 D.import java .io.*;import java.lang.Math; class GFG{ // Function for// distancestatic void distance(float x1, float y1, float z1, float x2, float y2, float z2){ double d = Math.pow((Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2) * 1.0), 0.5); System.out.println(\"Distance is \"+ d); return;} // Driver codepublic static void main(String[] args){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2);}} // This code is contributed// by Amber_Saxena.", "e": 29015, "s": 28202, "text": null }, { "code": "# Python program to find distance between# two points in 3 D. import math # Function to find distancedef distance(x1, y1, z1, x2, y2, z2): d = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) + math.pow(z2 - z1, 2)* 1.0) print(\"Distance is \") print(d) # Driver Codex1 = 2y1 = -5z1 = 7x2 = 3y2 = 4z2 = 5 # function call for distancedistance(x1, y1, z1, x2, y2, z2) ", "e": 29432, "s": 29015, "text": null }, { "code": "// C# program to find// distance between// two points in 3 D.using System; class GFG{ // Function for// distancestatic void distance(float x1, float y1, float z1, float x2, float y2, float z2){ double d = Math.Pow((Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2) + Math.Pow(z2 - z1, 2) * 1.0), 0.5); Console.WriteLine(\"Distance is \\n\" + d); return;} // Driver codepublic static void Main(){ float x1 = 2; float y1 = -5; float z1 = 7; float x2 = 3; float y2 = 4; float z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2);}} // This code is contributed// by chandan_jnu.", "e": 30198, "s": 29432, "text": null }, { "code": "<?php// PHP program to find// distance between// two points in 3 D. // function to print distancefunction distance($x1, $y1, $z1, $x2, $y2, $z2){ $d = sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2) + pow($z2 - $z1, 2) * 1.0); echo \"Distance is \". $d;} // Driver Code$x1 = 2;$y1 = -5;$z1 = 7;$x2 = 3;$y2 = 4;$z2 = 5; // function call for distancedistance($x1, $y1, $z1, $x2, $y2, $z2); // This code is contributed// by Mahadev.?>", "e": 30684, "s": 30198, "text": null }, { "code": "<script> // javascript program to find// distance between// two points in 3 D. // Function for distance function distance(x1 , y1 , z1 , x2 , y2 , z2) { var d = Math.pow((Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2) * 1.0), 0.5); document.write(\"Distance is \" + d.toFixed(10)); return; } // Driver code var x1 = 2; var y1 = -5; var z1 = 7; var x2 = 3; var y2 = 4; var z2 = 5; // function call // for distance distance(x1, y1, z1, x2, y2, z2); // This code contributed by aashish1995 </script>", "e": 31333, "s": 30684, "text": null }, { "code": null, "e": 31359, "s": 31333, "text": "Distance is \n9.2736184955" }, { "code": null, "e": 31374, "s": 31361, "text": "Amber_Saxena" }, { "code": null, "e": 31388, "s": 31374, "text": "Chandan_Kumar" }, { "code": null, "e": 31398, "s": 31388, "text": "Mahadev99" }, { "code": null, "e": 31410, "s": 31398, "text": "aashish1995" }, { "code": null, "e": 31429, "s": 31410, "text": "school-programming" }, { "code": null, "e": 31442, "s": 31429, "text": "Mathematical" }, { "code": null, "e": 31461, "s": 31442, "text": "School Programming" }, { "code": null, "e": 31474, "s": 31461, "text": "Mathematical" }, { "code": null, "e": 31572, "s": 31474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31596, "s": 31572, "text": "Merge two sorted arrays" }, { "code": null, "e": 31639, "s": 31596, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31653, "s": 31639, "text": "Prime Numbers" }, { "code": null, "e": 31695, "s": 31653, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31768, "s": 31695, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31786, "s": 31768, "text": "Python Dictionary" }, { "code": null, "e": 31802, "s": 31786, "text": "Arrays in C/C++" }, { "code": null, "e": 31821, "s": 31802, "text": "Inheritance in C++" }, { "code": null, "e": 31846, "s": 31821, "text": "Reverse a string in Java" } ]
Program to find nth term in Look and Say Sequence in Python
Suppose we have a number n we have to generate nth term in “Look and Say” sequence. This is a sequence whose few terms are like below − 1 11 21 1211 111221 The string will be read like 1 (One) 11 (One 1) So read the previous 1, and say “One 1” 21 (Two 1) So read the previous 11, and say “Two 1” 1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1” 111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1” Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term. To solve this, we will follow this approach − set s := “1” if n = 1, then return s for i := 2 to n + 1j := 0temp := empty stringcurr = empty string and count := 0while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0temp := temp + count as string + curr j := 0 temp := empty string curr = empty string and count := 0 while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0 if curr is empty string, thencurr := s[j], count := 1 and increase j by 1 curr := s[j], count := 1 and increase j by 1 else if curr is s[j], thenincrease count and j by 1 increase count and j by 1 otherwise:temp := temp + count as string + currcurr = empty stringcount := 0 temp := temp + count as string + curr curr = empty string count := 0 temp := temp + count as string + curr return s Let us see the following implementation to get better understanding − Live Demo class Solution(object): def solve(self, n): s = "1" if n == 1: return s for i in range(2,n+1): j = 0 temp = "" curr = "" count = 0 while j <len(s): if curr =="": curr=s[j] count=1 j+=1 elif curr == s[j]: count+=1 j+=1 else: temp+= str(count) + curr curr="" count = 0 temp+=str(count) + curr s=temp return s ob = Solution() n = 5 print(ob.solve(n)) 5 "111221"
[ { "code": null, "e": 1198, "s": 1062, "text": "Suppose we have a number n we have to generate nth term in “Look and Say” sequence. This is a sequence whose few terms are like below −" }, { "code": null, "e": 1200, "s": 1198, "text": "1" }, { "code": null, "e": 1203, "s": 1200, "text": "11" }, { "code": null, "e": 1206, "s": 1203, "text": "21" }, { "code": null, "e": 1211, "s": 1206, "text": "1211" }, { "code": null, "e": 1218, "s": 1211, "text": "111221" }, { "code": null, "e": 1247, "s": 1218, "text": "The string will be read like" }, { "code": null, "e": 1255, "s": 1247, "text": "1 (One)" }, { "code": null, "e": 1306, "s": 1255, "text": "11 (One 1) So read the previous 1, and say “One 1”" }, { "code": null, "e": 1358, "s": 1306, "text": "21 (Two 1) So read the previous 11, and say “Two 1”" }, { "code": null, "e": 1424, "s": 1358, "text": "1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1”" }, { "code": null, "e": 1506, "s": 1424, "text": "111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1”" }, { "code": null, "e": 1630, "s": 1506, "text": "Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term.\nTo solve this, we will follow this approach −" }, { "code": null, "e": 1643, "s": 1630, "text": "set s := “1”" }, { "code": null, "e": 1667, "s": 1643, "text": "if n = 1, then return s" }, { "code": null, "e": 2009, "s": 1667, "text": "for i := 2 to n + 1j := 0temp := empty stringcurr = empty string and count := 0while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0temp := temp + count as string + curr" }, { "code": null, "e": 2016, "s": 2009, "text": "j := 0" }, { "code": null, "e": 2037, "s": 2016, "text": "temp := empty string" }, { "code": null, "e": 2072, "s": 2037, "text": "curr = empty string and count := 0" }, { "code": null, "e": 2298, "s": 2072, "text": "while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0" }, { "code": null, "e": 2372, "s": 2298, "text": "if curr is empty string, thencurr := s[j], count := 1 and increase j by 1" }, { "code": null, "e": 2417, "s": 2372, "text": "curr := s[j], count := 1 and increase j by 1" }, { "code": null, "e": 2469, "s": 2417, "text": "else if curr is s[j], thenincrease count and j by 1" }, { "code": null, "e": 2495, "s": 2469, "text": "increase count and j by 1" }, { "code": null, "e": 2572, "s": 2495, "text": "otherwise:temp := temp + count as string + currcurr = empty stringcount := 0" }, { "code": null, "e": 2610, "s": 2572, "text": "temp := temp + count as string + curr" }, { "code": null, "e": 2630, "s": 2610, "text": "curr = empty string" }, { "code": null, "e": 2641, "s": 2630, "text": "count := 0" }, { "code": null, "e": 2679, "s": 2641, "text": "temp := temp + count as string + curr" }, { "code": null, "e": 2688, "s": 2679, "text": "return s" }, { "code": null, "e": 2758, "s": 2688, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2769, "s": 2758, "text": " Live Demo" }, { "code": null, "e": 3387, "s": 2769, "text": "class Solution(object):\n def solve(self, n):\n s = \"1\"\n if n == 1:\n return s\n for i in range(2,n+1):\n j = 0\n temp = \"\"\n curr = \"\"\n count = 0\n while j <len(s):\n if curr ==\"\":\n curr=s[j]\n count=1\n j+=1\n elif curr == s[j]:\n count+=1\n j+=1\n else:\n temp+= str(count) + curr\n curr=\"\"\n count = 0\n temp+=str(count) + curr\n s=temp\n return s\nob = Solution()\nn = 5\nprint(ob.solve(n))" }, { "code": null, "e": 3389, "s": 3387, "text": "5" }, { "code": null, "e": 3398, "s": 3389, "text": "\"111221\"" } ]
Python - Check if frequencies of all characters of a string are different
In this article we will see how to find the frequency of each character in a given string. Then see if two or more characters have the same frequency in the given string or not. We will accomplish this in two steps. In the first program we will just find out the frequency of each character. Here we find the frequency of each character in the given input screen. We declare a empty dictionary and then add each character as a string. We also assign keys to each of the character to create the key-value pair needed by the dictionary. Live Demo in_string = "She sells sea shells" dic1 = {} for k in in_string: if k in dic1.keys(): dic1[k]+=1 else: dic1[k]=1 print(dic1) for k in dic1.keys(): print(k, " repeats ",dic1[k]," time's") Running the above code gives us the following result − {'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1} S repeats 1 time's h repeats 2 time's e repeats 4 time's repeats 3 time's s repeats 5 time's l repeats 4 time's a repeats 1 time's Next we extend the above program to find out the frequency for each unique character. If the unique value of the frequency is greater than one, then we conclude that not all characters have same frequency. Live Demo in_string = "She sells sea shells" dic1 = {} for k in in_string: if k in dic1.keys(): dic1[k]+=1 else: dic1[k]=1 print(dic1) u_value = set( val for udic in dic1 for val in (dic1.values())) print("Number of Unique frequencies: ",len(u_value)) if len(u_value) == 1: print("All character have same frequiency") else: print("The characters have different frequencies.") Running the above code gives us the following result − {'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1} Number of Unique frequencies: 5 The characters have different frequencies.
[ { "code": null, "e": 1354, "s": 1062, "text": "In this article we will see how to find the frequency of each character in a given string. Then see if two or more characters have the same frequency in the given string or not. We will accomplish this in two steps. In the first program we will just find out the frequency of each character." }, { "code": null, "e": 1597, "s": 1354, "text": "Here we find the frequency of each character in the given input screen. We declare a empty dictionary and then add each character as a string. We also assign keys to each of the character to create the key-value pair needed by the dictionary." }, { "code": null, "e": 1608, "s": 1597, "text": " Live Demo" }, { "code": null, "e": 1816, "s": 1608, "text": "in_string = \"She sells sea shells\"\ndic1 = {}\nfor k in in_string:\n if k in dic1.keys():\n dic1[k]+=1\n else:\n dic1[k]=1\nprint(dic1)\nfor k in dic1.keys():\n print(k, \" repeats \",dic1[k],\" time's\")" }, { "code": null, "e": 1871, "s": 1816, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2061, "s": 1871, "text": "{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}\nS repeats 1 time's\nh repeats 2 time's\ne repeats 4 time's\n repeats 3 time's\ns repeats 5 time's\nl repeats 4 time's\na repeats 1 time's" }, { "code": null, "e": 2267, "s": 2061, "text": "Next we extend the above program to find out the frequency for each unique character. If the unique value of the frequency is greater than one, then we conclude that not all characters have same frequency." }, { "code": null, "e": 2278, "s": 2267, "text": " Live Demo" }, { "code": null, "e": 2668, "s": 2278, "text": "in_string = \"She sells sea shells\"\ndic1 = {}\nfor k in in_string:\n if k in dic1.keys():\n dic1[k]+=1\n else:\n dic1[k]=1\nprint(dic1)\nu_value = set( val for udic in dic1 for val in (dic1.values()))\nprint(\"Number of Unique frequencies: \",len(u_value))\nif len(u_value) == 1:\n print(\"All character have same frequiency\")\nelse:\n print(\"The characters have different frequencies.\")" }, { "code": null, "e": 2723, "s": 2668, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2855, "s": 2723, "text": "{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}\nNumber of Unique frequencies: 5\nThe characters have different frequencies." } ]
Check how many rows are in a MySQL database table?
To know how many rows are in a ySQL database table, you need to use aggregate function COUNT(*). The syntax is as follows SELECT COUNT(*) FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table CountRowsDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(20) - > ); Query OK, 0 rows affected (0.78 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into CountRowsDemo(Name) values(NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into CountRowsDemo(Name) values('Sam'); Query OK, 1 row affected (0.25 sec) mysql> insert into CountRowsDemo(Name) values(NULL); Query OK, 1 row affected (0.11 sec) mysql> insert into CountRowsDemo(Name) values('Mike'); Query OK, 1 row affected (0.21 sec) mysql> insert into CountRowsDemo(Name) values('David'); Query OK, 1 row affected (0.11 sec) mysql> insert into CountRowsDemo(Name) values(NULL); Query OK, 1 row affected (0.11 sec) mysql> insert into CountRowsDemo(Name) values(NULL); Query OK, 1 row affected (0.09 sec) mysql> insert into CountRowsDemo(Name) values('Carol'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement. The query is as follows mysql> select *from CountRowsDemo; The following is the output +----+-------+ | Id | Name | +----+-------+ | 1 | NULL | | 2 | Sam | | 3 | NULL | | 4 | Mike | | 5 | David | | 6 | NULL | | 7 | NULL | | 8 | Carol | +----+-------+ 8 rows in set (0.00 sec) Now let us run the following query to count rows from a table mysql> select count(*) AS TotalRows from CountRowsDemo; The following is the output +-----------+ | TotalRows | +-----------+ | 8 | +-----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1159, "s": 1062, "text": "To know how many rows are in a ySQL database table, you need to use aggregate function COUNT(*)." }, { "code": null, "e": 1184, "s": 1159, "text": "The syntax is as follows" }, { "code": null, "e": 1220, "s": 1184, "text": "SELECT COUNT(*) FROM yourTableName;" }, { "code": null, "e": 1317, "s": 1220, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1482, "s": 1317, "text": "mysql> create table CountRowsDemo\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > Name varchar(20)\n - > );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1537, "s": 1482, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1561, "s": 1537, "text": "The query is as follows" }, { "code": null, "e": 2282, "s": 1561, "text": "mysql> insert into CountRowsDemo(Name) values(NULL);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into CountRowsDemo(Name) values('Sam');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into CountRowsDemo(Name) values(NULL);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into CountRowsDemo(Name) values('Mike');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into CountRowsDemo(Name) values('David');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into CountRowsDemo(Name) values(NULL);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into CountRowsDemo(Name) values(NULL);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into CountRowsDemo(Name) values('Carol');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2341, "s": 2282, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2365, "s": 2341, "text": "The query is as follows" }, { "code": null, "e": 2400, "s": 2365, "text": "mysql> select *from CountRowsDemo;" }, { "code": null, "e": 2428, "s": 2400, "text": "The following is the output" }, { "code": null, "e": 2633, "s": 2428, "text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | NULL |\n| 2 | Sam |\n| 3 | NULL |\n| 4 | Mike |\n| 5 | David |\n| 6 | NULL |\n| 7 | NULL |\n| 8 | Carol |\n+----+-------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2695, "s": 2633, "text": "Now let us run the following query to count rows from a table" }, { "code": null, "e": 2751, "s": 2695, "text": "mysql> select count(*) AS TotalRows from CountRowsDemo;" }, { "code": null, "e": 2779, "s": 2751, "text": "The following is the output" }, { "code": null, "e": 2873, "s": 2779, "text": "+-----------+\n| TotalRows |\n+-----------+\n| 8 |\n+-----------+\n1 row in set (0.00 sec)" } ]
How to check if a table exists in MySQL and create if it does not already exist?
If you try to create a table and the table name already exist then MySQL will give a warning message. Let us verify the concept. Here, we are creating a table that already exist − mysql> CREATE TABLE IF NOT EXISTS DemoTable ( CustomerId int, CustomerName varchar(30), CustomerAge int ); Query OK, 0 rows affected, 1 warning (0.05 sec) The table name DemoTable is already present. Let us check the warning message. Following is the query − mysql> show warnings; This will produce the following output i.e. the warning message − +-------+------+------------------------------------+ | Level | Code | Message | +-------+------+------------------------------------+ | Note | 1050 | Table 'demotable' already exists | +-------+------+------------------------------------+ 1 row in set (0.00 sec) Let us change the table name and create a table that does not already exist − mysql> CREATE TABLE IF NOT EXISTS DemoTable2 ( CustomerId int, CustomerName varchar(20), CustomerAge int ); Query OK, 0 rows affected (0.56 sec) Table created successfully above since it does not already exist. Following is the query to insert records in the table using insert command − mysql> insert into DemoTable2 values(101,'Chris',23); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(102,'Robert',24); Query OK, 1 row affected (0.12 sec) Following is the query to display records from the table using select command − mysql> select *from DemoTable2; This will produce the following output +------------+--------------+-------------+ | CustomerId | CustomerName | CustomerAge | +------------+--------------+-------------+ | 101 | Chris | 23 | | 102 | Robert | 24 | +------------+--------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1191, "s": 1062, "text": "If you try to create a table and the table name already exist then MySQL will give a warning message. Let us verify the concept." }, { "code": null, "e": 1242, "s": 1191, "text": "Here, we are creating a table that already exist −" }, { "code": null, "e": 1412, "s": 1242, "text": "mysql> CREATE TABLE IF NOT EXISTS DemoTable\n (\n CustomerId int,\n CustomerName varchar(30),\n CustomerAge int\n );\nQuery OK, 0 rows affected, 1 warning (0.05 sec)" }, { "code": null, "e": 1491, "s": 1412, "text": "The table name DemoTable is already present. Let us check the warning message." }, { "code": null, "e": 1516, "s": 1491, "text": "Following is the query −" }, { "code": null, "e": 1538, "s": 1516, "text": "mysql> show warnings;" }, { "code": null, "e": 1604, "s": 1538, "text": "This will produce the following output i.e. the warning message −" }, { "code": null, "e": 1898, "s": 1604, "text": "+-------+------+------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------+\n| Note | 1050 | Table 'demotable' already exists |\n+-------+------+------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1976, "s": 1898, "text": "Let us change the table name and create a table that does not already exist −" }, { "code": null, "e": 2136, "s": 1976, "text": "mysql> CREATE TABLE IF NOT EXISTS DemoTable2\n (\n CustomerId int,\n CustomerName varchar(20),\n CustomerAge int\n );\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 2202, "s": 2136, "text": "Table created successfully above since it does not already exist." }, { "code": null, "e": 2279, "s": 2202, "text": "Following is the query to insert records in the table using insert command −" }, { "code": null, "e": 2460, "s": 2279, "text": "mysql> insert into DemoTable2 values(101,'Chris',23);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable2 values(102,'Robert',24);\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2540, "s": 2460, "text": "Following is the query to display records from the table using select command −" }, { "code": null, "e": 2572, "s": 2540, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2611, "s": 2572, "text": "This will produce the following output" }, { "code": null, "e": 2900, "s": 2611, "text": "+------------+--------------+-------------+\n| CustomerId | CustomerName | CustomerAge |\n+------------+--------------+-------------+\n| 101 | Chris | 23 |\n| 102 | Robert | 24 |\n+------------+--------------+-------------+\n2 rows in set (0.00 sec)" } ]
Time Functions in Python?
Python provides library to read, represent and reset the time information in many ways by using “time” module. Date, time and date time are an object in Python, so whenever we do any operation on them, we actually manipulate objects not strings or timestamps. In this section we’re going to discuss the “time” module which allows us to handle various operations on time. The time module follows the “EPOCH” convention which refers to the point where the time starts. In Unix system “EPOCH” time started from 1 January, 12:00 am, 1970 to year 2038. To determine the EPOCH time value on your system, just type below code - >>> import time >>> time.gmtime(0) time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) A tick refers to a time interval which is a floating-point number measured as units of seconds. Sometime we get time as Daylight Saving Time(DST), where the clock moves 1 hour forward during the summer time, and back again in the fall. Most common functions in Python Time Module - 1. time.time() function The time() is the main function of the time module. It measures the number of seconds since the epoch as a floating point value. time.time() Program to demonstrate above function: import time print("Number of seconds elapsed since the epoch are : ", time.time()) Number of seconds elapsed since the epoch are : 1553262407.0398576 We can use python time function to calculate the elapsed Wall-clock time between two points. Below is the program to calculate Wall clock time: import time start = time.time() print("Time elapsed on working...") time.sleep(0.9) end = time.time() print("Time consumed in working: ",end - start) Time elapsed on working... Time consumed in working: 0.9219651222229004 2. time.clock() function The time.clock() function return the processor time. It is used for performance testing/benchmarking. time.clock() The clock() function returns the right time taken by the program and it more accurate than its counterpart. Let’s write a program using above two time functions (discussed above) to differentiate: import time template = 'time()# {:0.2f}, clock()# {:0.2f}' print(template.format(time.time(), time.clock())) for i in range(5, 0, -1): print('---Sleeping for: ', i, 'sec.') time.sleep(i) print(template.format(time.time(), time.clock()) ) time()# 1553263728.08, clock()# 0.00 ---Sleeping for: 5 sec. time()# 1553263733.14, clock()# 5.06 ---Sleeping for: 4 sec. time()# 1553263737.25, clock()# 9.17 ---Sleeping for: 3 sec. time()# 1553263740.30, clock()# 12.22 ---Sleeping for: 2 sec. time()# 1553263742.36, clock()# 14.28 ---Sleeping for: 1 sec. time()# 1553263743.42, clock()# 15.34 3. time.ctime() function time.time() function takes the time in “seconds since the epoch” as input and translates into a human readable string value as per the local time. If no argument is passed, it returns the current time. import time print('The current local time is :', time.ctime()) newtime = time.time() + 60 print('60 secs from now :', time.ctime(newtime)) The current local time is : Fri Mar 22 19:43:11 2019 60 secs from now : Fri Mar 22 19:44:11 2019 4. time.sleep() function time.sleep() function halts the execution of the current thread for the specified number of seconds. Pass a floating point value as input to get more precise sleep time. The sleep() function can be used in situation where we need to wait for a file to finish closing or let a database commit to happen. import time # using ctime() to display present time print ("Time starts from : ",end="") print (time.ctime()) # using sleep() to suspend execution print ('Waiting for 5 sec.') time.sleep(5) # using ctime() to show present time print ("Time ends at : ",end="") print (time.ctime()) Time starts from : Fri Mar 22 20:00:00 2019 Waiting for 5 sec. Time ends at : Fri Mar 22 20:00:05 2019 5. time.struct_time class The time.struct_time is the only data structure present in the time module. It has a named tuple interface and is accessible via index or the attribute name. time.struct_time This class is useful when you need to access the specific field of a date. This class provides number of functions like localtime(), gmtime() and return the struct_time objects. import time print(' Current local time:', time.ctime()) t = time.localtime() print('Day of month:', t.tm_mday) print('Day of week :', t.tm_wday) print('Day of year :', t.tm_yday) Current local time: Fri Mar 22 20:10:25 2019 Day of month: 22 Day of week : 4 Day of year : 81 6. time.strftime() function This function takes a tuple or struct_time in the second argument and converts to a string as per the format specified in the first argument. time.strftime() Below is the program to implement time.strftime() function - import time now = time.localtime(time.time()) print("Current date time is: ",time.asctime(now)) print(time.strftime("%y/%m/%d %H:%M", now)) print(time.strftime("%a %b %d", now)) print(time.strftime("%c", now)) print(time.strftime("%I %p", now)) print(time.strftime("%Y-%m-%d %H:%M:%S %Z", now)) Current date time is: Fri Mar 22 20:13:43 2019 19/03/22 20:13 Fri Mar 22 Fri Mar 22 20:13:43 2019 08 PM 2019-03-22 20:13:43 India Standard Time There are two time-properties which give you the timezone info - 1. time.timezone It returns the offset of the local (non-DST) timezone in UTC format. >>> time.timezone -19800 2. time.tzname – It returns a tuple containing the local non-DST and DST time zones. >>> time.tzname ('India Standard Time', 'India Daylight Time')
[ { "code": null, "e": 1322, "s": 1062, "text": "Python provides library to read, represent and reset the time information in many ways by using “time” module. Date, time and date time are an object in Python, so whenever we do any operation on them, we actually manipulate objects not strings or timestamps." }, { "code": null, "e": 1433, "s": 1322, "text": "In this section we’re going to discuss the “time” module which allows us to handle various operations on time." }, { "code": null, "e": 1610, "s": 1433, "text": "The time module follows the “EPOCH” convention which refers to the point where the time starts. In Unix system “EPOCH” time started from 1 January, 12:00 am, 1970 to year 2038." }, { "code": null, "e": 1683, "s": 1610, "text": "To determine the EPOCH time value on your system, just type below code -" }, { "code": null, "e": 1718, "s": 1683, "text": ">>> import time\n>>> time.gmtime(0)" }, { "code": null, "e": 1835, "s": 1718, "text": "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0,\ntm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)" }, { "code": null, "e": 2071, "s": 1835, "text": "A tick refers to a time interval which is a floating-point number measured as units of seconds.\nSometime we get time as Daylight Saving Time(DST), where the clock moves 1 hour forward during the summer time, and back again in the fall." }, { "code": null, "e": 2117, "s": 2071, "text": "Most common functions in Python Time Module -" }, { "code": null, "e": 2141, "s": 2117, "text": "1. time.time() function" }, { "code": null, "e": 2270, "s": 2141, "text": "The time() is the main function of the time module. It measures the number of seconds since the epoch as a floating point value." }, { "code": null, "e": 2282, "s": 2270, "text": "time.time()" }, { "code": null, "e": 2321, "s": 2282, "text": "Program to demonstrate above function:" }, { "code": null, "e": 2404, "s": 2321, "text": "import time\nprint(\"Number of seconds elapsed since the epoch are : \", time.time())" }, { "code": null, "e": 2471, "s": 2404, "text": "Number of seconds elapsed since the epoch are : 1553262407.0398576" }, { "code": null, "e": 2564, "s": 2471, "text": "We can use python time function to calculate the elapsed Wall-clock time between two points." }, { "code": null, "e": 2615, "s": 2564, "text": "Below is the program to calculate Wall clock time:" }, { "code": null, "e": 2765, "s": 2615, "text": "import time\nstart = time.time()\nprint(\"Time elapsed on working...\")\ntime.sleep(0.9)\nend = time.time()\nprint(\"Time consumed in working: \",end - start)" }, { "code": null, "e": 2837, "s": 2765, "text": "Time elapsed on working...\nTime consumed in working: 0.9219651222229004" }, { "code": null, "e": 2862, "s": 2837, "text": "2. time.clock() function" }, { "code": null, "e": 2964, "s": 2862, "text": "The time.clock() function return the processor time. It is used for performance testing/benchmarking." }, { "code": null, "e": 2977, "s": 2964, "text": "time.clock()" }, { "code": null, "e": 3085, "s": 2977, "text": "The clock() function returns the right time taken by the program and it more accurate than its counterpart." }, { "code": null, "e": 3174, "s": 3085, "text": "Let’s write a program using above two time functions (discussed above) to differentiate:" }, { "code": null, "e": 3415, "s": 3174, "text": "import time\ntemplate = 'time()# {:0.2f}, clock()# {:0.2f}'\nprint(template.format(time.time(), time.clock()))\nfor i in range(5, 0, -1):\n print('---Sleeping for: ', i, 'sec.')\ntime.sleep(i)\nprint(template.format(time.time(), time.clock())\n)" }, { "code": null, "e": 3760, "s": 3415, "text": "time()# 1553263728.08, clock()# 0.00\n---Sleeping for: 5 sec.\ntime()# 1553263733.14, clock()# 5.06\n---Sleeping for: 4 sec.\ntime()# 1553263737.25, clock()# 9.17\n---Sleeping for: 3 sec.\ntime()# 1553263740.30, clock()# 12.22\n---Sleeping for: 2 sec.\ntime()# 1553263742.36, clock()# 14.28\n---Sleeping for: 1 sec.\ntime()# 1553263743.42, clock()# 15.34" }, { "code": null, "e": 3785, "s": 3760, "text": "3. time.ctime() function" }, { "code": null, "e": 3987, "s": 3785, "text": "time.time() function takes the time in “seconds since the epoch” as input and translates into a human readable string value as per the local time. If no argument is passed, it returns the current time." }, { "code": null, "e": 4126, "s": 3987, "text": "import time\nprint('The current local time is :', time.ctime())\nnewtime = time.time() + 60\nprint('60 secs from now :', time.ctime(newtime))" }, { "code": null, "e": 4223, "s": 4126, "text": "The current local time is : Fri Mar 22 19:43:11 2019\n60 secs from now : Fri Mar 22 19:44:11 2019" }, { "code": null, "e": 4248, "s": 4223, "text": "4. time.sleep() function" }, { "code": null, "e": 4418, "s": 4248, "text": "time.sleep() function halts the execution of the current thread for the specified number of seconds. Pass a floating point value as input to get more precise sleep time." }, { "code": null, "e": 4551, "s": 4418, "text": "The sleep() function can be used in situation where we need to wait for a file to finish closing or let a database commit to happen." }, { "code": null, "e": 4832, "s": 4551, "text": "import time\n# using ctime() to display present time\nprint (\"Time starts from : \",end=\"\")\nprint (time.ctime())\n# using sleep() to suspend execution\nprint ('Waiting for 5 sec.')\ntime.sleep(5)\n# using ctime() to show present time\nprint (\"Time ends at : \",end=\"\")\nprint (time.ctime())" }, { "code": null, "e": 4935, "s": 4832, "text": "Time starts from : Fri Mar 22 20:00:00 2019\nWaiting for 5 sec.\nTime ends at : Fri Mar 22 20:00:05 2019" }, { "code": null, "e": 4961, "s": 4935, "text": "5. time.struct_time class" }, { "code": null, "e": 5119, "s": 4961, "text": "The time.struct_time is the only data structure present in the time module. It has a named tuple interface and is accessible via index or the attribute name." }, { "code": null, "e": 5136, "s": 5119, "text": "time.struct_time" }, { "code": null, "e": 5211, "s": 5136, "text": "This class is useful when you need to access the specific field of a date." }, { "code": null, "e": 5314, "s": 5211, "text": "This class provides number of functions like localtime(), gmtime() and return the struct_time objects." }, { "code": null, "e": 5493, "s": 5314, "text": "import time\nprint(' Current local time:', time.ctime())\nt = time.localtime()\nprint('Day of month:', t.tm_mday)\nprint('Day of week :', t.tm_wday)\nprint('Day of year :', t.tm_yday)" }, { "code": null, "e": 5588, "s": 5493, "text": "Current local time: Fri Mar 22 20:10:25 2019\nDay of month: 22\nDay of week : 4\nDay of year : 81" }, { "code": null, "e": 5616, "s": 5588, "text": "6. time.strftime() function" }, { "code": null, "e": 5758, "s": 5616, "text": "This function takes a tuple or struct_time in the second argument and converts to a string as per the format specified in the first argument." }, { "code": null, "e": 5774, "s": 5758, "text": "time.strftime()" }, { "code": null, "e": 5835, "s": 5774, "text": "Below is the program to implement time.strftime() function -" }, { "code": null, "e": 6130, "s": 5835, "text": "import time\nnow = time.localtime(time.time())\nprint(\"Current date time is: \",time.asctime(now))\nprint(time.strftime(\"%y/%m/%d %H:%M\", now))\nprint(time.strftime(\"%a %b %d\", now))\nprint(time.strftime(\"%c\", now))\nprint(time.strftime(\"%I %p\", now))\nprint(time.strftime(\"%Y-%m-%d %H:%M:%S %Z\", now))" }, { "code": null, "e": 6274, "s": 6130, "text": "Current date time is: Fri Mar 22 20:13:43 2019\n19/03/22 20:13\nFri Mar 22\nFri Mar 22 20:13:43 2019\n08 PM\n2019-03-22 20:13:43 India Standard Time" }, { "code": null, "e": 6339, "s": 6274, "text": "There are two time-properties which give you the timezone info -" }, { "code": null, "e": 6356, "s": 6339, "text": "1. time.timezone" }, { "code": null, "e": 6425, "s": 6356, "text": "It returns the offset of the local (non-DST) timezone in UTC format." }, { "code": null, "e": 6450, "s": 6425, "text": ">>> time.timezone\n-19800" }, { "code": null, "e": 6535, "s": 6450, "text": "2. time.tzname – It returns a tuple containing the local non-DST and DST time zones." }, { "code": null, "e": 6598, "s": 6535, "text": ">>> time.tzname\n('India Standard Time', 'India Daylight Time')" } ]
How to find the group-wise correlation coefficient in R?
If we have two continuous and one categorical column in an R data frame then we can find the correlation coefficient between continuous values for the categories in the categorical column. For this purpose, we can use by function and pass the cor function with the spearman method as shown in the below examples. Consider the below data frame: Live Demo > x1<-sample(c("A","B","C"),20,replace=TRUE) > y1<-rnorm(20,1,0.24) > z1<-rpois(20,2) > df1<-data.frame(x1,y1,z1) > df1 x1 y1 z1 1 A 1.1155324 2 2 C 0.9801564 3 3 B 0.9116162 1 4 A 0.8406772 3 5 C 0.8009355 2 6 A 0.9331637 2 7 B 1.0642089 1 8 B 1.1633515 0 9 B 1.1599037 5 10 B 1.0509981 2 11 B 0.7574267 1 12 B 0.8456225 1 13 B 0.8926751 2 14 B 0.6074419 3 15 C 0.7999792 0 16 A 1.0685236 2 17 B 0.9756677 3 18 A 0.9495342 0 19 C 1.0109747 2 20 A 0.9090985 4 Finding the correlation between y1 and z1 for categories in x1: > by(df1,df1$x1,FUN=function(x) cor(df1$y1,df1$z1,method="spearman")) df1$x1: A [1] 0.03567607 df1$x1: B [1] 0.03567607 df1$x1: C [1] 0.03567607 Live Demo > x2<-sample(c("India","China","France"),20,replace=TRUE) > y2<-rexp(20,0.335) > z2<-runif(20,2,10) > df2<-data.frame(x2,y2,z2) > df2 x2 y2 z2 1 France 2.31790394 2.649538 2 China 10.61012173 8.340615 3 France 5.00085220 6.602884 4 France 1.67707140 7.722530 5 India 9.60663732 9.837268 6 France 1.46030289 5.370930 7 France 10.44614704 9.035748 8 India 0.39506766 6.318701 9 China 1.83071453 7.282782 10 China 0.23080001 7.210144 11 India 2.27763766 9.233019 12 China 18.21276888 9.928614 13 France 1.72085517 9.176826 14 India 4.77786071 8.899026 15 China 8.55501571 7.240147 16 China 0.19832026 5.641800 17 India 0.03113389 6.928705 18 China 0.56958471 3.496314 19 China 0.72728737 6.903436 20 India 8.73571474 5.286486 Finding the correlation between y2 and z2 for categories in x2: > by(df2,df2$x2,FUN=function(x) cor(df2$y2,df2$z2,method="spearman")) df2$x2: China [1] 0.487218 df2$x2: France [1] 0.487218 df2$x2: India [1] 0.487218
[ { "code": null, "e": 1375, "s": 1062, "text": "If we have two continuous and one categorical column in an R data frame then we can find the correlation coefficient between continuous values for the categories in the categorical column. For this purpose, we can use by function and pass the cor function with the spearman method as shown in the below examples." }, { "code": null, "e": 1406, "s": 1375, "text": "Consider the below data frame:" }, { "code": null, "e": 1416, "s": 1406, "text": "Live Demo" }, { "code": null, "e": 1536, "s": 1416, "text": "> x1<-sample(c(\"A\",\"B\",\"C\"),20,replace=TRUE)\n> y1<-rnorm(20,1,0.24)\n> z1<-rpois(20,2)\n> df1<-data.frame(x1,y1,z1)\n> df1" }, { "code": null, "e": 1883, "s": 1536, "text": " x1 y1 z1\n1 A 1.1155324 2\n2 C 0.9801564 3\n3 B 0.9116162 1\n4 A 0.8406772 3\n5 C 0.8009355 2\n6 A 0.9331637 2\n7 B 1.0642089 1\n8 B 1.1633515 0\n9 B 1.1599037 5\n10 B 1.0509981 2\n11 B 0.7574267 1\n12 B 0.8456225 1\n13 B 0.8926751 2\n14 B 0.6074419 3\n15 C 0.7999792 0\n16 A 1.0685236 2\n17 B 0.9756677 3\n18 A 0.9495342 0\n19 C 1.0109747 2\n20 A 0.9090985 4" }, { "code": null, "e": 1947, "s": 1883, "text": "Finding the correlation between y1 and z1 for categories in x1:" }, { "code": null, "e": 2027, "s": 1947, "text": "> by(df1,df1$x1,FUN=function(x) cor(df1$y1,df1$z1,method=\"spearman\"))\ndf1$x1: A" }, { "code": null, "e": 2042, "s": 2027, "text": "[1] 0.03567607" }, { "code": null, "e": 2052, "s": 2042, "text": "df1$x1: B" }, { "code": null, "e": 2068, "s": 2052, "text": "[1] 0.03567607\n" }, { "code": null, "e": 2078, "s": 2068, "text": "df1$x1: C" }, { "code": null, "e": 2093, "s": 2078, "text": "[1] 0.03567607" }, { "code": null, "e": 2103, "s": 2093, "text": "Live Demo" }, { "code": null, "e": 2237, "s": 2103, "text": "> x2<-sample(c(\"India\",\"China\",\"France\"),20,replace=TRUE)\n> y2<-rexp(20,0.335)\n> z2<-runif(20,2,10)\n> df2<-data.frame(x2,y2,z2)\n> df2" }, { "code": null, "e": 2843, "s": 2237, "text": " x2 y2 z2\n1 France 2.31790394 2.649538\n2 China 10.61012173 8.340615\n3 France 5.00085220 6.602884\n4 France 1.67707140 7.722530\n5 India 9.60663732 9.837268\n6 France 1.46030289 5.370930\n7 France 10.44614704 9.035748\n8 India 0.39506766 6.318701\n9 China 1.83071453 7.282782\n10 China 0.23080001 7.210144\n11 India 2.27763766 9.233019\n12 China 18.21276888 9.928614\n13 France 1.72085517 9.176826\n14 India 4.77786071 8.899026\n15 China 8.55501571 7.240147\n16 China 0.19832026 5.641800\n17 India 0.03113389 6.928705\n18 China 0.56958471 3.496314\n19 China 0.72728737 6.903436\n20 India 8.73571474 5.286486" }, { "code": null, "e": 2907, "s": 2843, "text": "Finding the correlation between y2 and z2 for categories in x2:" }, { "code": null, "e": 2991, "s": 2907, "text": "> by(df2,df2$x2,FUN=function(x) cor(df2$y2,df2$z2,method=\"spearman\"))\ndf2$x2: China" }, { "code": null, "e": 3004, "s": 2991, "text": "[1] 0.487218" }, { "code": null, "e": 3019, "s": 3004, "text": "df2$x2: France" }, { "code": null, "e": 3033, "s": 3019, "text": "[1] 0.487218\n" }, { "code": null, "e": 3047, "s": 3033, "text": "df2$x2: India" }, { "code": null, "e": 3060, "s": 3047, "text": "[1] 0.487218" } ]
Set lines to different transparency using ggplot2 in R - GeeksforGeeks
18 Jul, 2021 In this article, we will be discussing how can transparency of lines be made different for a line plot using GGPLOT2 in R programming language. First, let’s plot a line graph, so that the difference is apparent. R library("ggplot2") function1<- function(x){x**2} function2<-function(x){x**3} function3<-function(x){x/2} function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x = -2:2, values = c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun = rep(c("function1","function2", "function3","function4")) ) ggplot(df,aes(x,values,col=fun))+geom_line(size=3) Output: Let us first change the transparency of all the lines to the same value, for this alpha parameter is used. The maximum value it takes is 1, which makes it a solid line. To make it translucent, provide value(s) smaller than 1. R library("ggplot2") function1<- function(x){x**2} function2<-function(x){x**3} function3<-function(x){x/2} function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4")) ) ggplot(df,aes(x,values,col=fun))+geom_line(size=3, alpha=0.6) Output: To change the transparency to some other value for each line, pass the value to differentiate transparency by the attribute of the dataset and then pass the vector with values for each transparency level to the scale_alpha_manual() function. scale_alpha_manual() sets the values for alpha manually. Syntax: scale_alpha_manual(values) Code: R library("ggplot2") function1<- function(x){x**2} function2<-function(x){x**3} function3<-function(x){x/2} function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4")) ) ggplot(df,aes(x,values,col=fun))+geom_line(size=3, aes(alpha=fun))+ scale_alpha_manual(values=c(0.3,0.2,0.7,1)) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25314, "s": 25283, "text": " \n18 Jul, 2021\n" }, { "code": null, "e": 25458, "s": 25314, "text": "In this article, we will be discussing how can transparency of lines be made different for a line plot using GGPLOT2 in R programming language." }, { "code": null, "e": 25526, "s": 25458, "text": "First, let’s plot a line graph, so that the difference is apparent." }, { "code": null, "e": 25528, "s": 25526, "text": "R" }, { "code": "\n\n\n\n\n\n\nlibrary(\"ggplot2\") \n \n \nfunction1<- function(x){x**2} \nfunction2<-function(x){x**3} \nfunction3<-function(x){x/2} \nfunction4<-function(x){2*(x**3)+(x**2)-(x/2)} \n \ndf=data.frame(x = -2:2, \n values = c(function1(-2:2), \n function2(-2:2), \n function3(-2:2), \n function4(-2:2)), \n fun = rep(c(\"function1\",\"function2\", \n \"function3\",\"function4\")) \n ) \n \nggplot(df,aes(x,values,col=fun))+geom_line(size=3)\n\n\n\n\n\n", "e": 26083, "s": 25538, "text": null }, { "code": null, "e": 26091, "s": 26083, "text": "Output:" }, { "code": null, "e": 26317, "s": 26091, "text": "Let us first change the transparency of all the lines to the same value, for this alpha parameter is used. The maximum value it takes is 1, which makes it a solid line. To make it translucent, provide value(s) smaller than 1." }, { "code": null, "e": 26319, "s": 26317, "text": "R" }, { "code": "\n\n\n\n\n\n\nlibrary(\"ggplot2\") \n \nfunction1<- function(x){x**2} \nfunction2<-function(x){x**3} \nfunction3<-function(x){x/2} \nfunction4<-function(x){2*(x**3)+(x**2)-(x/2)} \n \ndf=data.frame(x=-2:2, \n values=c(function1(-2:2), \n function2(-2:2), \n function3(-2:2), \n function4(-2:2)), \n fun=rep(c(\"function1\",\"function2\", \n \"function3\",\"function4\")) \n) \n \nggplot(df,aes(x,values,col=fun))+geom_line(size=3, alpha=0.6) \n\n\n\n\n\n", "e": 26863, "s": 26329, "text": null }, { "code": null, "e": 26871, "s": 26863, "text": "Output:" }, { "code": null, "e": 27113, "s": 26871, "text": "To change the transparency to some other value for each line, pass the value to differentiate transparency by the attribute of the dataset and then pass the vector with values for each transparency level to the scale_alpha_manual() function." }, { "code": null, "e": 27170, "s": 27113, "text": "scale_alpha_manual() sets the values for alpha manually." }, { "code": null, "e": 27205, "s": 27170, "text": "Syntax: scale_alpha_manual(values)" }, { "code": null, "e": 27211, "s": 27205, "text": "Code:" }, { "code": null, "e": 27213, "s": 27211, "text": "R" }, { "code": "\n\n\n\n\n\n\nlibrary(\"ggplot2\") \n \nfunction1<- function(x){x**2} \nfunction2<-function(x){x**3} \nfunction3<-function(x){x/2} \nfunction4<-function(x){2*(x**3)+(x**2)-(x/2)} \n \ndf=data.frame(x=-2:2, \n values=c(function1(-2:2), \n function2(-2:2), \n function3(-2:2), \n function4(-2:2)), \n fun=rep(c(\"function1\",\"function2\", \n \"function3\",\"function4\")) \n) \n \nggplot(df,aes(x,values,col=fun))+geom_line(size=3, aes(alpha=fun))+ \n scale_alpha_manual(values=c(0.3,0.2,0.7,1)) \n\n\n\n\n\n", "e": 27811, "s": 27223, "text": null }, { "code": null, "e": 27819, "s": 27811, "text": "Output:" }, { "code": null, "e": 27828, "s": 27819, "text": "\nPicked\n" }, { "code": null, "e": 27839, "s": 27828, "text": "\nR-ggplot\n" }, { "code": null, "e": 27852, "s": 27839, "text": "\nR Language\n" }, { "code": null, "e": 28057, "s": 27852, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28109, "s": 28057, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28147, "s": 28109, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28182, "s": 28147, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28240, "s": 28182, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28289, "s": 28240, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28326, "s": 28289, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28376, "s": 28326, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28419, "s": 28376, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28445, "s": 28419, "text": "Time Series Analysis in R" } ]
Difference between YAML(.yml) and .properties file in Java SpringBoot - GeeksforGeeks
30 Jun, 2021 These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properties while developing the applications. If you have ever used Elastic Search instance and MongoDB database, both of these applications use YAML(.yml) as their default configuration format. Example: #.yml file some_key:value some_number:9 some_bool:true Nesting: For nesting, the .yml file support hierarchy using spaces. # .yml file somemap: key:value #use space not tab number:9 #inline format map2: {bool=true, date=2016-01-01} Let’s define a list in such files: YAML as part of its specification supports the list. #.properties file # A List numbers[0] = one numbers[1] = two # Inline List numbers = one, two .properties File: This file extension is used for the configuration application. These are used as the Property Resource Bundles files in technologies like Java, etc. Example: #.properties file some_key = value some_number = 9 some_bool = true Nesting: For nesting, the .properties file support dot(.) notation. The inline format in the .yml file is very similar to JSON #.properties file somemap.key = value somemap.number = 9 map2.bool = true map2.date = 2016-01-01 Let’s define a list in such files: .properties file doesn’t support list but spring uses an array as a convention to define the list in the .properties file. #.yml file numbers: - one # use a dash followed by space - two # Inline List numbers:[one, two] Table of Difference: What should I use .properties or .yml file? Strictly speaking, .yml file is advantageous over .properties file as it has type safety, hierarchy and supports list but if you are using spring, spring has a number of conventions as well as type conversions that allow you to get effectively all of these same features that YAML provides for you. One advantage that you may see out of using the YAML(.yml) file is if you are using more than one application that read the same configuration file. you may see better support in other languages for YAML(.yml) as opposed to .properties. simmytarika5 surinderdawra388 Java-Properties Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference between Process and Thread Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Differences between JDK, JRE and JVM Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24650, "s": 24622, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24864, "s": 24650, "text": "These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. " }, { "code": null, "e": 25040, "s": 24864, "text": "YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properties while developing the applications. " }, { "code": null, "e": 25190, "s": 25040, "text": "If you have ever used Elastic Search instance and MongoDB database, both of these applications use YAML(.yml) as their default configuration format. " }, { "code": null, "e": 25201, "s": 25190, "text": "Example: " }, { "code": null, "e": 25257, "s": 25201, "text": "#.yml file\n\nsome_key:value\nsome_number:9\nsome_bool:true" }, { "code": null, "e": 25327, "s": 25257, "text": "Nesting: For nesting, the .yml file support hierarchy using spaces. " }, { "code": null, "e": 25469, "s": 25327, "text": "# .yml file\n\nsomemap:\n key:value #use space not tab\n number:9\n\n#inline format \n map2: {bool=true, date=2016-01-01}" }, { "code": null, "e": 25559, "s": 25469, "text": "Let’s define a list in such files: YAML as part of its specification supports the list. " }, { "code": null, "e": 25655, "s": 25559, "text": "#.properties file\n\n# A List\nnumbers[0] = one\nnumbers[1] = two\n\n# Inline List\nnumbers = one, two" }, { "code": null, "e": 25823, "s": 25655, "text": ".properties File: This file extension is used for the configuration application. These are used as the Property Resource Bundles files in technologies like Java, etc. " }, { "code": null, "e": 25834, "s": 25823, "text": "Example: " }, { "code": null, "e": 25903, "s": 25834, "text": "#.properties file\n\nsome_key = value\nsome_number = 9\nsome_bool = true" }, { "code": null, "e": 26031, "s": 25903, "text": "Nesting: For nesting, the .properties file support dot(.) notation. The inline format in the .yml file is very similar to JSON " }, { "code": null, "e": 26131, "s": 26031, "text": "#.properties file\n\nsomemap.key = value \nsomemap.number = 9\n\nmap2.bool = true\nmap2.date = 2016-01-01" }, { "code": null, "e": 26291, "s": 26131, "text": "Let’s define a list in such files: .properties file doesn’t support list but spring uses an array as a convention to define the list in the .properties file. " }, { "code": null, "e": 26393, "s": 26291, "text": "#.yml file\n\nnumbers:\n - one # use a dash followed by space\n - two\n\n# Inline List\nnumbers:[one, two]" }, { "code": null, "e": 26416, "s": 26393, "text": "Table of Difference: " }, { "code": null, "e": 26461, "s": 26416, "text": "What should I use .properties or .yml file? " }, { "code": null, "e": 26761, "s": 26461, "text": "Strictly speaking, .yml file is advantageous over .properties file as it has type safety, hierarchy and supports list but if you are using spring, spring has a number of conventions as well as type conversions that allow you to get effectively all of these same features that YAML provides for you. " }, { "code": null, "e": 26999, "s": 26761, "text": "One advantage that you may see out of using the YAML(.yml) file is if you are using more than one application that read the same configuration file. you may see better support in other languages for YAML(.yml) as opposed to .properties. " }, { "code": null, "e": 27012, "s": 26999, "text": "simmytarika5" }, { "code": null, "e": 27029, "s": 27012, "text": "surinderdawra388" }, { "code": null, "e": 27045, "s": 27029, "text": "Java-Properties" }, { "code": null, "e": 27064, "s": 27045, "text": "Difference Between" }, { "code": null, "e": 27069, "s": 27064, "text": "Java" }, { "code": null, "e": 27074, "s": 27069, "text": "Java" }, { "code": null, "e": 27172, "s": 27074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27233, "s": 27172, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27271, "s": 27233, "text": "Difference between Process and Thread" }, { "code": null, "e": 27339, "s": 27271, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27371, "s": 27339, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 27408, "s": 27371, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 27423, "s": 27408, "text": "Arrays in Java" }, { "code": null, "e": 27467, "s": 27423, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27489, "s": 27467, "text": "For-each loop in Java" }, { "code": null, "e": 27525, "s": 27489, "text": "Arrays.sort() in Java with examples" } ]
How to print exception messages in android?
This example demonstrate about How to print exception messages in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout> In the above code, we have taken textview to show exception message. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class MainActivity extends AppCompatActivity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.text); try { int a = 0; int b = 10; int result = b/a; System.out.println(result); } catch(Exception e) { text.setText(e.toString()); e.printStackTrace(); } } } 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": 1137, "s": 1062, "text": "This example demonstrate about How to print exception messages in android." }, { "code": null, "e": 1266, "s": 1137, "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": 1331, "s": 1266, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1905, "s": 1331, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"100dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:gravity=\"center\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\">\n </TextView>\n</LinearLayout>" }, { "code": null, "e": 1974, "s": 1905, "text": "In the above code, we have taken textview to show exception message." }, { "code": null, "e": 2031, "s": 1974, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2893, "s": 2031, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport android.widget.TextView;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.text);\n try {\n int a = 0;\n int b = 10;\n int result = b/a;\n System.out.println(result);\n } catch(Exception e) {\n text.setText(e.toString());\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 3240, "s": 2893, "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": 3280, "s": 3240, "text": "Click here to download the project code" } ]
Power your Windows app with AI: connect C# application with Python model | by Pavlo Horbonos | Towards Data Science
No long intro here:a) we may always run our ML models or neural networks pipelines just in the console;b) there is no reason why we can’t run it on Windows and add some buttons for clicking. Though, here we face a problem. We can easily develop either some Python model or C# Windows Forms application. But their connection may be a real pain in the process of AI-powered application development. That’s why this piece focuses on the solution for the intermediate communication between C# and Python parts of the project. For the project, we will use the loan lending club dataset from Kaggle. Loan lending club dataset is surely well-known data accumulation, so we will skip the code for dataset preparation, cleaning, features selection, analysis, and other staff (since it is not the theme of the article). Check it in the example on my GitHub, if you want. Let’s create a very simple neural network with Keras library and train it to have more or less suitable accuracy: So, we have the 4-layered neural network with a final accuracy of 70%. Really not the best one, but that is enough for our purposes. By the way, we also created dumps of label encoders and scalers from sk-learn. We used a very handy pickle module: from pickle import dumpdump(scaler, open(‘scaler.pkl’, ‘wb’))dump(grade_encoder, open(‘grade_encoder.pkl’, ‘wb’))dump(ownership_encoder, open('ownership_encoder.pkl', 'wb'))dump(purpose_encoder, open('purpose_encoder.pkl', 'wb')) Now our task is: to write the code for model loading and prediction making; wrap this code in a simple class; add the code that receives input parameters in json format; add the code that returns the output in JSON format. So, the first step is the purpose we need the model, the second step is just for convenience. But the last two are intermediate stages for our app-to-model connection: JSON is a really convenient format for exchanging between different layers of the solution. Well, talk is cheap, here is our class: The good part in C# development for Windows Forms is the speed of interface creation: drag and drop few elements, fill some callbacks, check that edit boxes are properly validated, and voila — the primitive app is ready. There is really no reason to show all the code — it is a standard Windows Forms project in Visual Studio 2019. Nevertheless, you can check it in my GitHub. It looks like this: Nothing special, but we can enter the input parameters for our neural network from the previous step and get the result. And here comes the tricky part. So, we need a solution for the intermediate layer with C# to Python communication. It consists of two parts: PythonCaller class in the application and the Python aggregator script. As we see from the names, the C# class collects the arguments which should be passed to the model, gets model name and location, and throughs all that info into the calls aggregator script. And the aggregator script handles all jobs with the connection with the model. Let’s start with the C# part. As we have stated, all the information exchange takes place in json format. That’s why the first thing we need to do is to connect the Newtonsoft JSON parser library. It is free and can be easily added to Visual Studio through the marketplace. After downloading include it into the project: using Newtonsoft.Json; Before the class preparation, we should think about the way of passing input parameters from the GUI part inside the class. Well, since we made a decision to pack the arguments into a JSON object, we will prepare arguments container class. You may know that I am passionate about container design, so you can check my articles about constructing them. So, back to the container: it is a simple wrap around the dictionary, which collects arguments and can return them as a JSON object with some meta-information included. Of course, it will be passed into the caller class itself. Now for the main part. Firstly, every instance of the PythonCaller class will be connected to the concrete model script. Secondly, it will use ProcessStartInfo object to call the aggregator script through the Python interpreter. A previously created JSON object with input parameters will serve as the argument to the aggregator script. Implementation is simple: create an object with a connection to the concrete model class: transfer call of the selected model’s class method (with PythonCallerArgs container prepared, of course) to the aggregator script: You may notice, that we have got control over the in-out stream for the script call. It is the way we get the result from the script. And that is all, the solution is really so simple. We will integrate the class into the application later. The last part of the solution is calls aggregator itself. It is represented as Python script which gets all JSON-packed information from Windows application and contacts the desired AI model script. Implementation is simple — get the parameters from the Windows application and transfer them to the model through a specific method call. There are two trick places here. The first one is to import the model’s class into the script, so we can access the desired method. We will use importlib package for these purposes: it can import the module by the path to the code. The second trick place is to return the result of the call back to the application. But, as you remember, we forced ProcessStartInfo object to get control over the standard output. That’s why we just printed the result into the stream in the last line of the script. The last step is the integration of the designed class into our application: And now we can check the whole application and get the result from the AI module Yes, this solution is not perfect, but tuned once it will connect the power of AI to your application. That’s why you can propose your own working alternatives. And, as always, you can find the whole working example in my GitHub repository:
[ { "code": null, "e": 237, "s": 46, "text": "No long intro here:a) we may always run our ML models or neural networks pipelines just in the console;b) there is no reason why we can’t run it on Windows and add some buttons for clicking." }, { "code": null, "e": 568, "s": 237, "text": "Though, here we face a problem. We can easily develop either some Python model or C# Windows Forms application. But their connection may be a real pain in the process of AI-powered application development. That’s why this piece focuses on the solution for the intermediate communication between C# and Python parts of the project." }, { "code": null, "e": 640, "s": 568, "text": "For the project, we will use the loan lending club dataset from Kaggle." }, { "code": null, "e": 1021, "s": 640, "text": "Loan lending club dataset is surely well-known data accumulation, so we will skip the code for dataset preparation, cleaning, features selection, analysis, and other staff (since it is not the theme of the article). Check it in the example on my GitHub, if you want. Let’s create a very simple neural network with Keras library and train it to have more or less suitable accuracy:" }, { "code": null, "e": 1269, "s": 1021, "text": "So, we have the 4-layered neural network with a final accuracy of 70%. Really not the best one, but that is enough for our purposes. By the way, we also created dumps of label encoders and scalers from sk-learn. We used a very handy pickle module:" }, { "code": null, "e": 1499, "s": 1269, "text": "from pickle import dumpdump(scaler, open(‘scaler.pkl’, ‘wb’))dump(grade_encoder, open(‘grade_encoder.pkl’, ‘wb’))dump(ownership_encoder, open('ownership_encoder.pkl', 'wb'))dump(purpose_encoder, open('purpose_encoder.pkl', 'wb'))" }, { "code": null, "e": 1516, "s": 1499, "text": "Now our task is:" }, { "code": null, "e": 1575, "s": 1516, "text": "to write the code for model loading and prediction making;" }, { "code": null, "e": 1609, "s": 1575, "text": "wrap this code in a simple class;" }, { "code": null, "e": 1669, "s": 1609, "text": "add the code that receives input parameters in json format;" }, { "code": null, "e": 1722, "s": 1669, "text": "add the code that returns the output in JSON format." }, { "code": null, "e": 2022, "s": 1722, "text": "So, the first step is the purpose we need the model, the second step is just for convenience. But the last two are intermediate stages for our app-to-model connection: JSON is a really convenient format for exchanging between different layers of the solution. Well, talk is cheap, here is our class:" }, { "code": null, "e": 2419, "s": 2022, "text": "The good part in C# development for Windows Forms is the speed of interface creation: drag and drop few elements, fill some callbacks, check that edit boxes are properly validated, and voila — the primitive app is ready. There is really no reason to show all the code — it is a standard Windows Forms project in Visual Studio 2019. Nevertheless, you can check it in my GitHub. It looks like this:" }, { "code": null, "e": 2572, "s": 2419, "text": "Nothing special, but we can enter the input parameters for our neural network from the previous step and get the result. And here comes the tricky part." }, { "code": null, "e": 3022, "s": 2572, "text": "So, we need a solution for the intermediate layer with C# to Python communication. It consists of two parts: PythonCaller class in the application and the Python aggregator script. As we see from the names, the C# class collects the arguments which should be passed to the model, gets model name and location, and throughs all that info into the calls aggregator script. And the aggregator script handles all jobs with the connection with the model." }, { "code": null, "e": 3052, "s": 3022, "text": "Let’s start with the C# part." }, { "code": null, "e": 3343, "s": 3052, "text": "As we have stated, all the information exchange takes place in json format. That’s why the first thing we need to do is to connect the Newtonsoft JSON parser library. It is free and can be easily added to Visual Studio through the marketplace. After downloading include it into the project:" }, { "code": null, "e": 3366, "s": 3343, "text": "using Newtonsoft.Json;" }, { "code": null, "e": 3718, "s": 3366, "text": "Before the class preparation, we should think about the way of passing input parameters from the GUI part inside the class. Well, since we made a decision to pack the arguments into a JSON object, we will prepare arguments container class. You may know that I am passionate about container design, so you can check my articles about constructing them." }, { "code": null, "e": 3946, "s": 3718, "text": "So, back to the container: it is a simple wrap around the dictionary, which collects arguments and can return them as a JSON object with some meta-information included. Of course, it will be passed into the caller class itself." }, { "code": null, "e": 4309, "s": 3946, "text": "Now for the main part. Firstly, every instance of the PythonCaller class will be connected to the concrete model script. Secondly, it will use ProcessStartInfo object to call the aggregator script through the Python interpreter. A previously created JSON object with input parameters will serve as the argument to the aggregator script. Implementation is simple:" }, { "code": null, "e": 4373, "s": 4309, "text": "create an object with a connection to the concrete model class:" }, { "code": null, "e": 4504, "s": 4373, "text": "transfer call of the selected model’s class method (with PythonCallerArgs container prepared, of course) to the aggregator script:" }, { "code": null, "e": 4638, "s": 4504, "text": "You may notice, that we have got control over the in-out stream for the script call. It is the way we get the result from the script." }, { "code": null, "e": 4745, "s": 4638, "text": "And that is all, the solution is really so simple. We will integrate the class into the application later." }, { "code": null, "e": 4944, "s": 4745, "text": "The last part of the solution is calls aggregator itself. It is represented as Python script which gets all JSON-packed information from Windows application and contacts the desired AI model script." }, { "code": null, "e": 5314, "s": 4944, "text": "Implementation is simple — get the parameters from the Windows application and transfer them to the model through a specific method call. There are two trick places here. The first one is to import the model’s class into the script, so we can access the desired method. We will use importlib package for these purposes: it can import the module by the path to the code." }, { "code": null, "e": 5581, "s": 5314, "text": "The second trick place is to return the result of the call back to the application. But, as you remember, we forced ProcessStartInfo object to get control over the standard output. That’s why we just printed the result into the stream in the last line of the script." }, { "code": null, "e": 5658, "s": 5581, "text": "The last step is the integration of the designed class into our application:" }, { "code": null, "e": 5739, "s": 5658, "text": "And now we can check the whole application and get the result from the AI module" } ]
Cordova - File System
This plugin is used for manipulating the native file system on the user's device. We need to run the following code in the command prompt to install this plugin. C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file In this example, we will show you how to create file, write to file, read it and delete it. For this reason, we will create four buttons in index.html. We will also add textarea wherein, the content of our file will be shown. <button id = "createFile">CREATE FILE</button> <button id = "writeFile">WRITE FILE</button> <button id = "readFile">READ FILE</button> <button id = "removeFile">DELETE FILE</button> <textarea id = "textarea"></textarea> We will add event listeners in index.js inside the onDeviceReady function to ensure that everything has started before the plugin is used. document.getElementById("createFile").addEventListener("click", createFile); document.getElementById("writeFile").addEventListener("click", writeFile); document.getElementById("readFile").addEventListener("click", readFile); document.getElementById("removeFile").addEventListener("click", removeFile); The file will be created in the apps root folder on the device. To be able to access the root folder you need to provide superuser access to your folders. In our case, the path to root folder is \data\data\com.example.hello\cache. At the moment this folder is empty. Let us now add a function that will create the log.txt file. We will write this code in index.js and send a request to the file system. This method uses WINDOW.TEMPORARY or WINDOW.PERSISTENT. The size that will be required for storage is valued in bytes (5MB in our case). function createFile() { var type = window.TEMPORARY; var size = 5*1024*1024; window.requestFileSystem(type, size, successCallback, errorCallback) function successCallback(fs) { fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) { alert('File creation successfull!') }, errorCallback); } function errorCallback(error) { alert("ERROR: " + error.code) } } Now we can press the CREATE FILE button and the alert will confirm that we successfully created the file. Now, we can check our apps root folder again and we can find our new file there. In this step, we will write some text to our file. We will again send a request to the file system, and then create the file writer to be able to write Lorem Ipsum text that we assigned to the blob variable. function writeFile() { var type = window.TEMPORARY; var size = 5*1024*1024; window.requestFileSystem(type, size, successCallback, errorCallback) function successCallback(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { alert('Write completed.'); }; fileWriter.onerror = function(e) { alert('Write failed: ' + e.toString()); }; var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'}); fileWriter.write(blob); }, errorCallback); }, errorCallback); } function errorCallback(error) { alert("ERROR: " + error.code) } } After pressing the WRITE FILE button, the alert will inform us that the writing is successful as in the following screenshot. Now we can open log.txt and see that Lorem Ipsum is written inside. In this step, we will read the log.txt file and display it in the textarea element. We will send a request to the file system and get the file object, then we are creating reader. When the reader is loaded, we will assign the returned value to textarea. function readFile() { var type = window.TEMPORARY; var size = 5*1024*1024; window.requestFileSystem(type, size, successCallback, errorCallback) function successCallback(fs) { fs.root.getFile('log.txt', {}, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onloadend = function(e) { var txtArea = document.getElementById('textarea'); txtArea.value = this.result; }; reader.readAsText(file); }, errorCallback); }, errorCallback); } function errorCallback(error) { alert("ERROR: " + error.code) } } When we click the READ FILE button, the text from the file will be written inside textarea. And finally we will create function for deleting log.txt file. function removeFile() { var type = window.TEMPORARY; var size = 5*1024*1024; window.requestFileSystem(type, size, successCallback, errorCallback) function successCallback(fs) { fs.root.getFile('log.txt', {create: false}, function(fileEntry) { fileEntry.remove(function() { alert('File removed.'); }, errorCallback); }, errorCallback); } function errorCallback(error) { alert("ERROR: " + error.code) } } We can now press the DELETE FILE button to remove the file from the apps root folder. The alert will notify us that the delete operation is successful. If we check the apps root folder, we will see that it is empty. 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2262, "s": 2180, "text": "This plugin is used for manipulating the native file system on the user's device." }, { "code": null, "e": 2342, "s": 2262, "text": "We need to run the following code in the command prompt to install this plugin." }, { "code": null, "e": 2423, "s": 2342, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-file\n" }, { "code": null, "e": 2649, "s": 2423, "text": "In this example, we will show you how to create file, write to file, read it and delete it. For this reason, we will create four buttons in index.html. We will also add textarea wherein, the content of our file will be shown." }, { "code": null, "e": 2869, "s": 2649, "text": "<button id = \"createFile\">CREATE FILE</button>\n<button id = \"writeFile\">WRITE FILE</button>\n<button id = \"readFile\">READ FILE</button>\n<button id = \"removeFile\">DELETE FILE</button>\n<textarea id = \"textarea\"></textarea>" }, { "code": null, "e": 3008, "s": 2869, "text": "We will add event listeners in index.js inside the onDeviceReady function to ensure that everything has started before the plugin is used." }, { "code": null, "e": 3310, "s": 3008, "text": "document.getElementById(\"createFile\").addEventListener(\"click\", createFile);\ndocument.getElementById(\"writeFile\").addEventListener(\"click\", writeFile);\ndocument.getElementById(\"readFile\").addEventListener(\"click\", readFile);\ndocument.getElementById(\"removeFile\").addEventListener(\"click\", removeFile);" }, { "code": null, "e": 3577, "s": 3310, "text": "The file will be created in the apps root folder on the device. To be able to access the root folder you need to provide superuser access to your folders. In our case, the path to root folder is \\data\\data\\com.example.hello\\cache. At the moment this folder is empty." }, { "code": null, "e": 3850, "s": 3577, "text": "Let us now add a function that will create the log.txt file. We will write this code in index.js and send a request to the file system. This method uses WINDOW.TEMPORARY or WINDOW.PERSISTENT. The size that will be required for storage is valued in bytes (5MB in our case)." }, { "code": null, "e": 4284, "s": 3850, "text": "function createFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {\n alert('File creation successfull!')\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n\t\n}" }, { "code": null, "e": 4390, "s": 4284, "text": "Now we can press the CREATE FILE button and the alert will confirm that we successfully created the file." }, { "code": null, "e": 4471, "s": 4390, "text": "Now, we can check our apps root folder again and we can find our new file there." }, { "code": null, "e": 4679, "s": 4471, "text": "In this step, we will write some text to our file. We will again send a request to the file system, and then create the file writer to be able to write Lorem Ipsum text that we assigned to the blob variable." }, { "code": null, "e": 5466, "s": 4679, "text": "function writeFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: true}, function(fileEntry) {\n\n fileEntry.createWriter(function(fileWriter) {\n fileWriter.onwriteend = function(e) {\n alert('Write completed.');\n };\n\n fileWriter.onerror = function(e) {\n alert('Write failed: ' + e.toString());\n };\n\n var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});\n fileWriter.write(blob);\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}" }, { "code": null, "e": 5592, "s": 5466, "text": "After pressing the WRITE FILE button, the alert will inform us that the writing is successful as in the following screenshot." }, { "code": null, "e": 5660, "s": 5592, "text": "Now we can open log.txt and see that Lorem Ipsum is written inside." }, { "code": null, "e": 5914, "s": 5660, "text": "In this step, we will read the log.txt file and display it in the textarea element. We will send a request to the file system and get the file object, then we are creating reader. When the reader is loaded, we will assign the returned value to textarea." }, { "code": null, "e": 6592, "s": 5914, "text": "function readFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {}, function(fileEntry) {\n\n fileEntry.file(function(file) {\n var reader = new FileReader();\n\n reader.onloadend = function(e) {\n var txtArea = document.getElementById('textarea');\n txtArea.value = this.result;\n };\n reader.readAsText(file);\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}\t" }, { "code": null, "e": 6684, "s": 6592, "text": "When we click the READ FILE button, the text from the file will be written inside textarea." }, { "code": null, "e": 6747, "s": 6684, "text": "And finally we will create function for deleting log.txt file." }, { "code": null, "e": 7223, "s": 6747, "text": "function removeFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: false}, function(fileEntry) {\n\n fileEntry.remove(function() {\n alert('File removed.');\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}\t" }, { "code": null, "e": 7375, "s": 7223, "text": "We can now press the DELETE FILE button to remove the file from the apps root folder. The alert will notify us that the delete operation is successful." }, { "code": null, "e": 7439, "s": 7375, "text": "If we check the apps root folder, we will see that it is empty." }, { "code": null, "e": 7472, "s": 7439, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 7492, "s": 7472, "text": " Skillbakerystudios" }, { "code": null, "e": 7525, "s": 7492, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7538, "s": 7525, "text": " Nilay Mehta" }, { "code": null, "e": 7545, "s": 7538, "text": " Print" }, { "code": null, "e": 7556, "s": 7545, "text": " Add Notes" } ]
GraphQL - Schema
A GraphQL schema is at the core of any GraphQL server implementation. It describes the functionality available to the client applications that connect to it. We can use any programming language to create a GraphQL schema and build an interface around it. The GraphQL runtime defines a generic graph-based schema to publish the capabilities of the data service it represents. Client applications can query the schema within its capabilities. This approach decouples clients from servers and allows both to evolve and scale independently. In this chapter, we use Apollo server to execute GraphQL queries. The makeExecutableSchema function in graphql-tools helps you to bind schema and resolvers. The makeExecutableSchema function takes a single argument {} of Object type. The syntax for using this function is given below − import { makeExecutableSchema } from 'graphql-tools'; const jsSchema = makeExecutableSchema({ typeDefs, resolvers, // optional logger, // optional allowUndefinedInResolve = false, // optional resolverValidationOptions = {}, // optional directiveResolvers = null, // optional schemaDirectives = null, // optional parseOptions = {}, // optional inheritResolversFromInterfaces = false // optional }); typeDefs This is a required argument. It represents a GraphQL query as a UTF-8 string. Resolvers This is an optional argument (empty object by default). This has functions that handle the query. logger This is an optional argument and can be used to print errors to the server console. parseOptions This is an optional argument and allows customization of parse when specifying typeDefs as a string. allowUndefinedInResolve This is true by default. When set to false, causes your resolve functions to throw errors if they return undefined. resolverValidationOptions This is an optional argument and accepts an object with Boolean properties. inheritResolversFromInterfaces This is an optional argument and accepts a Boolean argument to check resolvers object inheritance. Let us create a simple application to understand this schema. This will create a schema for querying list of students from the server. The student data will be stored in a flat file and we will use a node module called notarealdb to fake a database and read from the flat file. Create a folder named schema-app. Change your directory to schema-app from the terminal. Then, follow steps 3 to 5 explained in the Environment Setup chapter to complete the download and the installation process. Add schema.graphql file in the project folder, schema-app and add the following code − type Query { greeting:String students:[Student] } type Student { id:ID! firstName:String lastName:String password:String collegeId:String } The root of the schema will be Query type. The query has two fields − greeting and Students that returns String and a list of students respectively. Student is declared as an Object type since it contains multiple fields. The ID field is declared as non-nullable. Create a file resolvers.js in the project folder and add the following code − const db = require('./db') const Query = { greeting:() => { return "hello from TutorialsPoint !!!" }, students:() => db.students.list() } module.exports = {Query} Here greeting and students are the resolvers that handle the query. students resolver function returns a list of students from the data access layer. To access resolver functions outside the module, Query object has to be exported using module.exports. Create a server.js file and refer step 8 in the Environment Setup Chapter. The next step is to execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL, http://localhost:9000/graphiql. Type the following query in the editor − { greeting students { id firstName lastName } } The query will display the output as shown below − Note − We can replace the students.json with a RESTful API call to retrieve student data or even a real database like MySQL or MongoDB. GraphQL becomes a thin wrapper around your original application layer to improve performance. 43 Lectures 3 hours Nilay Mehta 53 Lectures 3 hours Asfend Yar 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2206, "s": 1951, "text": "A GraphQL schema is at the core of any GraphQL server implementation. It describes the functionality available to the client applications that connect to it. We can use any programming language to create a GraphQL schema and build an interface around it." }, { "code": null, "e": 2488, "s": 2206, "text": "The GraphQL runtime defines a generic graph-based schema to publish the capabilities of the data service it represents. Client applications can query the schema within its capabilities. This approach decouples clients from servers and allows both to evolve and scale independently." }, { "code": null, "e": 2645, "s": 2488, "text": "In this chapter, we use Apollo server to execute GraphQL queries. The makeExecutableSchema function in graphql-tools helps you to bind schema and resolvers." }, { "code": null, "e": 2774, "s": 2645, "text": "The makeExecutableSchema function takes a single argument {} of Object type. The syntax for using this function is given below −" }, { "code": null, "e": 3205, "s": 2774, "text": "import { makeExecutableSchema } from 'graphql-tools';\n\nconst jsSchema = makeExecutableSchema({\n typeDefs,\n resolvers, // optional\n logger, // optional\n allowUndefinedInResolve = false, // optional\n resolverValidationOptions = {}, // optional\n directiveResolvers = null, // optional\n schemaDirectives = null, // optional\n parseOptions = {}, // optional\n inheritResolversFromInterfaces = false // optional\n});\t\n" }, { "code": null, "e": 3214, "s": 3205, "text": "typeDefs" }, { "code": null, "e": 3292, "s": 3214, "text": "This is a required argument. It represents a GraphQL query as a UTF-8 string." }, { "code": null, "e": 3302, "s": 3292, "text": "Resolvers" }, { "code": null, "e": 3400, "s": 3302, "text": "This is an optional argument (empty object by default). This has functions that handle the query." }, { "code": null, "e": 3407, "s": 3400, "text": "logger" }, { "code": null, "e": 3491, "s": 3407, "text": "This is an optional argument and can be used to print errors to the server console." }, { "code": null, "e": 3504, "s": 3491, "text": "parseOptions" }, { "code": null, "e": 3605, "s": 3504, "text": "This is an optional argument and allows customization of parse when specifying typeDefs as a string." }, { "code": null, "e": 3629, "s": 3605, "text": "allowUndefinedInResolve" }, { "code": null, "e": 3745, "s": 3629, "text": "This is true by default. When set to false, causes your resolve functions to throw errors if they return undefined." }, { "code": null, "e": 3771, "s": 3745, "text": "resolverValidationOptions" }, { "code": null, "e": 3847, "s": 3771, "text": "This is an optional argument and accepts an object with Boolean properties." }, { "code": null, "e": 3878, "s": 3847, "text": "inheritResolversFromInterfaces" }, { "code": null, "e": 3977, "s": 3878, "text": "This is an optional argument and accepts a Boolean argument to check resolvers object inheritance." }, { "code": null, "e": 4255, "s": 3977, "text": "Let us create a simple application to understand this schema. This will create a schema for querying list of students from the server. The student data will be stored in a flat file and we will use a node module called notarealdb to fake a database and read from the flat file." }, { "code": null, "e": 4468, "s": 4255, "text": "Create a folder named schema-app. Change your directory to schema-app from the terminal. Then, follow steps 3 to 5 explained in the Environment Setup chapter to complete the download and the installation process." }, { "code": null, "e": 4555, "s": 4468, "text": "Add schema.graphql file in the project folder, schema-app and add the following code −" }, { "code": null, "e": 4717, "s": 4555, "text": "type Query {\n greeting:String\n students:[Student]\n}\n\ntype Student {\n id:ID!\n firstName:String\n lastName:String\n password:String\n collegeId:String\n}" }, { "code": null, "e": 4981, "s": 4717, "text": "The root of the schema will be Query type. The query has two fields − greeting and Students that returns String and a list of students respectively. Student is declared as an Object type since it contains multiple fields. The ID field is declared as non-nullable." }, { "code": null, "e": 5059, "s": 4981, "text": "Create a file resolvers.js in the project folder and add the following code −" }, { "code": null, "e": 5239, "s": 5059, "text": "const db = require('./db')\nconst Query = {\n greeting:() => {\n return \"hello from TutorialsPoint !!!\"\n },\n students:() => db.students.list()\n}\n\nmodule.exports = {Query}" }, { "code": null, "e": 5492, "s": 5239, "text": "Here greeting and students are the resolvers that handle the query. students resolver function returns a list of students from the data access layer. To access resolver functions outside the module, Query object has to be exported using module.exports." }, { "code": null, "e": 5804, "s": 5492, "text": "Create a server.js file and refer step 8 in the Environment Setup Chapter. The next step is to execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL, http://localhost:9000/graphiql." }, { "code": null, "e": 5845, "s": 5804, "text": "Type the following query in the editor −" }, { "code": null, "e": 5920, "s": 5845, "text": "{\n greeting\n students {\n id\n firstName\n lastName\n }\n}" }, { "code": null, "e": 5971, "s": 5920, "text": "The query will display the output as shown below −" }, { "code": null, "e": 6201, "s": 5971, "text": "Note − We can replace the students.json with a RESTful API call to retrieve student data or even a real database like MySQL or MongoDB. GraphQL becomes a thin wrapper around your original application layer to improve performance." }, { "code": null, "e": 6234, "s": 6201, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 6247, "s": 6234, "text": " Nilay Mehta" }, { "code": null, "e": 6280, "s": 6247, "text": "\n 53 Lectures \n 3 hours \n" }, { "code": null, "e": 6292, "s": 6280, "text": " Asfend Yar" }, { "code": null, "e": 6325, "s": 6292, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6343, "s": 6325, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 6350, "s": 6343, "text": " Print" }, { "code": null, "e": 6361, "s": 6350, "text": " Add Notes" } ]
Create Certificates using Python-PIL - GeeksforGeeks
26 May, 2020 Prerequisites: Python: Pillow (a fork of PIL) Well if you have ever done something like creating certificates for participants of any event, then you know how tedious process it is. Let’s automate that using Python. We will be using the Pillow module of Python. To install that simply type the following in your terminal pip install Pillow You also need the design of the certificate as an image format (preferably png). You can use something like Microsoft Office Publisher to create the certificates and export them as png. Keep some extra space for entering the name. Below is the template certificate we will be using. Template Certificate: So, our certificate template is ready. Now, we need to find a suitable font for writing the name on it. You need the path to the font file (TTF file). If you are using Windows 10, then simply search for Fonts in windows search, it will show you results of Fonts settings. Head over there and you should see something similar to the following screen. Now, choose the font you like from here and click on it. You will see a path to that font. Note down the path somewhere. You will need it in your code. Below is the implementation. # importsfrom PIL import Image, ImageDraw, ImageFont def coupons(names: list, certificate: str, font_path: str): for name in names: # adjust the position according to # your sample text_y_position = 900 # opens the image img = Image.open(certificate, mode ='r') # gets the image width image_width = img.width # gets the image height image_height = img.height # creates a drawing canvas overlay # on top of the image draw = ImageDraw.Draw(img) # gets the font object from the # font file (TTF) font = ImageFont.truetype( font_path, 200 # change this according to your needs ) # fetches the text width for # calculations later on text_width, _ = draw.textsize(name, font = font) draw.text( ( # this calculation is done # to centre the image (image_width - text_width) / 2, text_y_position ), name, font = font ) # saves the image in png format img.save("{}.png".format(name)) # Driver Codeif __name__ == "__main__": # some example of names NAMES = ['Frank Muller', 'Mathew Frankfurt', 'Cristopher Greman', 'Natelie Wemberg', 'John Ken'] # path to font FONT = "/path / to / font / ITCEDSCR.ttf" # path to sample certificate CERTIFICATE = "path / to / Certificate.png" coupons(NAMES, CERTIFICATE, FONT) Output: Add the names to the NAMES list. Then change the font path and path to the certificate template according to your system. Then run the above code and all your certificates should be ready. This is a pretty effective solution for automating the process of creating certificates for a large number of participants. This can be very effective for event organizers. Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24648, "s": 24620, "text": "\n26 May, 2020" }, { "code": null, "e": 24694, "s": 24648, "text": "Prerequisites: Python: Pillow (a fork of PIL)" }, { "code": null, "e": 24969, "s": 24694, "text": "Well if you have ever done something like creating certificates for participants of any event, then you know how tedious process it is. Let’s automate that using Python. We will be using the Pillow module of Python. To install that simply type the following in your terminal" }, { "code": null, "e": 24988, "s": 24969, "text": "pip install Pillow" }, { "code": null, "e": 25271, "s": 24988, "text": "You also need the design of the certificate as an image format (preferably png). You can use something like Microsoft Office Publisher to create the certificates and export them as png. Keep some extra space for entering the name. Below is the template certificate we will be using." }, { "code": null, "e": 25293, "s": 25271, "text": "Template Certificate:" }, { "code": null, "e": 25643, "s": 25293, "text": "So, our certificate template is ready. Now, we need to find a suitable font for writing the name on it. You need the path to the font file (TTF file). If you are using Windows 10, then simply search for Fonts in windows search, it will show you results of Fonts settings. Head over there and you should see something similar to the following screen." }, { "code": null, "e": 25795, "s": 25643, "text": "Now, choose the font you like from here and click on it. You will see a path to that font. Note down the path somewhere. You will need it in your code." }, { "code": null, "e": 25824, "s": 25795, "text": "Below is the implementation." }, { "code": "# importsfrom PIL import Image, ImageDraw, ImageFont def coupons(names: list, certificate: str, font_path: str): for name in names: # adjust the position according to # your sample text_y_position = 900 # opens the image img = Image.open(certificate, mode ='r') # gets the image width image_width = img.width # gets the image height image_height = img.height # creates a drawing canvas overlay # on top of the image draw = ImageDraw.Draw(img) # gets the font object from the # font file (TTF) font = ImageFont.truetype( font_path, 200 # change this according to your needs ) # fetches the text width for # calculations later on text_width, _ = draw.textsize(name, font = font) draw.text( ( # this calculation is done # to centre the image (image_width - text_width) / 2, text_y_position ), name, font = font ) # saves the image in png format img.save(\"{}.png\".format(name)) # Driver Codeif __name__ == \"__main__\": # some example of names NAMES = ['Frank Muller', 'Mathew Frankfurt', 'Cristopher Greman', 'Natelie Wemberg', 'John Ken'] # path to font FONT = \"/path / to / font / ITCEDSCR.ttf\" # path to sample certificate CERTIFICATE = \"path / to / Certificate.png\" coupons(NAMES, CERTIFICATE, FONT)", "e": 27464, "s": 25824, "text": null }, { "code": null, "e": 27472, "s": 27464, "text": "Output:" }, { "code": null, "e": 27834, "s": 27472, "text": "Add the names to the NAMES list. Then change the font path and path to the certificate template according to your system. Then run the above code and all your certificates should be ready. This is a pretty effective solution for automating the process of creating certificates for a large number of participants. This can be very effective for event organizers." }, { "code": null, "e": 27845, "s": 27834, "text": "Python-pil" }, { "code": null, "e": 27852, "s": 27845, "text": "Python" }, { "code": null, "e": 27950, "s": 27852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27968, "s": 27950, "text": "Python Dictionary" }, { "code": null, "e": 28003, "s": 27968, "text": "Read a file line by line in Python" }, { "code": null, "e": 28025, "s": 28003, "text": "Enumerate() in Python" }, { "code": null, "e": 28057, "s": 28025, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28087, "s": 28057, "text": "Iterate over a list in Python" }, { "code": null, "e": 28129, "s": 28087, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28155, "s": 28129, "text": "Python String | replace()" }, { "code": null, "e": 28198, "s": 28155, "text": "Python program to convert a list to string" }, { "code": null, "e": 28235, "s": 28198, "text": "Create a Pandas DataFrame from Lists" } ]
RequireJS - Defining Function
The define() function can be used to load the modules (module can be an object, function, class or a code which is executed after loading a module). You can load different versions of the same module in the same page. The different versions can be analyzed in the same order, even if they are loaded in a different order. define(['module1', 'module2'], function (module1, module2) { //define the module value by returning a value return function () {}; }); You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module. These modules can be passed as parameters of the definition function. The following example shows the usage of the define() function while loading the modules. Create an html file with the name index.html and place the following code in it − <!DOCTYPE html> <html> <head> <title>Define() Function</title> <script data-main = "main" src = "require.js"></script> </head> <body> <h2>RequireJS Define() Function Example</h2> </body> </html> Create a js file with the name main.js and add the following code in it − define(function (require) { var myteam = require("./team"); var mylogger = require("./player"); alert("Player Name : " + myteam.player); mylogger.myfunc(); }); Now, create two more js files with the names team.js and player.js and place the following code respectively − define({ player: "Sachin Tendulkar", team : "India" }); define(function (require) { var myteam = require("./team"); return { myfunc: function () { document.write("Name: " + myteam.player + ", Country: " + myteam.team); } }; }); Open the HTML file in a browser; you will receive an output as in the following screenshot − Click on the "OK" button, you will get another output from modules − Print Add Notes Bookmark this page
[ { "code": null, "e": 2164, "s": 1842, "text": "The define() function can be used to load the modules (module can be an object, function, class or a code which is executed after loading a module). You can load different versions of the same module in the same page. The different versions can be analyzed in the same order, even if they are loaded in a different order." }, { "code": null, "e": 2306, "s": 2164, "text": "define(['module1', 'module2'], function (module1, module2) {\n //define the module value by returning a value\n return function () {};\n});\n" }, { "code": null, "e": 2518, "s": 2306, "text": "You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module. These modules can be passed as parameters of the definition function." }, { "code": null, "e": 2690, "s": 2518, "text": "The following example shows the usage of the define() function while loading the modules. Create an html file with the name index.html and place the following code in it −" }, { "code": null, "e": 2919, "s": 2690, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Define() Function</title>\n <script data-main = \"main\" src = \"require.js\"></script>\n </head>\n \n <body>\n <h2>RequireJS Define() Function Example</h2>\n </body>\n</html>" }, { "code": null, "e": 2993, "s": 2919, "text": "Create a js file with the name main.js and add the following code in it −" }, { "code": null, "e": 3165, "s": 2993, "text": "define(function (require) {\n var myteam = require(\"./team\");\n var mylogger = require(\"./player\");\n alert(\"Player Name : \" + myteam.player);\n mylogger.myfunc();\n});" }, { "code": null, "e": 3276, "s": 3165, "text": "Now, create two more js files with the names team.js and player.js and place the following code respectively −" }, { "code": null, "e": 3338, "s": 3276, "text": "define({\n player: \"Sachin Tendulkar\",\n team : \"India\"\n});" }, { "code": null, "e": 3541, "s": 3338, "text": "define(function (require) {\n var myteam = require(\"./team\");\n\n return {\n myfunc: function () {\n document.write(\"Name: \" + myteam.player + \", Country: \" + myteam.team);\n }\n };\n});" }, { "code": null, "e": 3634, "s": 3541, "text": "Open the HTML file in a browser; you will receive an output as in the following screenshot −" }, { "code": null, "e": 3703, "s": 3634, "text": "Click on the \"OK\" button, you will get another output from modules −" }, { "code": null, "e": 3710, "s": 3703, "text": " Print" }, { "code": null, "e": 3721, "s": 3710, "text": " Add Notes" } ]
Python Program to Reverse a String Using Recursion
When it is required to reverse a string using recursion technique, a user defined method is used along with recursion. The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem. Below is a demonstration for the same − Live Demo def reverse_string(my_string): if len(my_string) == 0: return my_string else: return reverse_string(my_string[1:]) + my_string[0] my_str = str(input("Enter the string that needs to be reversed : ")) print("The string is :") print(my_str) print("The reversed string is :") print(reverse_string(my_str)) Enter the string that needs to be reversed : Williw The string is : Williw The reversed string is : williW A method named ‘reverse_string’ is defined, that takes a string as a parameter. It checks the length of the string, and if it is not 0, then, the function is called again on all elements except the first element of the string, and the first element of the string is concatenated to the result of this fuction call. Outside the function, the user is asked to enter a string as input. The string is displayed on the console. The recursion function is called by passing this string as a parameter. It is displayed on the console as the output.
[ { "code": null, "e": 1181, "s": 1062, "text": "When it is required to reverse a string using recursion technique, a user defined method is used along with recursion." }, { "code": null, "e": 1316, "s": 1181, "text": "The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem." }, { "code": null, "e": 1356, "s": 1316, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1367, "s": 1356, "text": " Live Demo" }, { "code": null, "e": 1687, "s": 1367, "text": "def reverse_string(my_string):\n if len(my_string) == 0:\n return my_string\n else:\n return reverse_string(my_string[1:]) + my_string[0]\nmy_str = str(input(\"Enter the string that needs to be reversed : \"))\nprint(\"The string is :\")\nprint(my_str)\nprint(\"The reversed string is :\")\nprint(reverse_string(my_str))" }, { "code": null, "e": 1794, "s": 1687, "text": "Enter the string that needs to be reversed : Williw\nThe string is :\nWilliw\nThe reversed string is :\nwilliW" }, { "code": null, "e": 1874, "s": 1794, "text": "A method named ‘reverse_string’ is defined, that takes a string as a parameter." }, { "code": null, "e": 2109, "s": 1874, "text": "It checks the length of the string, and if it is not 0, then, the function is called again on all elements except the first element of the string, and the first element of the string is concatenated to the result of this fuction call." }, { "code": null, "e": 2177, "s": 2109, "text": "Outside the function, the user is asked to enter a string as input." }, { "code": null, "e": 2217, "s": 2177, "text": "The string is displayed on the console." }, { "code": null, "e": 2289, "s": 2217, "text": "The recursion function is called by passing this string as a parameter." }, { "code": null, "e": 2335, "s": 2289, "text": "It is displayed on the console as the output." } ]
Find the Number of Unique Pairs in an Array using C++
We require the appropriate knowledge to create several unique pairs in an array syntax in C++. In finding the number of unique pairs, we count all unique pairs in a given array, i.e., all possible pairs can be formed where each pair should be unique. For example − Input : array[ ] = { 5, 5, 9 } Output : 4 Explanation : The number of all unique pairs are (5, 5), (5, 9), (9, 5) and (9, 9). Input : array[ ] = { 5, 4, 3, 2, 2 } Output : 16 There are Two Approaches for this Solution and they are − In this approach, we will traverse through each possible pair, add those pairs to a set, and finally find out the size of the set. The time complexity of this approach is O(n2 log n). #include <bits/stdc++.h> using namespace std; int main () { int arr[] = { 5, 4, 3, 2, 2 }; int n = sizeof (arr) / sizeof (arr[0]); // declaring set to store pairs. set < pair < int, int >>set_of_pairs; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) set_of_pairs.insert (make_pair (arr[i], arr[j])); int result = set_of_pairs.size(); cout <<"Number of unique pairs : " << result; return 0; } Number of unique pairs : 16 In this code, first, we declare a set variable, and then, using two loops, we are traversing through each possible pair and inserting each pair in the set using i and j. Then we are calculating the size of the set and printing the result. Another approach is to first find out the number of unique numbers in an array; now, every other unique element, including itself, may create a pair with any other unique element, so the number of unique pairs equals the square of the number of all unique numbers. The time complexity of his approach is O(n). #include <bits/stdc++.h> using namespace std; int main () { int arr[] = { 5, 4, 3, 2, 2 }; int n = sizeof (arr) / sizeof (arr[0]); // declaring set to store unique elements. unordered_set < int >set_of_elements; // inserting elements in the set. for (int i = 0; i < n; i++) set_of_elements.insert (arr[i]); int size = set_of_elements.size (); // finding number of unique pairs int result = size * size; cout << "Number of unique pairs in an array: " << result; return 0; } Number of unique pairs : 16 In this code, we declare a set and then go through each element of the array inserting every element in the set. After that, we calculated the size of the set and found the result from formula n2, and printed the output. In this article, we solve the problem of finding the number of unique pairs in an array where we discuss two ways to solve the problem, i.e., simple and efficient. In a simple approach, we insert all possible pairs in a set with time complexity of O(n2 log n), and in an efficient approach, we find all unique numbers and find the result with n2. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.
[ { "code": null, "e": 1327, "s": 1062, "text": "We require the appropriate knowledge to create several unique pairs in an array syntax in C++. In finding the number of unique pairs, we count all unique pairs in a given array, i.e., all possible pairs can be formed where each pair should be unique. For example −" }, { "code": null, "e": 1503, "s": 1327, "text": "Input : array[ ] = { 5, 5, 9 }\nOutput : 4\nExplanation : The number of all unique pairs are (5, 5), (5, 9), (9, 5) and (9, 9).\n\nInput : array[ ] = { 5, 4, 3, 2, 2 }\nOutput : 16" }, { "code": null, "e": 1561, "s": 1503, "text": "There are Two Approaches for this Solution and they are −" }, { "code": null, "e": 1745, "s": 1561, "text": "In this approach, we will traverse through each possible pair, add those pairs to a set, and finally find out the size of the set. The time complexity of this approach is O(n2 log n)." }, { "code": null, "e": 2187, "s": 1745, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main () {\n int arr[] = { 5, 4, 3, 2, 2 };\n int n = sizeof (arr) / sizeof (arr[0]);\n // declaring set to store pairs.\n set < pair < int, int >>set_of_pairs;\n\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n set_of_pairs.insert (make_pair (arr[i], arr[j]));\n\n int result = set_of_pairs.size();\n\n cout <<\"Number of unique pairs : \" << result;\n return 0;\n}" }, { "code": null, "e": 2215, "s": 2187, "text": "Number of unique pairs : 16" }, { "code": null, "e": 2454, "s": 2215, "text": "In this code, first, we declare a set variable, and then, using two loops, we are traversing through each possible pair and inserting each pair in the set using i and j. Then we are calculating the size of the set and printing the result." }, { "code": null, "e": 2764, "s": 2454, "text": "Another approach is to first find out the number of unique numbers in an array; now, every other unique element, including itself, may create a pair with any other unique element, so the number of unique pairs equals the square of the number of all unique numbers. The time complexity of his approach is O(n)." }, { "code": null, "e": 3281, "s": 2764, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main () {\n int arr[] = { 5, 4, 3, 2, 2 };\n int n = sizeof (arr) / sizeof (arr[0]);\n\n // declaring set to store unique elements.\n\n unordered_set < int >set_of_elements;\n // inserting elements in the set.\n for (int i = 0; i < n; i++)\n set_of_elements.insert (arr[i]);\n\n int size = set_of_elements.size ();\n // finding number of unique pairs\n int result = size * size;\n\n cout << \"Number of unique pairs in an array: \" << result;\n return 0;\n}" }, { "code": null, "e": 3309, "s": 3281, "text": "Number of unique pairs : 16" }, { "code": null, "e": 3530, "s": 3309, "text": "In this code, we declare a set and then go through each element of the array inserting every element in the set. After that, we calculated the size of the set and found the result from formula n2, and printed the output." }, { "code": null, "e": 4008, "s": 3530, "text": "In this article, we solve the problem of finding the number of unique pairs in an array where we discuss two ways to solve the problem, i.e., simple and efficient. In a simple approach, we insert all possible pairs in a set with time complexity of O(n2 log n), and in an efficient approach, we find all unique numbers and find the result with n2. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful." } ]
Grav - Forms
You can create a form using the form plugin available in this link. Search for the form plugin and install it in your Grav folder. You can also install this plugin using the command $ bin/gpm install Form. Navigate to your root folder of Grav and type this command. It will automatically download the form plugin and install the necessary dependencies. You can create a simple form which can be defined in the page YAML frontmatter. The following is an example of a form − --- title: Contact Form form: name: contact fields: - name: name label: Name placeholder: Enter your name autofocus: on autocomplete: on type: text validate: required: true - name: email label: Email placeholder: Enter your email address type: email validate: required: true - name: message label: Message placeholder: Enter your message type: textarea validate: required: true - name: g-recaptcha-response label: Captcha type: captcha recatpcha_site_key: 6LelOg4TAAAAALAt1CjjjVMxFLKY8rrnednYVbr8 recaptcha_not_validated: 'Captcha not valid!' validate: required: true buttons: - type: submit value: Submit - type: reset value: Reset process: - email: subject: "[Site Contact Form] {{ form.value.name|e }}" body: "{% include 'forms/data.html.twig' %}" - save: fileprefix: contact- dateformat: Ymd-His-u extension: txt body: "{% include 'forms/data.txt.twig' %}" - message: Thank you for getting in touch! - display: thankyou --- The above code shows simple form page with name, email, message and Captcha fields. When you submit the information after filling the form, the form will process by adding process field to the YAML frontmatter as shown in the code. The process field uses the following information − The email option uses two fields such as from field specify sender of the email and to field specify receiver of the mail. The email option uses two fields such as from field specify sender of the email and to field specify receiver of the mail. The subject uses [feedback][entered mail] option in which email is sent to the entered email. The subject uses [feedback][entered mail] option in which email is sent to the entered email. The body of the email is specified in the forms/data.html.twig file which is present in the theme folder. The body of the email is specified in the forms/data.html.twig file which is present in the theme folder. The form input data is stored under the user/data folder. The template is defined in the forms/data.txt.twig file which is present in the theme folder. The form input data is stored under the user/data folder. The template is defined in the forms/data.txt.twig file which is present in the theme folder. Create a subpage under the thankyou/ sub folder which will be redirected to that page when a user submits the form. Create a subpage under the thankyou/ sub folder which will be redirected to that page when a user submits the form. You can use some fields with the form plugin as shown in the following table − Captcha It is an antispam field which is used in computing to determine whether or not the user is human. Checkbox It displays a simple checkbox. Checkboxes It displays multiple checkboxes. Date and Datetime Both fields are used to display date and date along with time respectively. Email It is an email field with validation. Hidden It specifies the hidden field. Password It specifies the password field. Radio It displays the simple radio buttons. Select It provides select field. Spacer It allows to add title, text or horizontal line to the form. Text It displays simple text field. Textarea It displays simple text area field. Display It displays the text or instruction field, not the input field. Every field accepts the following parameters which can be used to customize the appearance in the form. label It defines the label field. validate.required It makes the element required. validate.pattern It specifies validation pattern. validate.message It display the message when validation fails. type It defines the field type. default It defines the default field type. size It displays the field size such as large, x-small, medium, long, small. name It defines the field name. classes It uses string with css classes. id It defines the field id. style It specifies the style of the field. title It defines the title of the field. disabled It determines whether or not the field is in a disabled state. placeholder It is a short hint which is displayed in the input field before the user enters a value. autofocus It specifies that an input element should automatically get focus when the page loads. novalidate It specifies that form data should not be validated when submitted. readonly It determines field as read only state. autocomplete It displays the options in the field when user starts typing in the field and displays the values based on earlier typed values. Some of the fields contains specific parameters such as − date and datetime These fields use validate.min and validate.max to set minimum and maximum values. spacer It uses underline to add <hr> tag, adds text values using text and uses title as <h3> tag. select It uses multiple parameter to add multiple values. select and checkboxes It uses options field to set the available options. display It uses content parameter to display the content. It sets the markdown to true to show the content. captcha It uses recatpcha_site_key and recaptcha_not_validated parameters. We have code on captcha information under field called g-recaptcha-response as shown below − - name: g-recaptcha-response label: Captcha type: captcha recatpcha_site_key: 6LelOg4TAAAAALAt1CjjjVMxFLKY8rrnednYVbr8 recaptcha_not_validated: 'Captcha not valid!' validate: required: true The reCaptcha is used to protect your website from spam and abuse. It uses the recatpcha_site_key option and displays the widget on your site. To use reCaptcha, just refer the reCaptcha docs. If reCaptcha is incorrect, then it will display message using the recaptcha_not_validated option. You can send an email with specific options under the process field as shown below − - email: from: "{{ config.plugins.email.from }}" to: "{{ config.plugins.email.to }}" subject: "Contact by {{ form.value.name|e }}" body: "{% include 'forms/data.html.twig' %}" It uses the email option which includes two fields; the from field specifies the sender of the email address and the to field specifies the recevier of the email address by using the Email plugin configuration. The email field also uses subject option in which an email is sent to the email entered with the subject [Contact by][name entered] and the body of the email is defined in the forms/data.html.twig file of the theme. You can redirect to another page by using message and display options defined under the process field. process: - message: Thank you for getting in touch! - display: thankyou The message option sets a message which should be displayed when a user click the submit button. When a user submits the form, it should be redirected to another page. Create one subpage under the thankyou subfolder where your form.md file is stored. After submitting the form, it will be redirected on the page and displays the above message. The subpage called thankyou/formdata.md will have the following content. --- title: Email sent cache_enable: false process: twig: true --- ## Your email has been sent! When you submit the form, the plugin will send an email to the user and data is saved under the data/folder. It is used to save the data to a file which is saved under the user/data folder. For instance − process: - save: fileprefix: contact- dateformat: Ymd-His-u extension: txt body: "{% include 'forms/data.txt.twig' %}" The data will be stored in text format with extension txt. The body is taken from the templates/forms/data.html.twig file of the theme. The following screen shows a simple form − 19 Lectures 3 hours Mr. Pradeep Kshetrapal 30 Lectures 4 hours Priyanka Choudhary 55 Lectures 4.5 hours University Code 24 Lectures 1 hours Mike Clayton Print Add Notes Bookmark this page
[ { "code": null, "e": 2633, "s": 2502, "text": "You can create a form using the form plugin available in this link. Search for the form plugin and install it in your Grav folder." }, { "code": null, "e": 2855, "s": 2633, "text": "You can also install this plugin using the command $ bin/gpm install Form. Navigate to your root folder of Grav and type this command. It will automatically download the form plugin and install the necessary dependencies." }, { "code": null, "e": 2975, "s": 2855, "text": "You can create a simple form which can be defined in the page YAML frontmatter. The following is an example of a form −" }, { "code": null, "e": 4273, "s": 2975, "text": "---\ntitle: Contact Form\n\nform:\n name: contact\n\n fields:\n - name: name\n label: Name\n placeholder: Enter your name\n autofocus: on\n autocomplete: on\n type: text\n validate:\n required: true\n\n - name: email\n label: Email\n placeholder: Enter your email address\n type: email\n validate:\n required: true\n\n - name: message\n label: Message\n placeholder: Enter your message\n type: textarea\n validate:\n required: true\n\n - name: g-recaptcha-response\n label: Captcha\n type: captcha\n recatpcha_site_key: 6LelOg4TAAAAALAt1CjjjVMxFLKY8rrnednYVbr8\n recaptcha_not_validated: 'Captcha not valid!'\n validate:\n required: true\n\n buttons:\n - type: submit\n value: Submit\n - type: reset\n value: Reset\n\n process:\n - email:\n subject: \"[Site Contact Form] {{ form.value.name|e }}\"\n body: \"{% include 'forms/data.html.twig' %}\"\n - save:\n fileprefix: contact-\n dateformat: Ymd-His-u\n extension: txt\n body: \"{% include 'forms/data.txt.twig' %}\"\n - message: Thank you for getting in touch!\n - display: thankyou\n---" }, { "code": null, "e": 4505, "s": 4273, "text": "The above code shows simple form page with name, email, message and Captcha fields. When you submit the information after filling the form, the form will process by adding process field to the YAML frontmatter as shown in the code." }, { "code": null, "e": 4556, "s": 4505, "text": "The process field uses the following information −" }, { "code": null, "e": 4679, "s": 4556, "text": "The email option uses two fields such as from field specify sender of the email and to field specify receiver of the mail." }, { "code": null, "e": 4802, "s": 4679, "text": "The email option uses two fields such as from field specify sender of the email and to field specify receiver of the mail." }, { "code": null, "e": 4896, "s": 4802, "text": "The subject uses [feedback][entered mail] option in which email is sent to the entered email." }, { "code": null, "e": 4990, "s": 4896, "text": "The subject uses [feedback][entered mail] option in which email is sent to the entered email." }, { "code": null, "e": 5096, "s": 4990, "text": "The body of the email is specified in the forms/data.html.twig file which is present in the theme folder." }, { "code": null, "e": 5202, "s": 5096, "text": "The body of the email is specified in the forms/data.html.twig file which is present in the theme folder." }, { "code": null, "e": 5354, "s": 5202, "text": "The form input data is stored under the user/data folder. The template is defined in the forms/data.txt.twig file which is present in the theme folder." }, { "code": null, "e": 5506, "s": 5354, "text": "The form input data is stored under the user/data folder. The template is defined in the forms/data.txt.twig file which is present in the theme folder." }, { "code": null, "e": 5622, "s": 5506, "text": "Create a subpage under the thankyou/ sub folder which will be redirected to that page when a user submits the form." }, { "code": null, "e": 5738, "s": 5622, "text": "Create a subpage under the thankyou/ sub folder which will be redirected to that page when a user submits the form." }, { "code": null, "e": 5817, "s": 5738, "text": "You can use some fields with the form plugin as shown in the following table −" }, { "code": null, "e": 5825, "s": 5817, "text": "Captcha" }, { "code": null, "e": 5923, "s": 5825, "text": "It is an antispam field which is used in computing to determine whether or not the user is human." }, { "code": null, "e": 5932, "s": 5923, "text": "Checkbox" }, { "code": null, "e": 5963, "s": 5932, "text": "It displays a simple checkbox." }, { "code": null, "e": 5974, "s": 5963, "text": "Checkboxes" }, { "code": null, "e": 6007, "s": 5974, "text": "It displays multiple checkboxes." }, { "code": null, "e": 6025, "s": 6007, "text": "Date and Datetime" }, { "code": null, "e": 6101, "s": 6025, "text": "Both fields are used to display date and date along with time respectively." }, { "code": null, "e": 6107, "s": 6101, "text": "Email" }, { "code": null, "e": 6145, "s": 6107, "text": "It is an email field with validation." }, { "code": null, "e": 6152, "s": 6145, "text": "Hidden" }, { "code": null, "e": 6183, "s": 6152, "text": "It specifies the hidden field." }, { "code": null, "e": 6192, "s": 6183, "text": "Password" }, { "code": null, "e": 6225, "s": 6192, "text": "It specifies the password field." }, { "code": null, "e": 6231, "s": 6225, "text": "Radio" }, { "code": null, "e": 6269, "s": 6231, "text": "It displays the simple radio buttons." }, { "code": null, "e": 6276, "s": 6269, "text": "Select" }, { "code": null, "e": 6302, "s": 6276, "text": "It provides select field." }, { "code": null, "e": 6309, "s": 6302, "text": "Spacer" }, { "code": null, "e": 6370, "s": 6309, "text": "It allows to add title, text or horizontal line to the form." }, { "code": null, "e": 6375, "s": 6370, "text": "Text" }, { "code": null, "e": 6406, "s": 6375, "text": "It displays simple text field." }, { "code": null, "e": 6415, "s": 6406, "text": "Textarea" }, { "code": null, "e": 6451, "s": 6415, "text": "It displays simple text area field." }, { "code": null, "e": 6459, "s": 6451, "text": "Display" }, { "code": null, "e": 6523, "s": 6459, "text": "It displays the text or instruction field, not the input field." }, { "code": null, "e": 6627, "s": 6523, "text": "Every field accepts the following parameters which can be used to customize the appearance in the form." }, { "code": null, "e": 6633, "s": 6627, "text": "label" }, { "code": null, "e": 6661, "s": 6633, "text": "It defines the label field." }, { "code": null, "e": 6679, "s": 6661, "text": "validate.required" }, { "code": null, "e": 6710, "s": 6679, "text": "It makes the element required." }, { "code": null, "e": 6727, "s": 6710, "text": "validate.pattern" }, { "code": null, "e": 6760, "s": 6727, "text": "It specifies validation pattern." }, { "code": null, "e": 6777, "s": 6760, "text": "validate.message" }, { "code": null, "e": 6823, "s": 6777, "text": "It display the message when validation fails." }, { "code": null, "e": 6828, "s": 6823, "text": "type" }, { "code": null, "e": 6855, "s": 6828, "text": "It defines the field type." }, { "code": null, "e": 6863, "s": 6855, "text": "default" }, { "code": null, "e": 6898, "s": 6863, "text": "It defines the default field type." }, { "code": null, "e": 6903, "s": 6898, "text": "size" }, { "code": null, "e": 6975, "s": 6903, "text": "It displays the field size such as large, x-small, medium, long, small." }, { "code": null, "e": 6980, "s": 6975, "text": "name" }, { "code": null, "e": 7007, "s": 6980, "text": "It defines the field name." }, { "code": null, "e": 7015, "s": 7007, "text": "classes" }, { "code": null, "e": 7048, "s": 7015, "text": "It uses string with css classes." }, { "code": null, "e": 7051, "s": 7048, "text": "id" }, { "code": null, "e": 7076, "s": 7051, "text": "It defines the field id." }, { "code": null, "e": 7082, "s": 7076, "text": "style" }, { "code": null, "e": 7119, "s": 7082, "text": "It specifies the style of the field." }, { "code": null, "e": 7125, "s": 7119, "text": "title" }, { "code": null, "e": 7160, "s": 7125, "text": "It defines the title of the field." }, { "code": null, "e": 7169, "s": 7160, "text": "disabled" }, { "code": null, "e": 7232, "s": 7169, "text": "It determines whether or not the field is in a disabled state." }, { "code": null, "e": 7244, "s": 7232, "text": "placeholder" }, { "code": null, "e": 7333, "s": 7244, "text": "It is a short hint which is displayed in the input field before the user enters a value." }, { "code": null, "e": 7343, "s": 7333, "text": "autofocus" }, { "code": null, "e": 7430, "s": 7343, "text": "It specifies that an input element should automatically get focus when the page loads." }, { "code": null, "e": 7441, "s": 7430, "text": "novalidate" }, { "code": null, "e": 7509, "s": 7441, "text": "It specifies that form data should not be validated when submitted." }, { "code": null, "e": 7518, "s": 7509, "text": "readonly" }, { "code": null, "e": 7558, "s": 7518, "text": "It determines field as read only state." }, { "code": null, "e": 7571, "s": 7558, "text": "autocomplete" }, { "code": null, "e": 7700, "s": 7571, "text": "It displays the options in the field when user starts typing in the field and displays the values based on earlier typed values." }, { "code": null, "e": 7758, "s": 7700, "text": "Some of the fields contains specific parameters such as −" }, { "code": null, "e": 7776, "s": 7758, "text": "date and datetime" }, { "code": null, "e": 7858, "s": 7776, "text": "These fields use validate.min and validate.max to set minimum and maximum values." }, { "code": null, "e": 7865, "s": 7858, "text": "spacer" }, { "code": null, "e": 7956, "s": 7865, "text": "It uses underline to add <hr> tag, adds text values using text and uses title as <h3> tag." }, { "code": null, "e": 7963, "s": 7956, "text": "select" }, { "code": null, "e": 8014, "s": 7963, "text": "It uses multiple parameter to add multiple values." }, { "code": null, "e": 8036, "s": 8014, "text": "select and checkboxes" }, { "code": null, "e": 8088, "s": 8036, "text": "It uses options field to set the available options." }, { "code": null, "e": 8096, "s": 8088, "text": "display" }, { "code": null, "e": 8196, "s": 8096, "text": "It uses content parameter to display the content. It sets the markdown to true to show the content." }, { "code": null, "e": 8204, "s": 8196, "text": "captcha" }, { "code": null, "e": 8271, "s": 8204, "text": "It uses recatpcha_site_key and recaptcha_not_validated parameters." }, { "code": null, "e": 8364, "s": 8271, "text": "We have code on captcha information under field called g-recaptcha-response as shown below −" }, { "code": null, "e": 8571, "s": 8364, "text": "- name: g-recaptcha-response\n label: Captcha\n type: captcha\n recatpcha_site_key: 6LelOg4TAAAAALAt1CjjjVMxFLKY8rrnednYVbr8\n recaptcha_not_validated: 'Captcha not valid!'\n validate:\n\t\trequired: true" }, { "code": null, "e": 8861, "s": 8571, "text": "The reCaptcha is used to protect your website from spam and abuse. It uses the recatpcha_site_key option and displays the widget on your site. To use reCaptcha, just refer the reCaptcha docs. If reCaptcha is incorrect, then it will display message using the recaptcha_not_validated option." }, { "code": null, "e": 8946, "s": 8861, "text": "You can send an email with specific options under the process field as shown below −" }, { "code": null, "e": 9126, "s": 8946, "text": "- email:\n\tfrom: \"{{ config.plugins.email.from }}\"\n\tto: \"{{ config.plugins.email.to }}\"\n\tsubject: \"Contact by {{ form.value.name|e }}\"\n\tbody: \"{% include 'forms/data.html.twig' %}\"" }, { "code": null, "e": 9553, "s": 9126, "text": "It uses the email option which includes two fields; the from field specifies the sender of the email address and the to field specifies the recevier of the email address by using the Email plugin configuration. The email field also uses subject option in which an email is sent to the email entered with the subject [Contact by][name entered] and the body of the email is defined in the forms/data.html.twig file of the theme." }, { "code": null, "e": 9656, "s": 9553, "text": "You can redirect to another page by using message and display options defined under the process field." }, { "code": null, "e": 9734, "s": 9656, "text": "process:\n - message: Thank you for getting in touch!\n - display: thankyou" }, { "code": null, "e": 10078, "s": 9734, "text": "The message option sets a message which should be displayed when a user click the submit button. When a user submits the form, it should be redirected to another page. Create one subpage under the thankyou subfolder where your form.md file is stored. After submitting the form, it will be redirected on the page and displays the above message." }, { "code": null, "e": 10151, "s": 10078, "text": "The subpage called thankyou/formdata.md will have the following content." }, { "code": null, "e": 10250, "s": 10151, "text": "---\ntitle: Email sent\ncache_enable: false\nprocess:\n twig: true\n---\n\n## Your email has been sent!" }, { "code": null, "e": 10359, "s": 10250, "text": "When you submit the form, the plugin will send an email to the user and data is saved under the data/folder." }, { "code": null, "e": 10440, "s": 10359, "text": "It is used to save the data to a file which is saved under the user/data folder." }, { "code": null, "e": 10455, "s": 10440, "text": "For instance −" }, { "code": null, "e": 10601, "s": 10455, "text": "process:\n - save:\n fileprefix: contact-\n dateformat: Ymd-His-u\n extension: txt\n body: \"{% include 'forms/data.txt.twig' %}\"" }, { "code": null, "e": 10737, "s": 10601, "text": "The data will be stored in text format with extension txt. The body is taken from the templates/forms/data.html.twig file of the theme." }, { "code": null, "e": 10780, "s": 10737, "text": "The following screen shows a simple form −" }, { "code": null, "e": 10813, "s": 10780, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 10837, "s": 10813, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 10870, "s": 10837, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 10890, "s": 10870, "text": " Priyanka Choudhary" }, { "code": null, "e": 10925, "s": 10890, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10942, "s": 10925, "text": " University Code" }, { "code": null, "e": 10975, "s": 10942, "text": "\n 24 Lectures \n 1 hours \n" }, { "code": null, "e": 10989, "s": 10975, "text": " Mike Clayton" }, { "code": null, "e": 10996, "s": 10989, "text": " Print" }, { "code": null, "e": 11007, "s": 10996, "text": " Add Notes" } ]
C - Pointer arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and - To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer − ptr++ After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001. We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array − #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); /* move to the next location */ ptr++; } return 0; } When the above code is compiled and executed, it produces the following result − Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200 The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below − #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %x\n", i-1, ptr ); printf("Value of var[%d] = %d\n", i-1, *ptr ); /* move to the previous location */ ptr--; } return 0; } When the above code is compiled and executed, it produces the following result − Address of var[2] = bfedbcd8 Value of var[2] = 200 Address of var[1] = bfedbcd4 Value of var[1] = 100 Address of var[0] = bfedbcd0 Value of var[0] = 10 Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared. The following program modifies the previous example − one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] − #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have address of the first element in pointer */ ptr = var; i = 0; while ( ptr <= &var[MAX - 1] ) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); /* point to the next location */ ptr++; i++; } return 0; } When the above code is compiled and executed, it produces the following result − Address of var[0] = bfdbcb20 Value of var[0] = 10 Address of var[1] = bfdbcb24 Value of var[1] = 100 Address of var[2] = bfdbcb28 Value of var[2] = 200 Print Add Notes Bookmark this page
[ { "code": null, "e": 2321, "s": 2084, "text": "A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -" }, { "code": null, "e": 2529, "s": 2321, "text": "To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −" }, { "code": null, "e": 2536, "s": 2529, "text": "ptr++\n" }, { "code": null, "e": 3018, "s": 2536, "text": "After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001." }, { "code": null, "e": 3315, "s": 3018, "text": "We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array −" }, { "code": null, "e": 3692, "s": 3315, "text": "#include <stdio.h>\n\nconst int MAX = 3;\n\nint main () {\n\n int var[] = {10, 100, 200};\n int i, *ptr;\n\n /* let us have array address in pointer */\n ptr = var;\n\t\n for ( i = 0; i < MAX; i++) {\n\n printf(\"Address of var[%d] = %x\\n\", i, ptr );\n printf(\"Value of var[%d] = %d\\n\", i, *ptr );\n\n /* move to the next location */\n ptr++;\n }\n\t\n return 0;\n}" }, { "code": null, "e": 3773, "s": 3692, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3926, "s": 3773, "text": "Address of var[0] = bf882b30\nValue of var[0] = 10\nAddress of var[1] = bf882b34\nValue of var[1] = 100\nAddress of var[2] = bf882b38\nValue of var[2] = 200\n" }, { "code": null, "e": 4066, "s": 3926, "text": "The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below −" }, { "code": null, "e": 4459, "s": 4066, "text": "#include <stdio.h>\n\nconst int MAX = 3;\n\nint main () {\n\n int var[] = {10, 100, 200};\n int i, *ptr;\n\n /* let us have array address in pointer */\n ptr = &var[MAX-1];\n\t\n for ( i = MAX; i > 0; i--) {\n\n printf(\"Address of var[%d] = %x\\n\", i-1, ptr );\n printf(\"Value of var[%d] = %d\\n\", i-1, *ptr );\n\n /* move to the previous location */\n ptr--;\n }\n\t\n return 0;\n}" }, { "code": null, "e": 4540, "s": 4459, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4693, "s": 4540, "text": "Address of var[2] = bfedbcd8\nValue of var[2] = 200\nAddress of var[1] = bfedbcd4\nValue of var[1] = 100\nAddress of var[0] = bfedbcd0\nValue of var[0] = 10\n" }, { "code": null, "e": 4916, "s": 4693, "text": "Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared." }, { "code": null, "e": 5156, "s": 4916, "text": "The following program modifies the previous example − one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] −" }, { "code": null, "e": 5574, "s": 5156, "text": "#include <stdio.h>\n\nconst int MAX = 3;\n\nint main () {\n\n int var[] = {10, 100, 200};\n int i, *ptr;\n\n /* let us have address of the first element in pointer */\n ptr = var;\n i = 0;\n\t\n while ( ptr <= &var[MAX - 1] ) {\n\n printf(\"Address of var[%d] = %x\\n\", i, ptr );\n printf(\"Value of var[%d] = %d\\n\", i, *ptr );\n\n /* point to the next location */\n ptr++;\n i++;\n }\n\t\n return 0;\n}" }, { "code": null, "e": 5655, "s": 5574, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5808, "s": 5655, "text": "Address of var[0] = bfdbcb20\nValue of var[0] = 10\nAddress of var[1] = bfdbcb24\nValue of var[1] = 100\nAddress of var[2] = bfdbcb28\nValue of var[2] = 200\n" }, { "code": null, "e": 5815, "s": 5808, "text": " Print" }, { "code": null, "e": 5826, "s": 5815, "text": " Add Notes" } ]
java.lang.reflect.Method.getParameterTypes() Method Example
The java.lang.reflect.Method.getParameterTypes() method returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters. Following is the declaration for java.lang.reflect.Method.getParameterTypes() method. public Class<?>[] getParameterTypes() the parameter types for the method this object represents. The following example shows the usage of java.lang.reflect.Method.getParameterTypes() method. package com.tutorialspoint; import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); Class[] parameterTypes = methods[1].getParameterTypes(); for(Class parameterType: parameterTypes){ System.out.println(parameterType.getName()); } } } class SampleClass { private String sampleField; public String getSampleField() { return sampleField; } public void setSampleField(String sampleField) { this.sampleField = sampleField; } } Let us compile and run the above program, this will produce the following result − java.lang.String Print Add Notes Bookmark this page
[ { "code": null, "e": 1733, "s": 1454, "text": "The java.lang.reflect.Method.getParameterTypes() method returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters." }, { "code": null, "e": 1819, "s": 1733, "text": "Following is the declaration for java.lang.reflect.Method.getParameterTypes() method." }, { "code": null, "e": 1858, "s": 1819, "text": "public Class<?>[] getParameterTypes()\n" }, { "code": null, "e": 1917, "s": 1858, "text": "the parameter types for the method this object represents." }, { "code": null, "e": 2011, "s": 1917, "text": "The following example shows the usage of java.lang.reflect.Method.getParameterTypes() method." }, { "code": null, "e": 2607, "s": 2011, "text": "package com.tutorialspoint;\n\nimport java.lang.reflect.Method;\n\npublic class MethodDemo {\n public static void main(String[] args) {\n\n Method[] methods = SampleClass.class.getMethods();\n Class[] parameterTypes = methods[1].getParameterTypes();\n\n for(Class parameterType: parameterTypes){\n System.out.println(parameterType.getName()); \n \n }\n }\n}\n\nclass SampleClass {\n private String sampleField;\n\n public String getSampleField() {\n return sampleField;\n }\n\n public void setSampleField(String sampleField) {\n this.sampleField = sampleField;\n } \n}" }, { "code": null, "e": 2690, "s": 2607, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2708, "s": 2690, "text": "java.lang.String\n" }, { "code": null, "e": 2715, "s": 2708, "text": " Print" }, { "code": null, "e": 2726, "s": 2715, "text": " Add Notes" } ]
GWT - DatePicker Widget
The DatePicker widget represents a standard GWT date picker. Following is the declaration for com.google.gwt.user.datepicker.client.DatePicker class − public class DatePicker extends Composite implements HasHighlightHandlers<java.util.Date>, HasShowRangeHandlers<java.util.Date>, HasValue<java.util.Date> Following default CSS Style rules will be applied to all the DatePicker widget. You can override it as per your requirements. .gwt-DatePicker { } .datePickerMonthSelector { } .datePickerMonth { } .datePickerPreviousButton { } .datePickerNextButton { } .datePickerDays { } .datePickerWeekdayLabel { } .datePickerWeekendLabel { } .datePickerDay { } .datePickerDayIsToday { } .datePickerDayIsWeekend { } .datePickerDayIsFiller { } .datePickerDayIsValue { } .datePickerDayIsDisabled { } .datePickerDayIsHighlighted { } .datePickerDayIsValueAndHighlighted { } DatePicker() Create a new date picker. protected DatePicker(MonthSelector monthSelector, CalendarView view, CalendarModel model) Create a new date picker. HandlerRegistration addHighlightHandler(HighlightHandler<java.util.Date> handler) Adds a HighlightEvent handler. Handler Registration add Show Range Handler (ShowRangeHandler<java.util.Date> handler) Adds a ShowRangeEvent handler. Handler Registration addShow Range Handler AndFire (Show Range Handler<java.util.Date> handler) Adds a show range handler and immediately activate the handler on the current view. void addStyleToDates(java.lang.String styleName, java.util.Date date) Add a style name to the given dates. void addStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Add a style name to the given dates. void add Style To Dates(java.lang.String style Name, java.lang.Iterable<java.util.Date> dates) Add a style name to the given dates. void addTransientStyleToDates(java.lang.String styleName, java.util.Date date) Adds the given style name to the specified dates, which must be visible. void addTransientStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Adds the given style name to the specified dates, which must be visible. void add Transient Style ToDates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates) Adds the given style name to the specified dates, which must be visible. Handler Registration addValue Change Handler(ValueChangeHandler<java.util.Date> handler) Adds a ValueChangeEvent handler. java.util.Date getCurrentMonth() Gets the current month the date picker is showing. java.util.Date getFirstDate() Returns the first shown date. java.util.Date getHighlightedDate() Gets the highlighted date (the one the mouse is hovering over), if any. java.util.Date getLastDate() Returns the last shown date. protected CalendarModel getModel() Gets the CalendarModel associated with this date picker. protected MonthSelector getMonthSelector() Gets the MonthSelector associated with this date picker. java.lang.String getStyleOfDate(java.util.Date date) Gets the style associated with a date (does not include styles set via addTransientStyleToDates(java.lang.String, java.util.Date)). java.util.Date getValue() Returns the selected date, or null if none is selected. protected CalendarView getView() Gets the CalendarView associated with this date picker. boolean isDateEnabled(java.util.Date date) Is the visible date enabled? boolean isDateVisible(java.util.Date date) Is the date currently shown in the date picker? void onLoad() This method is called immediately after a widget becomes attached to the browser's document. protected void refreshAll() Refreshes all components of this date picker. void removeStyleFromDates(java.lang.String styleName, java.util.Date date) Removes the styleName from the given dates (even if it is transient). void removeStyleFromDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Removes the styleName from the given dates (even if it is transient). void remove Style From Dates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates) Removes the styleName from the given dates (even if it is transient). void setCurrentMonth(java.util.Date month) Sets the date picker to show the given month, use getFirstDate() and getLastDate() to access the exact date range the date picker chose to display. void setStyleName(java.lang.String styleName) Sets the date picker style name. void setTransientEnabledOnDates(boolean enabled, java.util.Date date) Sets a visible date to be enabled or disabled. void setTransientEnabledOnDates(boolean enabled, java.util.Date date, java.util.Date... moreDates) Sets a visible date to be enabled or disabled. void set Transient Enabled On Dates(boolean enabled, java.lang.Iterable<java.util.Date> dates) Sets a group of visible dates to be enabled or disabled. protected void setup() Sets up the date picker. void setValue(java.util.Date newValue) Sets the DatePicker's value. void setValue(java.util.Date newValue, boolean fireEvents) Sets the DatePicker's value. This class inherits methods from the following classes − com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Composite com.google.gwt.user.client.ui.Composite java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a DatePicker Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-DatePicker { border: 1px solid #ccc; border-top:1px solid #999; cursor: default; } .gwt-DatePicker td, .datePickerMonthSelector td:focus { outline: none; } .datePickerMonthSelector td:focus { outline: none; } .datePickerDays { width: 100%; background: white; } .datePickerDay, .datePickerWeekdayLabel, .datePickerWeekendLabel { font-size: 85%; text-align: center; padding: 4px; outline: none; font-weight:bold; color:#333; border-right: 1px solid #EDEDED; border-bottom: 1px solid #EDEDED; } .datePickerWeekdayLabel, .datePickerWeekendLabel { background: #fff; padding: 0px 4px 2px; cursor: default; color:#666; font-size:70%; font-weight:normal; } .datePickerDay { padding: 4px 7px; cursor: hand; cursor: pointer; } .datePickerDayIsWeekend { background: #f7f7f7; } .datePickerDayIsFiller { color: #999; font-weight:normal; } .datePickerDayIsValue { background: #d7dfe8; } .datePickerDayIsDisabled { color: #AAAAAA; font-style: italic; } .datePickerDayIsHighlighted { background: #F0E68C; } .datePickerDayIsValueAndHighlighted { background: #d7dfe8; } .datePickerDayIsToday { padding: 3px; color: #00f; background: url(images/hborder.png) repeat-x 0px -2607px; } .datePickerMonthSelector { width: 100%; padding: 1px 0 5px 0; background: #fff; } .datePickerPreviousButton, .datePickerNextButton { font-size: 120%; line-height: 1em; color: #3a6aad; cursor: hand; cursor: pointer; font-weight: bold; padding: 0px 4px; outline: none; } td.datePickerMonth { text-align: center; vertical-align: middle; white-space: nowrap; font-size: 100%; font-weight: bold; color: #333; } .gwt-DateBox { padding: 5px 4px; border: 1px solid #ccc; border-top: 1px solid #999; font-size: 100%; } .gwt-DateBox input { width: 8em; } .dateBoxFormatError { background: #ffcccc; } .dateBoxPopup { } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>DatePicker Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Tree widget. package com.tutorialspoint.client; import java.util.Date; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.datepicker.client.DateBox; import com.google.gwt.user.datepicker.client.DatePicker; public class HelloWorld implements EntryPoint { public void onModuleLoad() { // Create a basic date picker DatePicker datePicker = new DatePicker(); final Label text = new Label(); // Set the value in the text box when the user selects a date datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() { @Override public void onValueChange(ValueChangeEvent<Date> event) { Date date = event.getValue(); String dateString = DateTimeFormat.getFormat("MM/dd/yyyy").format(date); text.setText(dateString); } }); // Set the default value datePicker.setValue(new Date(), true); // Create a DateBox DateTimeFormat dateFormat = DateTimeFormat.getFormat("MM/dd/yyyy"); DateBox dateBox = new DateBox(); dateBox.setFormat(new DateBox.DefaultFormat(dateFormat)); Label selectLabel = new Label("Permanent DatePicker:"); Label selectLabel2 = new Label("DateBox with popup DatePicker:"); // Add widgets to the root panel. VerticalPanel vPanel = new VerticalPanel(); vPanel.setSpacing(10); vPanel.add(selectLabel); vPanel.add(text); vPanel.add(datePicker); vPanel.add(selectLabel2); vPanel.add(dateBox); RootPanel.get("gwtContainer").add(vPanel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − Print Add Notes Bookmark this page
[ { "code": null, "e": 2084, "s": 2023, "text": "The DatePicker widget represents a standard GWT date picker." }, { "code": null, "e": 2174, "s": 2084, "text": "Following is the declaration for com.google.gwt.user.datepicker.client.DatePicker class −" }, { "code": null, "e": 2343, "s": 2174, "text": "public class DatePicker\n extends Composite\n implements HasHighlightHandlers<java.util.Date>,\n\t HasShowRangeHandlers<java.util.Date>, HasValue<java.util.Date>" }, { "code": null, "e": 2469, "s": 2343, "text": "Following default CSS Style rules will be applied to all the DatePicker widget. You can override it as per your requirements." }, { "code": null, "e": 2925, "s": 2469, "text": ".gwt-DatePicker { }\n\n.datePickerMonthSelector { }\n\n.datePickerMonth { }\n\n.datePickerPreviousButton { }\n\n.datePickerNextButton { }\n\n.datePickerDays { }\n\n.datePickerWeekdayLabel { }\n\n.datePickerWeekendLabel { }\n\n.datePickerDay { }\n\n.datePickerDayIsToday { }\n\n.datePickerDayIsWeekend { }\n\n.datePickerDayIsFiller { }\n\n.datePickerDayIsValue { }\n\n.datePickerDayIsDisabled { }\n\n.datePickerDayIsHighlighted { }\n\n.datePickerDayIsValueAndHighlighted { }" }, { "code": null, "e": 2938, "s": 2925, "text": "DatePicker()" }, { "code": null, "e": 2964, "s": 2938, "text": "Create a new date picker." }, { "code": null, "e": 3054, "s": 2964, "text": "protected DatePicker(MonthSelector monthSelector, CalendarView view, CalendarModel model)" }, { "code": null, "e": 3080, "s": 3054, "text": "Create a new date picker." }, { "code": null, "e": 3162, "s": 3080, "text": "HandlerRegistration addHighlightHandler(HighlightHandler<java.util.Date> handler)" }, { "code": null, "e": 3193, "s": 3162, "text": "Adds a HighlightEvent handler." }, { "code": null, "e": 3280, "s": 3193, "text": "Handler Registration add Show Range Handler (ShowRangeHandler<java.util.Date> handler)" }, { "code": null, "e": 3311, "s": 3280, "text": "Adds a ShowRangeEvent handler." }, { "code": null, "e": 3407, "s": 3311, "text": "Handler Registration addShow Range Handler AndFire (Show Range Handler<java.util.Date> handler)" }, { "code": null, "e": 3491, "s": 3407, "text": "Adds a show range handler and immediately activate the handler on the current view." }, { "code": null, "e": 3561, "s": 3491, "text": "void addStyleToDates(java.lang.String styleName, java.util.Date date)" }, { "code": null, "e": 3598, "s": 3561, "text": "Add a style name to the given dates." }, { "code": null, "e": 3697, "s": 3598, "text": "void addStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates)" }, { "code": null, "e": 3734, "s": 3697, "text": "Add a style name to the given dates." }, { "code": null, "e": 3829, "s": 3734, "text": "void add Style To Dates(java.lang.String style Name, java.lang.Iterable<java.util.Date> dates)" }, { "code": null, "e": 3866, "s": 3829, "text": "Add a style name to the given dates." }, { "code": null, "e": 3945, "s": 3866, "text": "void addTransientStyleToDates(java.lang.String styleName, java.util.Date date)" }, { "code": null, "e": 4018, "s": 3945, "text": "Adds the given style name to the specified dates, which must be visible." }, { "code": null, "e": 4126, "s": 4018, "text": "void addTransientStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates)" }, { "code": null, "e": 4199, "s": 4126, "text": "Adds the given style name to the specified dates, which must be visible." }, { "code": null, "e": 4302, "s": 4199, "text": "void add Transient Style ToDates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates)" }, { "code": null, "e": 4375, "s": 4302, "text": "Adds the given style name to the specified dates, which must be visible." }, { "code": null, "e": 4464, "s": 4375, "text": "Handler Registration addValue Change Handler(ValueChangeHandler<java.util.Date> handler)" }, { "code": null, "e": 4497, "s": 4464, "text": "Adds a ValueChangeEvent handler." }, { "code": null, "e": 4530, "s": 4497, "text": "java.util.Date getCurrentMonth()" }, { "code": null, "e": 4581, "s": 4530, "text": "Gets the current month the date picker is showing." }, { "code": null, "e": 4611, "s": 4581, "text": "java.util.Date getFirstDate()" }, { "code": null, "e": 4641, "s": 4611, "text": "Returns the first shown date." }, { "code": null, "e": 4677, "s": 4641, "text": "java.util.Date getHighlightedDate()" }, { "code": null, "e": 4749, "s": 4677, "text": "Gets the highlighted date (the one the mouse is hovering over), if any." }, { "code": null, "e": 4778, "s": 4749, "text": "java.util.Date getLastDate()" }, { "code": null, "e": 4807, "s": 4778, "text": "Returns the last shown date." }, { "code": null, "e": 4842, "s": 4807, "text": "protected CalendarModel getModel()" }, { "code": null, "e": 4899, "s": 4842, "text": "Gets the CalendarModel associated with this date picker." }, { "code": null, "e": 4942, "s": 4899, "text": "protected MonthSelector getMonthSelector()" }, { "code": null, "e": 4999, "s": 4942, "text": "Gets the MonthSelector associated with this date picker." }, { "code": null, "e": 5052, "s": 4999, "text": "java.lang.String getStyleOfDate(java.util.Date date)" }, { "code": null, "e": 5184, "s": 5052, "text": "Gets the style associated with a date (does not include styles set via addTransientStyleToDates(java.lang.String, java.util.Date))." }, { "code": null, "e": 5210, "s": 5184, "text": "java.util.Date getValue()" }, { "code": null, "e": 5266, "s": 5210, "text": "Returns the selected date, or null if none is selected." }, { "code": null, "e": 5299, "s": 5266, "text": "protected CalendarView getView()" }, { "code": null, "e": 5355, "s": 5299, "text": "Gets the CalendarView associated with this date picker." }, { "code": null, "e": 5398, "s": 5355, "text": "boolean isDateEnabled(java.util.Date date)" }, { "code": null, "e": 5427, "s": 5398, "text": "Is the visible date enabled?" }, { "code": null, "e": 5470, "s": 5427, "text": "boolean isDateVisible(java.util.Date date)" }, { "code": null, "e": 5518, "s": 5470, "text": "Is the date currently shown in the date picker?" }, { "code": null, "e": 5532, "s": 5518, "text": "void onLoad()" }, { "code": null, "e": 5625, "s": 5532, "text": "This method is called immediately after a widget becomes attached to the browser's document." }, { "code": null, "e": 5653, "s": 5625, "text": "protected void refreshAll()" }, { "code": null, "e": 5699, "s": 5653, "text": "Refreshes all components of this date picker." }, { "code": null, "e": 5774, "s": 5699, "text": "void removeStyleFromDates(java.lang.String styleName, java.util.Date date)" }, { "code": null, "e": 5844, "s": 5774, "text": "Removes the styleName from the given dates (even if it is transient)." }, { "code": null, "e": 5948, "s": 5844, "text": "void removeStyleFromDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates)" }, { "code": null, "e": 6018, "s": 5948, "text": "Removes the styleName from the given dates (even if it is transient)." }, { "code": null, "e": 6117, "s": 6018, "text": "void remove Style From Dates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates)" }, { "code": null, "e": 6187, "s": 6117, "text": "Removes the styleName from the given dates (even if it is transient)." }, { "code": null, "e": 6230, "s": 6187, "text": "void setCurrentMonth(java.util.Date month)" }, { "code": null, "e": 6378, "s": 6230, "text": "Sets the date picker to show the given month, use getFirstDate() and getLastDate() to access the exact date range the date picker chose to display." }, { "code": null, "e": 6424, "s": 6378, "text": "void setStyleName(java.lang.String styleName)" }, { "code": null, "e": 6457, "s": 6424, "text": "Sets the date picker style name." }, { "code": null, "e": 6527, "s": 6457, "text": "void setTransientEnabledOnDates(boolean enabled, java.util.Date date)" }, { "code": null, "e": 6574, "s": 6527, "text": "Sets a visible date to be enabled or disabled." }, { "code": null, "e": 6673, "s": 6574, "text": "void setTransientEnabledOnDates(boolean enabled, java.util.Date date, java.util.Date... moreDates)" }, { "code": null, "e": 6720, "s": 6673, "text": "Sets a visible date to be enabled or disabled." }, { "code": null, "e": 6815, "s": 6720, "text": "void set Transient Enabled On Dates(boolean enabled, java.lang.Iterable<java.util.Date> dates)" }, { "code": null, "e": 6872, "s": 6815, "text": "Sets a group of visible dates to be enabled or disabled." }, { "code": null, "e": 6895, "s": 6872, "text": "protected void setup()" }, { "code": null, "e": 6920, "s": 6895, "text": "Sets up the date picker." }, { "code": null, "e": 6959, "s": 6920, "text": "void setValue(java.util.Date newValue)" }, { "code": null, "e": 6988, "s": 6959, "text": "Sets the DatePicker's value." }, { "code": null, "e": 7047, "s": 6988, "text": "void setValue(java.util.Date newValue, boolean fireEvents)" }, { "code": null, "e": 7076, "s": 7047, "text": "Sets the DatePicker's value." }, { "code": null, "e": 7133, "s": 7076, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 7172, "s": 7133, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 7211, "s": 7172, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 7248, "s": 7211, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 7285, "s": 7248, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 7325, "s": 7285, "text": "com.google.gwt.user.client.ui.Composite" }, { "code": null, "e": 7365, "s": 7325, "text": "com.google.gwt.user.client.ui.Composite" }, { "code": null, "e": 7382, "s": 7365, "text": "java.lang.Object" }, { "code": null, "e": 7399, "s": 7382, "text": "java.lang.Object" }, { "code": null, "e": 7599, "s": 7399, "text": "This example will take you through simple steps to show usage of a DatePicker Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 7701, "s": 7599, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 8310, "s": 7701, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 8388, "s": 8310, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 10545, "s": 8388, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-DatePicker {\n border: 1px solid #ccc;\n border-top:1px solid #999;\n cursor: default;\n}\n\n.gwt-DatePicker td,\n.datePickerMonthSelector td:focus {\n outline: none;\n}\n\n.datePickerMonthSelector td:focus {\n outline: none;\n}\n\n.datePickerDays {\n width: 100%;\n background: white;\n}\n\n.datePickerDay,\n.datePickerWeekdayLabel,\n.datePickerWeekendLabel {\n font-size: 85%;\n text-align: center;\n padding: 4px;\n outline: none;\n font-weight:bold;\n color:#333;\n border-right: 1px solid #EDEDED;\n border-bottom: 1px solid #EDEDED;\n}\n\n.datePickerWeekdayLabel,\n.datePickerWeekendLabel {\n background: #fff;\n padding: 0px 4px 2px;\n cursor: default;\n color:#666;\n font-size:70%;\n font-weight:normal;\n}\n\n.datePickerDay {\n padding: 4px 7px;\n cursor: hand;\n cursor: pointer;\n}\n\n.datePickerDayIsWeekend {\n background: #f7f7f7;\n}\n\n.datePickerDayIsFiller {\n color: #999;\n font-weight:normal;\n}\n\n.datePickerDayIsValue {\n background: #d7dfe8;\n}\n\n.datePickerDayIsDisabled {\n color: #AAAAAA;\n font-style: italic;\n}\n\n.datePickerDayIsHighlighted {\n background: #F0E68C;\n}\n\n.datePickerDayIsValueAndHighlighted {\n background: #d7dfe8;\n}\n\n.datePickerDayIsToday {\n padding: 3px;\n color: #00f;\n background: url(images/hborder.png) repeat-x 0px -2607px;\n}\n\n.datePickerMonthSelector {\n width: 100%;\n padding: 1px 0 5px 0;\n background: #fff;\n}\n\n.datePickerPreviousButton,\n.datePickerNextButton {\n font-size: 120%;\n line-height: 1em;\n color: #3a6aad;\n cursor: hand;\n cursor: pointer;\n font-weight: bold;\n padding: 0px 4px;\n outline: none;\n}\n\ntd.datePickerMonth {\n text-align: center;\n vertical-align: middle;\n white-space: nowrap;\n font-size: 100%;\n font-weight: bold;\n color: #333;\n}\n\n.gwt-DateBox {\n padding: 5px 4px;\n border: 1px solid #ccc;\n border-top: 1px solid #999;\n font-size: 100%;\n}\n\n.gwt-DateBox input {\n width: 8em;\n}\n\n.dateBoxFormatError {\n background: #ffcccc;\n}\n\n.dateBoxPopup {\n}" }, { "code": null, "e": 10622, "s": 10545, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 10951, "s": 10622, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>DatePicker Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 11076, "s": 10951, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Tree widget." }, { "code": null, "e": 12994, "s": 11076, "text": "package com.tutorialspoint.client;\n\nimport java.util.Date;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.logical.shared.ValueChangeEvent;\nimport com.google.gwt.event.logical.shared.ValueChangeHandler;\nimport com.google.gwt.i18n.client.DateTimeFormat;\nimport com.google.gwt.user.client.ui.Label;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\nimport com.google.gwt.user.datepicker.client.DateBox;\nimport com.google.gwt.user.datepicker.client.DatePicker;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n // Create a basic date picker\n DatePicker datePicker = new DatePicker();\n final Label text = new Label();\n\n // Set the value in the text box when the user selects a date\n datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {\n @Override\n public void onValueChange(ValueChangeEvent<Date> event) {\n Date date = event.getValue();\n String dateString = \n DateTimeFormat.getFormat(\"MM/dd/yyyy\").format(date);\n text.setText(dateString);\t\t\t\t\n }\n });\n \n // Set the default value\n datePicker.setValue(new Date(), true);\n\n // Create a DateBox\n DateTimeFormat dateFormat = DateTimeFormat.getFormat(\"MM/dd/yyyy\");\n DateBox dateBox = new DateBox();\n dateBox.setFormat(new DateBox.DefaultFormat(dateFormat));\n\n Label selectLabel = new Label(\"Permanent DatePicker:\");\n Label selectLabel2 = new Label(\"DateBox with popup DatePicker:\");\n \n // Add widgets to the root panel.\n VerticalPanel vPanel = new VerticalPanel();\n vPanel.setSpacing(10);\n vPanel.add(selectLabel);\n vPanel.add(text);\n vPanel.add(datePicker);\n vPanel.add(selectLabel2);\n vPanel.add(dateBox);\n\n RootPanel.get(\"gwtContainer\").add(vPanel);\n } \n}" }, { "code": null, "e": 13228, "s": 12994, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 13235, "s": 13228, "text": " Print" }, { "code": null, "e": 13246, "s": 13235, "text": " Add Notes" } ]
Python Numpy - GeeksforGeeks
15 Oct, 2018 Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists. Creating a Numpy ArrayArrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.Note: Type of array can be explicitly defined while creating the array. Output: Array with Rank 1: [1 2 3] Array with Rank 2: [[1 2 3] [4 5 6]] Array created using passed tuple: [1 3 2] Accessing the array IndexIn a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content. Output: Initial Array: [[-1. 2. 0. 4. ] [ 4. -0.5 6. 0. ] [ 2.6 0. 7. 8. ] [ 3. -7. 4. 2. ]] Array with first 2 rows and alternate columns(0 and 2): [[-1. 0.] [ 4. 6.]] Elements at indices (1, 3), (1, 2), (0, 1), (3, 0): [ 0. 54. 2. 3.] Basic Array OperationsIn numpy, arrays allow a wide range of operations which can be performed on a particular array or a combination of Arrays. These operation include some basic Mathematical operation as well as Unary and Binary operations. Output: Adding 1 to every element: [[2 3] [4 5]] Subtracting 2 from each element: [[ 2 1] [ 0 -1]] Sum of all array elements: 10 Array sum: [[5 5] [5 5]] More on Numpy Arrays Basic Array Operations in Numpy Advanced Array Operations in Numpy Basic Slicing and Advanced Indexing in NumPy Python Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Every ndarray has an associated data type (dtype) object. This data type object (dtype) provides information about the layout of the array. The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes which can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be used to construct arrays. At the time of Array creation, Numpy tries to guess a datatype, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Constructing a Datatype ObjectIn Numpy, datatypes of Arrays need not to be defined unless a specific datatype is required. Numpy tries to guess the datatype for Arrays which are not predefined in the constructor function. Output: Integer Datatype: int64 Float Datatype: float64 Forcing a Datatype: int64 Math Operations on DataType arrayIn Numpy arrays, basic mathematical operations are performed element-wise on the array. These operations are applied both as operator overloads and as functions. Many useful functions are provided in Numpy for performing computations on Arrays such as sum: for addition of Array elements, T: for Transpose of elements, etc. Output: Addition of Two Arrays: [[ 7. 13.] [ 4. 14.]] Addition of Array elements: 19.0 Square root of Array1 elements: [[2. 2.64575131] [1.41421356 2.44948974]] Transpose of Array: [[4. 2.] [7. 6.]] More on Numpy Data Type Data type Object (dtype) in NumPy Programs on Numpy Python | Check whether a list is empty or not Python | Get unique values from a list Python | Multiply all numbers in the list (3 different ways) Transpose a matrix in Single line in Python Multiplication of two Matrices in Single line using Numpy in Python Python program to print checkerboard pattern of nxn using numpy Graph Plotting in Python | Set 1, Set 2, Set 3 Useful Numpy Articles Matrix manipulation in Python Basic Slicing and Advanced Indexing in NumPy Python Differences between Flatten() and Ravel() rand vs normal in Numpy.random in Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies Axios in React: A Guide for Beginners C++ Program For Inserting A Node In A Linked List Python Program For Inserting A Node In A Linked List Implementation of Bit Stuffing and Bit Destuffing How to set background images in ReactJS ? Tailwind CSS vs Bootstrap Image Sharpening Using Laplacian Filter and High Boost Filtering in MATLAB
[ { "code": null, "e": 41528, "s": 41500, "text": "\n15 Oct, 2018" }, { "code": null, "e": 41872, "s": 41528, "text": "Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data." }, { "code": null, "e": 42328, "s": 41872, "text": "Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists." }, { "code": null, "e": 42713, "s": 42328, "text": "Creating a Numpy ArrayArrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.Note: Type of array can be explicitly defined while creating the array." }, { "code": null, "e": 42721, "s": 42713, "text": "Output:" }, { "code": null, "e": 42835, "s": 42721, "text": "Array with Rank 1: \n [1 2 3]\nArray with Rank 2: \n [[1 2 3]\n [4 5 6]]\n\nArray created using passed tuple:\n [1 3 2]\n" }, { "code": null, "e": 43271, "s": 42835, "text": " Accessing the array IndexIn a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content." }, { "code": null, "e": 43279, "s": 43271, "text": "Output:" }, { "code": null, "e": 43542, "s": 43279, "text": "Initial Array: \n[[-1. 2. 0. 4. ]\n [ 4. -0.5 6. 0. ]\n [ 2.6 0. 7. 8. ]\n [ 3. -7. 4. 2. ]]\nArray with first 2 rows and alternate columns(0 and 2):\n [[-1. 0.]\n [ 4. 6.]]\n\nElements at indices (1, 3), (1, 2), (0, 1), (3, 0):\n [ 0. 54. 2. 3.]\n\n" }, { "code": null, "e": 43786, "s": 43542, "text": " Basic Array OperationsIn numpy, arrays allow a wide range of operations which can be performed on a particular array or a combination of Arrays. These operation include some basic Mathematical operation as well as Unary and Binary operations." }, { "code": null, "e": 43794, "s": 43786, "text": "Output:" }, { "code": null, "e": 43952, "s": 43794, "text": "Adding 1 to every element:\n [[2 3]\n [4 5]]\n\nSubtracting 2 from each element:\n [[ 2 1]\n [ 0 -1]]\n\nSum of all array elements: 10\n\nArray sum:\n [[5 5]\n [5 5]]\n" }, { "code": null, "e": 43974, "s": 43952, "text": " More on Numpy Arrays" }, { "code": null, "e": 44006, "s": 43974, "text": "Basic Array Operations in Numpy" }, { "code": null, "e": 44041, "s": 44006, "text": "Advanced Array Operations in Numpy" }, { "code": null, "e": 44093, "s": 44041, "text": "Basic Slicing and Advanced Indexing in NumPy Python" }, { "code": null, "e": 44776, "s": 44093, "text": "Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Every ndarray has an associated data type (dtype) object. This data type object (dtype) provides information about the layout of the array. The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes which can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be used to construct arrays. At the time of Array creation, Numpy tries to guess a datatype, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype." }, { "code": null, "e": 44998, "s": 44776, "text": "Constructing a Datatype ObjectIn Numpy, datatypes of Arrays need not to be defined unless a specific datatype is required. Numpy tries to guess the datatype for Arrays which are not predefined in the constructor function." }, { "code": null, "e": 45006, "s": 44998, "text": "Output:" }, { "code": null, "e": 45086, "s": 45006, "text": "Integer Datatype: \nint64\n\nFloat Datatype: \nfloat64\n\nForcing a Datatype: \nint64\n" }, { "code": null, "e": 45444, "s": 45086, "text": " Math Operations on DataType arrayIn Numpy arrays, basic mathematical operations are performed element-wise on the array. These operations are applied both as operator overloads and as functions. Many useful functions are provided in Numpy for performing computations on Arrays such as sum: for addition of Array elements, T: for Transpose of elements, etc." }, { "code": null, "e": 45452, "s": 45444, "text": "Output:" }, { "code": null, "e": 45662, "s": 45452, "text": "Addition of Two Arrays: \n[[ 7. 13.]\n [ 4. 14.]]\n\nAddition of Array elements: \n19.0\n\nSquare root of Array1 elements: \n[[2. 2.64575131]\n [1.41421356 2.44948974]]\n\nTranspose of Array: \n[[4. 2.]\n [7. 6.]]\n" }, { "code": null, "e": 45687, "s": 45662, "text": " More on Numpy Data Type" }, { "code": null, "e": 45721, "s": 45687, "text": "Data type Object (dtype) in NumPy" }, { "code": null, "e": 45739, "s": 45721, "text": "Programs on Numpy" }, { "code": null, "e": 45785, "s": 45739, "text": "Python | Check whether a list is empty or not" }, { "code": null, "e": 45824, "s": 45785, "text": "Python | Get unique values from a list" }, { "code": null, "e": 45885, "s": 45824, "text": "Python | Multiply all numbers in the list (3 different ways)" }, { "code": null, "e": 45929, "s": 45885, "text": "Transpose a matrix in Single line in Python" }, { "code": null, "e": 45997, "s": 45929, "text": "Multiplication of two Matrices in Single line using Numpy in Python" }, { "code": null, "e": 46061, "s": 45997, "text": "Python program to print checkerboard pattern of nxn using numpy" }, { "code": null, "e": 46108, "s": 46061, "text": "Graph Plotting in Python | Set 1, Set 2, Set 3" }, { "code": null, "e": 46130, "s": 46108, "text": "Useful Numpy Articles" }, { "code": null, "e": 46160, "s": 46130, "text": "Matrix manipulation in Python" }, { "code": null, "e": 46212, "s": 46160, "text": "Basic Slicing and Advanced Indexing in NumPy Python" }, { "code": null, "e": 46254, "s": 46212, "text": "Differences between Flatten() and Ravel()" }, { "code": null, "e": 46295, "s": 46254, "text": "rand vs normal in Numpy.random in Python" }, { "code": null, "e": 46393, "s": 46295, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 46402, "s": 46393, "text": "Comments" }, { "code": null, "e": 46415, "s": 46402, "text": "Old Comments" }, { "code": null, "e": 46474, "s": 46415, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 46506, "s": 46474, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 46559, "s": 46506, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 46597, "s": 46559, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 46647, "s": 46597, "text": "C++ Program For Inserting A Node In A Linked List" }, { "code": null, "e": 46700, "s": 46647, "text": "Python Program For Inserting A Node In A Linked List" }, { "code": null, "e": 46750, "s": 46700, "text": "Implementation of Bit Stuffing and Bit Destuffing" }, { "code": null, "e": 46792, "s": 46750, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 46818, "s": 46792, "text": "Tailwind CSS vs Bootstrap" } ]
Erlang - Processes
The granularity of concurrency in Erlang is a process. A process is an activity/task that runs concurrently with and is independent from the other processes. These processes in Erlang are different than the processes and threads most people are familiar with. Erlang processes are lightweight, operate in (memory) isolation from other processes, and are scheduled by Erlang’s Virtual Machine (VM). The creation time of process is very low, the memory footprint of a just spawned process is very small, and a single Erlang VM can have millions of processes running. A process is created with the help of the spawn method. The general syntax of the method is given below. spawn(Module, Name, Args) Module − This is a predefined atom value which must be ?MODULE. Module − This is a predefined atom value which must be ?MODULE. Name − This is the name of the function to be called when the process is defined. Name − This is the name of the function to be called when the process is defined. Args − These are the arguments which need to be sent to the function. Args − These are the arguments which need to be sent to the function. Returns the process id of the new process created. An example of the spawn method is shown in the following program. -module(helloworld). -export([start/0, call/2]). call(Arg1, Arg2) -> io:format("~p ~p~n", [Arg1, Arg2]). start() -> Pid = spawn(?MODULE, call, ["hello", "process"]), io:fwrite("~p",[Pid]). The following things need to be noted about the above program. A function called call is defined and will be used to create the process. A function called call is defined and will be used to create the process. The spawn method calls the call function with the parameters hello and process. The spawn method calls the call function with the parameters hello and process. When we run the above program we will get the following result. <0.29.0>"hello" "process" Now let’s look at the other functions which are available with processes. is_pid This method is used to determine if a process id exists. is_process_alive This is called as is_process_alive(Pid). A Pid must refer to a process at the local node. pid_to_list It converts a process id to a list. registered Returns a list with the names of all registered processes. self One of the most commonly used BIF, returns the pid of the calling processes. register This is used to register a process in the system. whereis It is called as whereis(Name). Returns the pid of the process that is registered with the name. unregister This is used to unregister a process in the system. Print Add Notes Bookmark this page
[ { "code": null, "e": 2866, "s": 2301, "text": "The granularity of concurrency in Erlang is a process. A process is an activity/task that runs concurrently with and is independent from the other processes. These processes in Erlang are different than the processes and threads most people are familiar with. Erlang processes are lightweight, operate in (memory) isolation from other processes, and are scheduled by Erlang’s Virtual Machine (VM). The creation time of process is very low, the memory footprint of a just spawned process is very small, and a single Erlang VM can have millions of processes running." }, { "code": null, "e": 2971, "s": 2866, "text": "A process is created with the help of the spawn method. The general syntax of the method is given below." }, { "code": null, "e": 2998, "s": 2971, "text": "spawn(Module, Name, Args)\n" }, { "code": null, "e": 3062, "s": 2998, "text": "Module − This is a predefined atom value which must be ?MODULE." }, { "code": null, "e": 3126, "s": 3062, "text": "Module − This is a predefined atom value which must be ?MODULE." }, { "code": null, "e": 3208, "s": 3126, "text": "Name − This is the name of the function to be called when the process is defined." }, { "code": null, "e": 3290, "s": 3208, "text": "Name − This is the name of the function to be called when the process is defined." }, { "code": null, "e": 3360, "s": 3290, "text": "Args − These are the arguments which need to be sent to the function." }, { "code": null, "e": 3430, "s": 3360, "text": "Args − These are the arguments which need to be sent to the function." }, { "code": null, "e": 3481, "s": 3430, "text": "Returns the process id of the new process created." }, { "code": null, "e": 3547, "s": 3481, "text": "An example of the spawn method is shown in the following program." }, { "code": null, "e": 3752, "s": 3547, "text": "-module(helloworld). \n-export([start/0, call/2]). \n\ncall(Arg1, Arg2) -> \n io:format(\"~p ~p~n\", [Arg1, Arg2]). \nstart() -> \n Pid = spawn(?MODULE, call, [\"hello\", \"process\"]), \n io:fwrite(\"~p\",[Pid])." }, { "code": null, "e": 3815, "s": 3752, "text": "The following things need to be noted about the above program." }, { "code": null, "e": 3889, "s": 3815, "text": "A function called call is defined and will be used to create the process." }, { "code": null, "e": 3963, "s": 3889, "text": "A function called call is defined and will be used to create the process." }, { "code": null, "e": 4043, "s": 3963, "text": "The spawn method calls the call function with the parameters hello and process." }, { "code": null, "e": 4123, "s": 4043, "text": "The spawn method calls the call function with the parameters hello and process." }, { "code": null, "e": 4187, "s": 4123, "text": "When we run the above program we will get the following result." }, { "code": null, "e": 4214, "s": 4187, "text": "<0.29.0>\"hello\" \"process\"\n" }, { "code": null, "e": 4288, "s": 4214, "text": "Now let’s look at the other functions which are available with processes." }, { "code": null, "e": 4295, "s": 4288, "text": "is_pid" }, { "code": null, "e": 4352, "s": 4295, "text": "This method is used to determine if a process id exists." }, { "code": null, "e": 4369, "s": 4352, "text": "is_process_alive" }, { "code": null, "e": 4459, "s": 4369, "text": "This is called as is_process_alive(Pid). A Pid must refer to a process at the local node." }, { "code": null, "e": 4471, "s": 4459, "text": "pid_to_list" }, { "code": null, "e": 4507, "s": 4471, "text": "It converts a process id to a list." }, { "code": null, "e": 4518, "s": 4507, "text": "registered" }, { "code": null, "e": 4577, "s": 4518, "text": "Returns a list with the names of all registered processes." }, { "code": null, "e": 4582, "s": 4577, "text": "self" }, { "code": null, "e": 4659, "s": 4582, "text": "One of the most commonly used BIF, returns the pid of the calling processes." }, { "code": null, "e": 4668, "s": 4659, "text": "register" }, { "code": null, "e": 4718, "s": 4668, "text": "This is used to register a process in the system." }, { "code": null, "e": 4726, "s": 4718, "text": "whereis" }, { "code": null, "e": 4822, "s": 4726, "text": "It is called as whereis(Name). Returns the pid of the process that is registered with the name." }, { "code": null, "e": 4833, "s": 4822, "text": "unregister" }, { "code": null, "e": 4885, "s": 4833, "text": "This is used to unregister a process in the system." }, { "code": null, "e": 4892, "s": 4885, "text": " Print" }, { "code": null, "e": 4903, "s": 4892, "text": " Add Notes" } ]
Power of Four | Practice | GeeksforGeeks
Given a number N, check if N is power of 4 or not. Example 1: Input: N = 64 Output: 1 Explanation: 43= 64 Example 2: Input: N = 75 Output : 0 Explanation : 75 is not a power of 4. +1 princejee20191 month ago C++ || 0ms || Recursive Solution|| Easy to Understand int isPowerOfFour(unsigned int n){ if(n<1)return 0; if(n==1)return 1; if(n%4!=0)return 0; return isPowerOfFour(n/4); } // Like wise you can find any number power ...like power of 3,power of 5,power of any number !! IT's cool na !! HAPPY CODING !! 0 aniketag7871 month ago class Solution{ int isPowerOfFour(long n) {// Your code herefor(int i = 0; i < 31; i++){ double ans = Math.pow(4,i); if(ans == n){ return 1; }}return 0; }} +1 princejee20192 months ago C++ Code || Easy To Understand int isPowerOfFour(unsigned int n){ if(n==1){ return 1; } int a =1; for(int i =2;i<16;i++){ if(n==a){ return 1; } a =a*4; } return 0; } 0 abhinav72903 months ago int isPowerOfFour(unsigned int n) { long long int a[15]; a[0]=1; for(int i=1;i<15;i++) { a[i] = a[i-1] *4; } for(int i=0;i<15;i++) { if(a[i]==n) return 1; } return 0; } 0 sahuprashant294 months ago int isPowerOfFour(long n) { if(n==0)return 0; if((n&(n-1))==0 && (int)(Math.log(n)/Math.log(2))%2==0)return 1; return 0; } +1 skp915137 months ago Time complexity less than o(n) 95 % of the cases we won't go in the while loop. class Solution{ public: int isPowerOfFour(unsigned int n) { // Your code goes here if(n==4 || n ==1) return 1 ; if(n==2 || n ==3) return 0 ; if(n%2!=0) return 0 ; if(n%4!=0) return 0 ; if(n%8!=0) return 0 ; if(n%10 == 4 || n%10 == 6 ){ while(n!=0){ if(n==4) return 1; if(n %4 !=0) return 0 ; n = n/4; } return 1 ; } else return 0 ; }}; -2 amonk7 months ago int isPowerOfFour(unsigned int n) { if(n==0){ return 0; } if(floor(log(n)/log(4)) == ceil(log(n)/log(4))){ return 1; }return 0; } 0 Sawi Sharma1 year ago Sawi Sharma Python3 solusann: def isPowerofFour(self, n): # code here self.temp=1 if n==1: return 1 while self.temp<=n: if self.temp==n: return 1 else: self.temp*=4 return 0 0 Annanya Mathur1 year ago Annanya Mathur int isPowerOfFour(unsigned int n){int z=0,a=0; if(n==1) return 1; while(n) { if(n&1) a++; else z++; n=n>>1; } if(a==1 && z%2==0) return 1; else return 0;} 0 Yash Patil2 years ago Yash Patil double val=(Math.log10(n)/Math.log10(4));int res=(int)val;if(val==res){ return 1;} return 0; 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": 277, "s": 226, "text": "Given a number N, check if N is power of 4 or not." }, { "code": null, "e": 288, "s": 277, "text": "Example 1:" }, { "code": null, "e": 333, "s": 288, "text": "Input: \nN = 64\nOutput: 1\nExplanation:\n43= 64" }, { "code": null, "e": 344, "s": 333, "text": "Example 2:" }, { "code": null, "e": 408, "s": 344, "text": "Input: \nN = 75\nOutput : 0\nExplanation :\n75 is not a power of 4." }, { "code": null, "e": 411, "s": 408, "text": "+1" }, { "code": null, "e": 436, "s": 411, "text": "princejee20191 month ago" }, { "code": null, "e": 491, "s": 436, "text": "C++ || 0ms || Recursive Solution|| Easy to Understand " }, { "code": null, "e": 632, "s": 491, "text": " int isPowerOfFour(unsigned int n){ if(n<1)return 0; if(n==1)return 1; if(n%4!=0)return 0; return isPowerOfFour(n/4); }" }, { "code": null, "e": 732, "s": 632, "text": " // Like wise you can find any number power ...like power of 3,power of 5,power of any number !!" }, { "code": null, "e": 765, "s": 732, "text": "IT's cool na !! HAPPY CODING !!" }, { "code": null, "e": 767, "s": 765, "text": "0" }, { "code": null, "e": 790, "s": 767, "text": "aniketag7871 month ago" }, { "code": null, "e": 976, "s": 790, "text": "class Solution{ int isPowerOfFour(long n) {// Your code herefor(int i = 0; i < 31; i++){ double ans = Math.pow(4,i); if(ans == n){ return 1; }}return 0; }}" }, { "code": null, "e": 979, "s": 976, "text": "+1" }, { "code": null, "e": 1005, "s": 979, "text": "princejee20192 months ago" }, { "code": null, "e": 1036, "s": 1005, "text": "C++ Code || Easy To Understand" }, { "code": null, "e": 1243, "s": 1036, "text": " int isPowerOfFour(unsigned int n){ if(n==1){ return 1; } int a =1; for(int i =2;i<16;i++){ if(n==a){ return 1; } a =a*4; } return 0; }" }, { "code": null, "e": 1245, "s": 1243, "text": "0" }, { "code": null, "e": 1269, "s": 1245, "text": "abhinav72903 months ago" }, { "code": null, "e": 1524, "s": 1269, "text": "int isPowerOfFour(unsigned int n) { long long int a[15]; a[0]=1; for(int i=1;i<15;i++) { a[i] = a[i-1] *4; } for(int i=0;i<15;i++) { if(a[i]==n) return 1; } return 0; }" }, { "code": null, "e": 1526, "s": 1524, "text": "0" }, { "code": null, "e": 1553, "s": 1526, "text": "sahuprashant294 months ago" }, { "code": null, "e": 1693, "s": 1553, "text": "int isPowerOfFour(long n) { if(n==0)return 0; if((n&(n-1))==0 && (int)(Math.log(n)/Math.log(2))%2==0)return 1; return 0; }" }, { "code": null, "e": 1696, "s": 1693, "text": "+1" }, { "code": null, "e": 1717, "s": 1696, "text": "skp915137 months ago" }, { "code": null, "e": 1750, "s": 1719, "text": "Time complexity less than o(n)" }, { "code": null, "e": 1799, "s": 1750, "text": "95 % of the cases we won't go in the while loop." }, { "code": null, "e": 2276, "s": 1799, "text": "class Solution{ public: int isPowerOfFour(unsigned int n) { // Your code goes here if(n==4 || n ==1) return 1 ; if(n==2 || n ==3) return 0 ; if(n%2!=0) return 0 ; if(n%4!=0) return 0 ; if(n%8!=0) return 0 ; if(n%10 == 4 || n%10 == 6 ){ while(n!=0){ if(n==4) return 1; if(n %4 !=0) return 0 ; n = n/4; } return 1 ; } else return 0 ; }};" }, { "code": null, "e": 2281, "s": 2278, "text": "-2" }, { "code": null, "e": 2299, "s": 2281, "text": "amonk7 months ago" }, { "code": null, "e": 2477, "s": 2299, "text": "int isPowerOfFour(unsigned int n) { if(n==0){ return 0; } if(floor(log(n)/log(4)) == ceil(log(n)/log(4))){ return 1; }return 0; }" }, { "code": null, "e": 2479, "s": 2477, "text": "0" }, { "code": null, "e": 2501, "s": 2479, "text": "Sawi Sharma1 year ago" }, { "code": null, "e": 2513, "s": 2501, "text": "Sawi Sharma" }, { "code": null, "e": 2531, "s": 2513, "text": "Python3 solusann:" }, { "code": null, "e": 2773, "s": 2531, "text": "def isPowerofFour(self, n): # code here self.temp=1 if n==1: return 1 while self.temp<=n: if self.temp==n: return 1 else: self.temp*=4 return 0" }, { "code": null, "e": 2775, "s": 2773, "text": "0" }, { "code": null, "e": 2800, "s": 2775, "text": "Annanya Mathur1 year ago" }, { "code": null, "e": 2815, "s": 2800, "text": "Annanya Mathur" }, { "code": null, "e": 3004, "s": 2815, "text": "int isPowerOfFour(unsigned int n){int z=0,a=0; if(n==1) return 1; while(n) { if(n&1) a++; else z++; n=n>>1; } if(a==1 && z%2==0) return 1; else return 0;}" }, { "code": null, "e": 3006, "s": 3004, "text": "0" }, { "code": null, "e": 3028, "s": 3006, "text": "Yash Patil2 years ago" }, { "code": null, "e": 3039, "s": 3028, "text": "Yash Patil" }, { "code": null, "e": 3125, "s": 3039, "text": "double val=(Math.log10(n)/Math.log10(4));int res=(int)val;if(val==res){ return 1;}" }, { "code": null, "e": 3138, "s": 3125, "text": " return 0;" }, { "code": null, "e": 3284, "s": 3138, "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": 3320, "s": 3284, "text": " Login to access your submissions. " }, { "code": null, "e": 3330, "s": 3320, "text": "\nProblem\n" }, { "code": null, "e": 3340, "s": 3330, "text": "\nContest\n" }, { "code": null, "e": 3403, "s": 3340, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3551, "s": 3403, "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": 3759, "s": 3551, "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": 3865, "s": 3759, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Ultimate Pandas Guide: Time Series Window Functions | by Skyler Dale | Towards Data Science
In my last post, I walked through how to run window functions in Pandas based on column values. This approach is useful anytime we want to know information about both the individual records and the groups they belong to. For example, if we have customer-level transaction data, an approach like this can provide us with information about each individual transaction, as well as the total sales during the month in which it took place: In this post, I’ll walk through another type of the window function — one where we perform our calculation based on the position of the rows, rather than the values of a categorical column. For my examples below, I’ll work with some game-level basketball data from the NCAA ML competition on Kaggle. If basketball is not your thing, fear not. Here is a quick data dictionary that tells you all you need to know about the variables: DayNum: Our measure of time. It counts how many days into the season the game occurred.Season: The year the game took place.Team1/Team2: The IDs of the teams that played in the game.Efficiency: A measure of how well Team1 performed in the game.Outcome: Flag for whether or not Team1 won the game (1 is win, 0 is loss). DayNum: Our measure of time. It counts how many days into the season the game occurred. Season: The year the game took place. Team1/Team2: The IDs of the teams that played in the game. Efficiency: A measure of how well Team1 performed in the game. Outcome: Flag for whether or not Team1 won the game (1 is win, 0 is loss). Finally, let’s assume our goal is to predict who won each game. We won’t do any machine learning here, but this will help motivate the use cases. Let’s start by doing a simple “shift.” This method does exactly what it sounds like. It shifts the values in a column either forward or backwards. Below we shift the GameEfficiency by 1: game_data[‘prior_game_outcome’] = game_data[‘Outcome’].shift(1) Now — for each game — we know how well Team1 did in the prior game. Perhaps this could help us predict the outcome. Note that we can pass either positive or negative integers to shift forward or backwards: game_data['NextEfficiency'] = game_data['GameEfficiency'].shift(-1) Also keep in mind that when we do a positive shift on the first row we get a null value because there is no available data in the preceding one. We can address this by setting the “fill_value” parameter to replace the null with a different value of our choice. While the shift method is useful, it doesn’t allow us to perform any functions on the prior or future rows. For example, we might want to find the average efficiency of Team1 over the prior three games. This is where we can leverage the rolling method. The basic syntax is pretty simple — we just need to pass the number of prior rows we want to look at and then perform an aggregation: game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].rolling(3).mean() Note that there are technically two steps here: the “rolling” method creates a Rolling object, and then the “mean” method returns the new column. We probably want to make one more adjustment here. By default, each record gets included in its own window average. If we want to predict each game, this is bad because it means we have information about the outcome encoded in the average. To solve this, we can add a shift function so that the data from previous 3 rows is included (rather than the current row and the prior 2): game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1).rolling(3).mean() The expanding method is very similar to the rolling method, except that it creates as large of window as it can given the data. Here’s an example: game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1).expanding().mean() Note that the AvgEfficiency value in the second to last row is the same as when we ran the rolling method above (12.02), but the last rows are different (2.41 vs. 13.46). That’s because when we’re at the second to last row, we only have 3 prior records available, but when we reach the last row we have 4 prior records. Again, the expanding method uses as much of the data as possible. Finally, we can use the “min_periods” parameter if we want to make sure that our expanding window has at least a certain number of records in order for the aggregation to be applied: game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1) .expanding(min_periods = 4).mean() We started off this post by differentiating between column-based windowing and position-based windowing. Our final use case leverages both. Here’s the problem with all of the work above: we actually have multiple teams and seasons in our dataset, so we run into issues at the edges of our sorted data: In order to resolve this, we need to split our data up into groups of Team/Season and perform an expanding window aggregation: game_data[‘AvgEfficiency’] = game_data.groupby([‘Season’, ‘Team1’])[[‘GameEfficiency’]].transform(lambda x: x.shift(1).expanding().mean()) Now our expanding average calculation starts fresh for each team’s schedule! There’s a lot going on in the code above, but here’s how I would think about it: First we split our data up into groups of Season and Team1Then we apply a custom anonymous function (lambda) to each group which shifts the data and calculates an expanding meanFinally we return these values back to the original index First we split our data up into groups of Season and Team1 Then we apply a custom anonymous function (lambda) to each group which shifts the data and calculates an expanding mean Finally we return these values back to the original index In this post we walked through time series window functions in Pandas. The syntax for some of these methods can be a bit tricky, but when you break it down into smaller steps everything becomes a little more clear. It also doesn’t hurt to spend some time playing around with each method until you get the hang of it. Happy coding!
[ { "code": null, "e": 267, "s": 171, "text": "In my last post, I walked through how to run window functions in Pandas based on column values." }, { "code": null, "e": 392, "s": 267, "text": "This approach is useful anytime we want to know information about both the individual records and the groups they belong to." }, { "code": null, "e": 606, "s": 392, "text": "For example, if we have customer-level transaction data, an approach like this can provide us with information about each individual transaction, as well as the total sales during the month in which it took place:" }, { "code": null, "e": 796, "s": 606, "text": "In this post, I’ll walk through another type of the window function — one where we perform our calculation based on the position of the rows, rather than the values of a categorical column." }, { "code": null, "e": 906, "s": 796, "text": "For my examples below, I’ll work with some game-level basketball data from the NCAA ML competition on Kaggle." }, { "code": null, "e": 949, "s": 906, "text": "If basketball is not your thing, fear not." }, { "code": null, "e": 1038, "s": 949, "text": "Here is a quick data dictionary that tells you all you need to know about the variables:" }, { "code": null, "e": 1357, "s": 1038, "text": "DayNum: Our measure of time. It counts how many days into the season the game occurred.Season: The year the game took place.Team1/Team2: The IDs of the teams that played in the game.Efficiency: A measure of how well Team1 performed in the game.Outcome: Flag for whether or not Team1 won the game (1 is win, 0 is loss)." }, { "code": null, "e": 1445, "s": 1357, "text": "DayNum: Our measure of time. It counts how many days into the season the game occurred." }, { "code": null, "e": 1483, "s": 1445, "text": "Season: The year the game took place." }, { "code": null, "e": 1542, "s": 1483, "text": "Team1/Team2: The IDs of the teams that played in the game." }, { "code": null, "e": 1605, "s": 1542, "text": "Efficiency: A measure of how well Team1 performed in the game." }, { "code": null, "e": 1680, "s": 1605, "text": "Outcome: Flag for whether or not Team1 won the game (1 is win, 0 is loss)." }, { "code": null, "e": 1826, "s": 1680, "text": "Finally, let’s assume our goal is to predict who won each game. We won’t do any machine learning here, but this will help motivate the use cases." }, { "code": null, "e": 1865, "s": 1826, "text": "Let’s start by doing a simple “shift.”" }, { "code": null, "e": 1973, "s": 1865, "text": "This method does exactly what it sounds like. It shifts the values in a column either forward or backwards." }, { "code": null, "e": 2013, "s": 1973, "text": "Below we shift the GameEfficiency by 1:" }, { "code": null, "e": 2077, "s": 2013, "text": "game_data[‘prior_game_outcome’] = game_data[‘Outcome’].shift(1)" }, { "code": null, "e": 2193, "s": 2077, "text": "Now — for each game — we know how well Team1 did in the prior game. Perhaps this could help us predict the outcome." }, { "code": null, "e": 2283, "s": 2193, "text": "Note that we can pass either positive or negative integers to shift forward or backwards:" }, { "code": null, "e": 2351, "s": 2283, "text": "game_data['NextEfficiency'] = game_data['GameEfficiency'].shift(-1)" }, { "code": null, "e": 2612, "s": 2351, "text": "Also keep in mind that when we do a positive shift on the first row we get a null value because there is no available data in the preceding one. We can address this by setting the “fill_value” parameter to replace the null with a different value of our choice." }, { "code": null, "e": 2720, "s": 2612, "text": "While the shift method is useful, it doesn’t allow us to perform any functions on the prior or future rows." }, { "code": null, "e": 2815, "s": 2720, "text": "For example, we might want to find the average efficiency of Team1 over the prior three games." }, { "code": null, "e": 2865, "s": 2815, "text": "This is where we can leverage the rolling method." }, { "code": null, "e": 2999, "s": 2865, "text": "The basic syntax is pretty simple — we just need to pass the number of prior rows we want to look at and then perform an aggregation:" }, { "code": null, "e": 3074, "s": 2999, "text": "game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].rolling(3).mean()" }, { "code": null, "e": 3220, "s": 3074, "text": "Note that there are technically two steps here: the “rolling” method creates a Rolling object, and then the “mean” method returns the new column." }, { "code": null, "e": 3460, "s": 3220, "text": "We probably want to make one more adjustment here. By default, each record gets included in its own window average. If we want to predict each game, this is bad because it means we have information about the outcome encoded in the average." }, { "code": null, "e": 3600, "s": 3460, "text": "To solve this, we can add a shift function so that the data from previous 3 rows is included (rather than the current row and the prior 2):" }, { "code": null, "e": 3684, "s": 3600, "text": "game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1).rolling(3).mean()" }, { "code": null, "e": 3812, "s": 3684, "text": "The expanding method is very similar to the rolling method, except that it creates as large of window as it can given the data." }, { "code": null, "e": 3831, "s": 3812, "text": "Here’s an example:" }, { "code": null, "e": 3916, "s": 3831, "text": "game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1).expanding().mean()" }, { "code": null, "e": 4087, "s": 3916, "text": "Note that the AvgEfficiency value in the second to last row is the same as when we ran the rolling method above (12.02), but the last rows are different (2.41 vs. 13.46)." }, { "code": null, "e": 4302, "s": 4087, "text": "That’s because when we’re at the second to last row, we only have 3 prior records available, but when we reach the last row we have 4 prior records. Again, the expanding method uses as much of the data as possible." }, { "code": null, "e": 4485, "s": 4302, "text": "Finally, we can use the “min_periods” parameter if we want to make sure that our expanding window has at least a certain number of records in order for the aggregation to be applied:" }, { "code": null, "e": 4586, "s": 4485, "text": "game_data[‘AvgEfficiency’] = game_data[‘GameEfficiency’].shift(1) .expanding(min_periods = 4).mean()" }, { "code": null, "e": 4691, "s": 4586, "text": "We started off this post by differentiating between column-based windowing and position-based windowing." }, { "code": null, "e": 4726, "s": 4691, "text": "Our final use case leverages both." }, { "code": null, "e": 4888, "s": 4726, "text": "Here’s the problem with all of the work above: we actually have multiple teams and seasons in our dataset, so we run into issues at the edges of our sorted data:" }, { "code": null, "e": 5015, "s": 4888, "text": "In order to resolve this, we need to split our data up into groups of Team/Season and perform an expanding window aggregation:" }, { "code": null, "e": 5154, "s": 5015, "text": "game_data[‘AvgEfficiency’] = game_data.groupby([‘Season’, ‘Team1’])[[‘GameEfficiency’]].transform(lambda x: x.shift(1).expanding().mean())" }, { "code": null, "e": 5231, "s": 5154, "text": "Now our expanding average calculation starts fresh for each team’s schedule!" }, { "code": null, "e": 5312, "s": 5231, "text": "There’s a lot going on in the code above, but here’s how I would think about it:" }, { "code": null, "e": 5547, "s": 5312, "text": "First we split our data up into groups of Season and Team1Then we apply a custom anonymous function (lambda) to each group which shifts the data and calculates an expanding meanFinally we return these values back to the original index" }, { "code": null, "e": 5606, "s": 5547, "text": "First we split our data up into groups of Season and Team1" }, { "code": null, "e": 5726, "s": 5606, "text": "Then we apply a custom anonymous function (lambda) to each group which shifts the data and calculates an expanding mean" }, { "code": null, "e": 5784, "s": 5726, "text": "Finally we return these values back to the original index" } ]
Student of the Year | Practice | GeeksforGeeks
Given a vector containing name of N student (in lowercase letters) and their marks in an exam. The task is to sort the students with respect to their marks (student with highest marks will be on top). If marks are same, consider lexicographic sorting for names. Example 1: Input: N = 4 michal 56 john 100 abbas 98 jordan 45 Output: john 100 abbas 98 michal 56 jordan 45 Explanation: Marks of students in decreasing order is as 100, 98, 56, 45. So, their names are as john 100, abbas 98, michal 56, jordan 45. Your Task: Since this is a function problem, you don't need to take any input. You just need to complete the provided function sortMarks(). Output the name of students with their marks in decreasing order, each student in new line. Constraints: 1 <= N <= 106 1 <= marks <= 106 0 hgaur7013 days ago Using lambda function : vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N) { sort(v.begin(), v.end(), [](pair<string, int> p1, pair<string, int> p2) { if(p1.second == p2.second) return (p1.first < p2.first); else return (p1.second > p2.second); }); return v; } +2 hermione2673 months ago bool cmp(pair<string,int> a, pair<string,int > b){ if(a.second == b.second){ return a.first < b.first; } else return a.second > b.second;}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ sort(v.begin(), v.end(), cmp); return v; } 0 karntiwari3 months ago CPP: bool mycomparision(pair<string,int>a,pair<string,int>b){ if(a.second>b.second)// comparision btw number if number is greater than return true { return true; } else if(a.second==b.second)// if number is same { if(a.first<b.first) // then comparision in string { return true; } // comparision btw string according to alphabatical order in which string is smaller than return true else { return false; } } return false;}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ sort(v.begin(),v.end(),mycomparision);// called comparision function return v; //Complete the code and return the sorted vector} 0 aakritiashi4 months ago #include<bits/stdc++.h>#include<iostream>using namespace std; bool sortbysec(const pair<string,int> &a, const pair<string,int> &b){ return (a.second > b.second);} int main(){ vector<pair<string,int>>v; int n; cout<<"enter no. of students: "; cin>>n; for(int i=0 ; i<n ; i++) { string s; int x; cin>>s>>x; v.push_back({s,x}); } for(int i=0; i<v.size(); i++) { cout<<v[i].first<<" "<<v[i].second<<endl; } cout<<"student of the year is "<<endl; sort(v.begin(),v.end(),sortbysec); for(int i=0; i<v.size(); i++) { cout<<v[i].first<<" "<<v[i].second<<endl; } } 0 dreamvivek65 months ago bool mycomp(pair<string,int> a,pair<string,int> b){ if(a.second>b.second) return true; else if(a.second<b.second) return false; else { if(a.first<b.first) return true; else return false; }}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ //Complete the code and return the sorted vector sort(v.begin(),v.end(),mycomp); return v;} +2 badgujarsachin837 months ago bool fun(pair<string,int> a1,pair<string,int> a2){ if(a1.second>a2.second){ return 1; }else if(a1.second==a2.second){ if(a1.first<a2.first){ return 1; }else{ return 0; } } return 0; } vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ //Complete the code and return the sorted vector sort(v.begin(),v.end(),fun); return v; } 0 noobcoderdj8 months ago noobcoderdj c++ two liner vector<pair<string, int="">> sortMarks(vector<pair<string, int="">> v, int N){ sort(v.begin(), v.end(), [](pair<string, int=""> a, pair<string, int=""> b){ if(a.second == b.second) return a.first<b.first; return="" a.second="">b.second; }); return v;} 0 mscodi1 year ago mscodi bool cmp_by_sec(pair<string, int=""> p1, pair<string, int=""> p2){ if(p1.second > p2.second) { return 1; } else if(p1.second == p2.second) { if(p1.first < p2.first) { return 1; } else { return 0; } } return 0;}vector<pair<string, int="">> sortMarks(vector<pair<string, int="">> v, int N){ sort(v.begin(), v.end(),cmp_by_sec); return v; 0 fnxl This comment was deleted. 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.20 bool myCmp(pair<string, int=""> p1, pair<string, int=""> p2){ if(p1.second > p2.second) { return 1; } else if(p1.second == p2.second) { if(p1.first < p2.first) { return 1; } else { return 0; } } return 0;}vector<pair<string, int="">> sortMarks(vector<pair<string, int="">> v, int N){ sort(v.begin(), v.end(), myCmp); return v;} 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": 488, "s": 226, "text": "Given a vector containing name of N student (in lowercase letters) and their marks in an exam. The task is to sort the students with respect to their marks (student with highest marks will be on top). If marks are same, consider lexicographic sorting for names." }, { "code": null, "e": 738, "s": 488, "text": "Example 1: \nInput:\nN = 4\nmichal 56\njohn 100\nabbas 98\njordan 45\nOutput: \njohn 100\nabbas 98\nmichal 56\njordan 45\nExplanation:\nMarks of students in decreasing order is\nas 100, 98, 56, 45. So, their names are\nas john 100, abbas 98, michal 56, jordan 45.\n" }, { "code": null, "e": 970, "s": 738, "text": "Your Task:\nSince this is a function problem, you don't need to take any input. You just need to complete the provided function sortMarks(). Output the name of students with their marks in decreasing order, each student in new line." }, { "code": null, "e": 1015, "s": 970, "text": "Constraints:\n1 <= N <= 106\n1 <= marks <= 106" }, { "code": null, "e": 1017, "s": 1015, "text": "0" }, { "code": null, "e": 1036, "s": 1017, "text": "hgaur7013 days ago" }, { "code": null, "e": 1060, "s": 1036, "text": "Using lambda function :" }, { "code": null, "e": 1346, "s": 1060, "text": "vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N)\n{\n sort(v.begin(), v.end(), [](pair<string, int> p1, pair<string, int> p2)\n {\n if(p1.second == p2.second) return (p1.first < p2.first);\n else return (p1.second > p2.second); });\n\nreturn v;\n}" }, { "code": null, "e": 1349, "s": 1346, "text": "+2" }, { "code": null, "e": 1373, "s": 1349, "text": "hermione2673 months ago" }, { "code": null, "e": 1649, "s": 1373, "text": "bool cmp(pair<string,int> a, pair<string,int > b){ if(a.second == b.second){ return a.first < b.first; } else return a.second > b.second;}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ sort(v.begin(), v.end(), cmp); return v; }" }, { "code": null, "e": 1651, "s": 1649, "text": "0" }, { "code": null, "e": 1674, "s": 1651, "text": "karntiwari3 months ago" }, { "code": null, "e": 1679, "s": 1674, "text": "CPP:" }, { "code": null, "e": 2402, "s": 1679, "text": "bool mycomparision(pair<string,int>a,pair<string,int>b){ if(a.second>b.second)// comparision btw number if number is greater than return true { return true; } else if(a.second==b.second)// if number is same { if(a.first<b.first) // then comparision in string { return true; } // comparision btw string according to alphabatical order in which string is smaller than return true else { return false; } } return false;}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ sort(v.begin(),v.end(),mycomparision);// called comparision function return v; //Complete the code and return the sorted vector}" }, { "code": null, "e": 2404, "s": 2402, "text": "0" }, { "code": null, "e": 2428, "s": 2404, "text": "aakritiashi4 months ago" }, { "code": null, "e": 2490, "s": 2428, "text": "#include<bits/stdc++.h>#include<iostream>using namespace std;" }, { "code": null, "e": 2605, "s": 2490, "text": "bool sortbysec(const pair<string,int> &a, const pair<string,int> &b){ return (a.second > b.second);}" }, { "code": null, "e": 3079, "s": 2605, "text": "int main(){ vector<pair<string,int>>v; int n; cout<<\"enter no. of students: \"; cin>>n; for(int i=0 ; i<n ; i++) { string s; int x; cin>>s>>x; v.push_back({s,x}); } for(int i=0; i<v.size(); i++) { cout<<v[i].first<<\" \"<<v[i].second<<endl; } cout<<\"student of the year is \"<<endl; sort(v.begin(),v.end(),sortbysec); for(int i=0; i<v.size(); i++) { cout<<v[i].first<<\" \"<<v[i].second<<endl; }" }, { "code": null, "e": 3082, "s": 3079, "text": "} " }, { "code": null, "e": 3084, "s": 3082, "text": "0" }, { "code": null, "e": 3108, "s": 3084, "text": "dreamvivek65 months ago" }, { "code": null, "e": 3488, "s": 3108, "text": "bool mycomp(pair<string,int> a,pair<string,int> b){ if(a.second>b.second) return true; else if(a.second<b.second) return false; else { if(a.first<b.first) return true; else return false; }}vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){ //Complete the code and return the sorted vector sort(v.begin(),v.end(),mycomp); return v;}" }, { "code": null, "e": 3491, "s": 3488, "text": "+2" }, { "code": null, "e": 3520, "s": 3491, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 3965, "s": 3520, "text": "bool fun(pair<string,int> a1,pair<string,int> a2){\n if(a1.second>a2.second){\n return 1;\n }else if(a1.second==a2.second){\n if(a1.first<a2.first){\n return 1;\n }else{\n return 0;\n }\n }\n return 0;\n}\nvector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){\n \n \n //Complete the code and return the sorted vector\n sort(v.begin(),v.end(),fun);\n return v;\n}" }, { "code": null, "e": 3967, "s": 3965, "text": "0" }, { "code": null, "e": 3991, "s": 3967, "text": "noobcoderdj8 months ago" }, { "code": null, "e": 4003, "s": 3991, "text": "noobcoderdj" }, { "code": null, "e": 4017, "s": 4003, "text": "c++ two liner" }, { "code": null, "e": 4296, "s": 4017, "text": "vector<pair<string, int=\"\">> sortMarks(vector<pair<string, int=\"\">> v, int N){ sort(v.begin(), v.end(), [](pair<string, int=\"\"> a, pair<string, int=\"\"> b){ if(a.second == b.second) return a.first<b.first; return=\"\" a.second=\"\">b.second; }); return v;}" }, { "code": null, "e": 4298, "s": 4296, "text": "0" }, { "code": null, "e": 4315, "s": 4298, "text": "mscodi1 year ago" }, { "code": null, "e": 4322, "s": 4315, "text": "mscodi" }, { "code": null, "e": 4759, "s": 4322, "text": "bool cmp_by_sec(pair<string, int=\"\"> p1, pair<string, int=\"\"> p2){ if(p1.second > p2.second) { return 1; } else if(p1.second == p2.second) { if(p1.first < p2.first) { return 1; } else { return 0; } } return 0;}vector<pair<string, int=\"\">> sortMarks(vector<pair<string, int=\"\">> v, int N){ sort(v.begin(), v.end(),cmp_by_sec); return v;" }, { "code": null, "e": 4761, "s": 4759, "text": "0" }, { "code": null, "e": 4766, "s": 4761, "text": "fnxl" }, { "code": null, "e": 4792, "s": 4766, "text": "This comment was deleted." }, { "code": null, "e": 4794, "s": 4792, "text": "0" }, { "code": null, "e": 4820, "s": 4794, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 4836, "s": 4820, "text": "Debojyoti Sinha" }, { "code": null, "e": 4885, "s": 4836, "text": "Correct Answer.Correct AnswerExecution Time:0.20" }, { "code": null, "e": 5319, "s": 4885, "text": "bool myCmp(pair<string, int=\"\"> p1, pair<string, int=\"\"> p2){ if(p1.second > p2.second) { return 1; } else if(p1.second == p2.second) { if(p1.first < p2.first) { return 1; } else { return 0; } } return 0;}vector<pair<string, int=\"\">> sortMarks(vector<pair<string, int=\"\">> v, int N){ sort(v.begin(), v.end(), myCmp); return v;}" }, { "code": null, "e": 5465, "s": 5319, "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": 5501, "s": 5465, "text": " Login to access your submissions. " }, { "code": null, "e": 5511, "s": 5501, "text": "\nProblem\n" }, { "code": null, "e": 5521, "s": 5511, "text": "\nContest\n" }, { "code": null, "e": 5584, "s": 5521, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5732, "s": 5584, "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": 5940, "s": 5732, "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": 6046, "s": 5940, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is the difference between pairs() vs. ipairs() in Lua?
In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table. While both of them have some similarities, it is also good to know that they have some very notable differences that we should be aware of. The first difference between the pairs() and ipairs() function is that the pairs() function doesn’t maintain the key order whereas the ipairs() function surely does. Consider the example shown below − Live Demo u={} u[1]="a" u[3]="b" u[2]="c" u[4]="d" u["aa"] = "zz" u[7] = "e" for key,value in ipairs(u) do print(key,value) end print(“---”) for key,value in pairs(u) do print(key,value) end In the example above, the ipairs() function will print the order of the key in numeric order, whereas the pairs() function doesn’t guarantee it. Also, if we look at the example a bit more closely, we will see the second difference, and that is that the ipairs() function doesn’t return non-numeric keys that are present in the table. Consider the output for the reference. 1 a 2 c 3 b 4 d --- 1 a 2 c 3 b 4 d 7 e aa zz
[ { "code": null, "e": 1329, "s": 1062, "text": "In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table." }, { "code": null, "e": 1469, "s": 1329, "text": "While both of them have some similarities, it is also good to know that they have some very notable differences that we should be aware of." }, { "code": null, "e": 1635, "s": 1469, "text": "The first difference between the pairs() and ipairs() function is that the pairs() function doesn’t maintain the key order whereas the ipairs() function surely does." }, { "code": null, "e": 1670, "s": 1635, "text": "Consider the example shown below −" }, { "code": null, "e": 1681, "s": 1670, "text": " Live Demo" }, { "code": null, "e": 1862, "s": 1681, "text": "u={}\nu[1]=\"a\"\nu[3]=\"b\"\nu[2]=\"c\"\nu[4]=\"d\"\nu[\"aa\"] = \"zz\"\nu[7] = \"e\"\nfor key,value in ipairs(u) do print(key,value) end\nprint(“---”)\nfor key,value in pairs(u) do print(key,value) end" }, { "code": null, "e": 2007, "s": 1862, "text": "In the example above, the ipairs() function will print the order of the key in numeric order, whereas the pairs() function doesn’t guarantee it." }, { "code": null, "e": 2196, "s": 2007, "text": "Also, if we look at the example a bit more closely, we will see the second difference, and that is that the ipairs() function doesn’t return non-numeric keys that are present in the table." }, { "code": null, "e": 2235, "s": 2196, "text": "Consider the output for the reference." }, { "code": null, "e": 2299, "s": 2235, "text": "1 a\n2 c\n3 b\n4 d\n---\n1 a\n2 c\n3 b\n4 d\n7 e\naa zz" } ]
Python program to check whether two lists are circularly identical
Here two lists are given. Our task is to check and found weather two given lists are circularly identical or not. Input : A = [100, 100, 10, 10, 100] B = [100, 100, 100, 10, 10] Output : True True as when these elements in the list will circularly rotate then they would be similar to other given list Step 1: Create First and Second List. Step 2: Then Lists are converted to map. Step 3: join () method is used for converting the list objects into the string. Step 3: doubling list A and converted to the map. Step 4: compare two list. If result is true then Two Lists are circularly identical and if return false then they are circularly non identical. # Python program to check and verify whether two lists are circularly identical or not A=list() n=int(input("Enter the size of the First List ::")) print("Enter the Element of First List ::") for i in range(int(n)): k=int(input("")) A.append(k) B=list() n1=int(input("Enter the size of the Second List ::")) print("Enter the Element of the Second List ::") for i in range(int(n1)): k=int(input("")) B.append(k) C=list() n3=int(input("Enter the size of the Third List ::")) print("Enter the Element of the Third List ::") for i in range(int(n3)): k=int(input("")) C.append(k) print("Compare First List and Second List ::>") print(' '.join(map(str, B)) in ' '.join(map(str, A * 2))) print("Compare Second List and Third List ::>") print(' '.join(map(str, C)) in ' '.join(map(str, A * 2))) Enter the size of the First List :: 5 Enter the Element of First List :: 10 10 0 0 10 Enter the size of the Second List :: 5 Enter the Element of the Second List :: 10 10 10 0 0 Enter the size of the Third List :: 5 Enter the Element of the Third List :: 1 10 10 0 0 Compare First List and Second List ::> True Compare Second List and Third List ::> False
[ { "code": null, "e": 1176, "s": 1062, "text": "Here two lists are given. Our task is to check and found weather two given lists are circularly identical or not." }, { "code": null, "e": 1263, "s": 1176, "text": "Input : A = [100, 100, 10, 10, 100]\n B = [100, 100, 100, 10, 10]\nOutput : True\n" }, { "code": null, "e": 1374, "s": 1263, "text": "True as when these elements in the list will circularly rotate then they would be similar to other given list " }, { "code": null, "e": 1728, "s": 1374, "text": "Step 1: Create First and Second List.\nStep 2: Then Lists are converted to map.\nStep 3: join () method is used for converting the list objects into the string.\nStep 3: doubling list A and converted to the map.\nStep 4: compare two list. If result is true then Two Lists are circularly identical and if return false then they are circularly non identical.\n" }, { "code": null, "e": 2537, "s": 1728, "text": "# Python program to check and verify whether two lists are circularly identical or not\n\nA=list()\nn=int(input(\"Enter the size of the First List ::\"))\nprint(\"Enter the Element of First List ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n A.append(k)\n\nB=list()\nn1=int(input(\"Enter the size of the Second List ::\"))\nprint(\"Enter the Element of the Second List ::\")\nfor i in range(int(n1)):\n k=int(input(\"\"))\n B.append(k)\n\nC=list()\nn3=int(input(\"Enter the size of the Third List ::\"))\nprint(\"Enter the Element of the Third List ::\")\nfor i in range(int(n3)):\n k=int(input(\"\"))\n C.append(k)\n\nprint(\"Compare First List and Second List ::>\")\nprint(' '.join(map(str, B)) in ' '.join(map(str, A * 2)))\nprint(\"Compare Second List and Third List ::>\")\nprint(' '.join(map(str, C)) in ' '.join(map(str, A * 2)))" }, { "code": null, "e": 2895, "s": 2537, "text": "Enter the size of the First List :: 5\nEnter the Element of First List ::\n10\n10\n0\n0\n10\nEnter the size of the Second List :: 5\nEnter the Element of the Second List ::\n10\n10\n10\n0\n0\nEnter the size of the Third List :: 5\nEnter the Element of the Third List ::\n1\n10\n10\n0\n0\nCompare First List and Second List ::>\nTrue\nCompare Second List and Third List ::>\nFalse\n" } ]
Arduino - I/O Functions
The pins on the Arduino board can be configured as either inputs or outputs. We will explain the functioning of the pins in those modes. It is important to note that a majority of Arduino analog pins, may be configured, and used, in exactly the same manner as digital pins. Arduino pins are by default configured as inputs, so they do not need to be explicitly declared as inputs with pinMode() when you are using them as inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megaohm in front of the pin. This means that it takes very little current to switch the input pin from one state to another. This makes the pins useful for such tasks as implementing a capacitive touch sensor or reading an LED as a photodiode. Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected to them that are not connected to other circuits, report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin. Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This can be done by adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to ground) on the input. A 10K resistor is a good value for a pull-up or pull-down resistor. There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from software. These built-in pull-up resistors are accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is OFF and LOW means the sensor is ON. The value of this pull-up depends on the microcontroller used. On most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the microcontroller on your board. When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be connected to the ground. In case of a simple switch, this causes the pin to read HIGH when the switch is open and LOW when the switch is pressed. The pull-up resistors provide enough current to light an LED dimly connected to a pin configured as an input. If LEDs in a project seem to be working, but very dimly, this is likely what is going on. Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW control the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors turned on when the pin is in INPUTmode, will have the pin configured as HIGH if the pin is then switched to an OUTPUT mode with pinMode(). This works in the other direction as well, and an output pin that is left in a HIGH state will have the pull-up resistor set if switched to an input with pinMode(). Example pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This is enough current to brightly light up an LED (do not forget the series resistor), or run many sensors but not enough current to run relays, solenoids, or motors. Attempting to run high current devices from the output pins, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip. Often, this results in a "dead" pin in the microcontroller but the remaining chips still function adequately. For this reason, it is a good idea to connect the OUTPUT pins to other devices through 470Ω or 1k resistors, unless maximum current drawn from the pins is required for a particular application. The pinMode() function is used to configure a specific pin to behave either as an input or an output. It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pull-ups. Void setup () { pinMode (pin , mode); } pin − the number of the pin whose mode you wish to set pin − the number of the pin whose mode you wish to set mode − INPUT, OUTPUT, or INPUT_PULLUP. mode − INPUT, OUTPUT, or INPUT_PULLUP. Example int button = 5 ; // button connected to pin 5 int LED = 6; // LED connected to pin 6 void setup () { pinMode(button , INPUT_PULLUP); // set the digital pin as input with pull-up resistor pinMode(button , OUTPUT); // set the digital pin as output } void setup () { If (digitalRead(button ) == LOW) // if button pressed { digitalWrite(LED,HIGH); // turn on led delay(500); // delay for 500 ms digitalWrite(LED,LOW); // turn off led delay(500); // delay for 500 ms } } The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor. If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(), digitalWrite() will have enabled the internal pull-up resistor, which acts like a large current-limiting resistor. Void loop() { digitalWrite (pin ,value); } pin − the number of the pin whose mode you wish to set pin − the number of the pin whose mode you wish to set value − HIGH, or LOW. value − HIGH, or LOW. Example int LED = 6; // LED connected to pin 6 void setup () { pinMode(LED, OUTPUT); // set the digital pin as output } void setup () { digitalWrite(LED,HIGH); // turn on led delay(500); // delay for 500 ms digitalWrite(LED,LOW); // turn off led delay(500); // delay for 500 ms } Arduino is able to detect whether there is a voltage applied to one of its pins and report it through the digitalRead() function. There is a difference between an on/off sensor (which detects the presence of an object) and an analog sensor, whose value continuously changes. In order to read this type of sensor, we need a different type of pin. In the lower-right part of the Arduino board, you will see six pins marked “Analog In”. These special pins not only tell whether there is a voltage applied to them, but also its value. By using the analogRead() function, we can read the voltage applied to one of the pins. This function returns a number between 0 and 1023, which represents voltages between 0 and 5 volts. For example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0) returns 512. analogRead(pin); pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega) pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega) Example int analogPin = 3;//potentiometer wiper (middle terminal) // connected to analog pin 3 int val = 0; // variable to store the value read void setup() { Serial.begin(9600); // setup serial } void loop() { val = analogRead(analogPin); // read the input pin Serial.println(val); // debug value } 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3144, "s": 2870, "text": "The pins on the Arduino board can be configured as either inputs or outputs. We will explain the functioning of the pins in those modes. It is important to note that a majority of Arduino analog pins, may be configured, and used, in exactly the same manner as digital pins." }, { "code": null, "e": 3514, "s": 3144, "text": "Arduino pins are by default configured as inputs, so they do not need to be explicitly declared as inputs with pinMode() when you are using them as inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megaohm in front of the pin." }, { "code": null, "e": 3729, "s": 3514, "text": "This means that it takes very little current to switch the input pin from one state to another. This makes the pins useful for such tasks as implementing a capacitive touch sensor or reading an LED as a photodiode." }, { "code": null, "e": 4022, "s": 3729, "text": "Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected to them that are not connected to other circuits, report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin." }, { "code": null, "e": 4303, "s": 4022, "text": "Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This can be done by adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to ground) on the input. A 10K resistor is a good value for a pull-up or pull-down resistor." }, { "code": null, "e": 4886, "s": 4303, "text": "There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from software. These built-in pull-up resistors are accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is OFF and LOW means the sensor is ON. The value of this pull-up depends on the microcontroller used. On most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the microcontroller on your board." }, { "code": null, "e": 5320, "s": 4886, "text": "When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be connected to the ground. In case of a simple switch, this causes the pin to read HIGH when the switch is open and LOW when the switch is pressed. The pull-up resistors provide enough current to light an LED dimly connected to a pin configured as an input. If LEDs in a project seem to be working, but very dimly, this is likely what is going on." }, { "code": null, "e": 5810, "s": 5320, "text": "Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW control the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors turned on when the pin is in INPUTmode, will have the pin configured as HIGH if the pin is then switched to an OUTPUT mode with pinMode(). This works in the other direction as well, and an output pin that is left in a HIGH state will have the pull-up resistor set if switched to an input with pinMode()." }, { "code": null, "e": 5818, "s": 5810, "text": "Example" }, { "code": null, "e": 5976, "s": 5818, "text": "pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor\npinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor\n" }, { "code": null, "e": 6457, "s": 5976, "text": "Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This is enough current to brightly light up an LED (do not forget the series resistor), or run many sensors but not enough current to run relays, solenoids, or motors." }, { "code": null, "e": 6913, "s": 6457, "text": "Attempting to run high current devices from the output pins, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip. Often, this results in a \"dead\" pin in the microcontroller but the remaining chips still function adequately. For this reason, it is a good idea to connect the OUTPUT pins to other devices through 470Ω or 1k resistors, unless maximum current drawn from the pins is required for a particular application." }, { "code": null, "e": 7171, "s": 6913, "text": "The pinMode() function is used to configure a specific pin to behave either as an input or an output. It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pull-ups." }, { "code": null, "e": 7215, "s": 7171, "text": "Void setup () {\n pinMode (pin , mode);\n}\n" }, { "code": null, "e": 7270, "s": 7215, "text": "pin − the number of the pin whose mode you wish to set" }, { "code": null, "e": 7325, "s": 7270, "text": "pin − the number of the pin whose mode you wish to set" }, { "code": null, "e": 7364, "s": 7325, "text": "mode − INPUT, OUTPUT, or INPUT_PULLUP." }, { "code": null, "e": 7403, "s": 7364, "text": "mode − INPUT, OUTPUT, or INPUT_PULLUP." }, { "code": null, "e": 7411, "s": 7403, "text": "Example" }, { "code": null, "e": 7919, "s": 7411, "text": "int button = 5 ; // button connected to pin 5\nint LED = 6; // LED connected to pin 6\n\nvoid setup () {\n pinMode(button , INPUT_PULLUP); \n // set the digital pin as input with pull-up resistor\n pinMode(button , OUTPUT); // set the digital pin as output\n}\n\nvoid setup () {\n If (digitalRead(button ) == LOW) // if button pressed {\n digitalWrite(LED,HIGH); // turn on led\n delay(500); // delay for 500 ms\n digitalWrite(LED,LOW); // turn off led\n delay(500); // delay for 500 ms\n }\n}" }, { "code": null, "e": 8398, "s": 7919, "text": "The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor." }, { "code": null, "e": 8680, "s": 8398, "text": "If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(), digitalWrite() will have enabled the internal pull-up resistor, which acts like a large current-limiting resistor." }, { "code": null, "e": 8727, "s": 8680, "text": "Void loop() {\n digitalWrite (pin ,value);\n}\n" }, { "code": null, "e": 8782, "s": 8727, "text": "pin − the number of the pin whose mode you wish to set" }, { "code": null, "e": 8837, "s": 8782, "text": "pin − the number of the pin whose mode you wish to set" }, { "code": null, "e": 8859, "s": 8837, "text": "value − HIGH, or LOW." }, { "code": null, "e": 8881, "s": 8859, "text": "value − HIGH, or LOW." }, { "code": null, "e": 8889, "s": 8881, "text": "Example" }, { "code": null, "e": 9179, "s": 8889, "text": "int LED = 6; // LED connected to pin 6\n\nvoid setup () {\n pinMode(LED, OUTPUT); // set the digital pin as output\n}\n\nvoid setup () { \n digitalWrite(LED,HIGH); // turn on led\n delay(500); // delay for 500 ms\n digitalWrite(LED,LOW); // turn off led\n delay(500); // delay for 500 ms\n}" }, { "code": null, "e": 9525, "s": 9179, "text": "Arduino is able to detect whether there is a voltage applied to one of its pins and report it through the digitalRead() function. There is a difference between an on/off sensor (which detects the presence of an object) and an analog sensor, whose value continuously changes. In order to read this type of sensor, we need a different type of pin." }, { "code": null, "e": 9798, "s": 9525, "text": "In the lower-right part of the Arduino board, you will see six pins marked “Analog In”. These special pins not only tell whether there is a voltage applied to them, but also its value. By using the analogRead() function, we can read the voltage applied to one of the pins." }, { "code": null, "e": 9994, "s": 9798, "text": "This function returns a number between 0 and 1023, which represents voltages between 0 and 5 volts. For example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0) returns 512." }, { "code": null, "e": 10012, "s": 9994, "text": "analogRead(pin);\n" }, { "code": null, "e": 10140, "s": 10012, "text": "pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega)" }, { "code": null, "e": 10268, "s": 10140, "text": "pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega)" }, { "code": null, "e": 10276, "s": 10268, "text": "Example" }, { "code": null, "e": 10585, "s": 10276, "text": "int analogPin = 3;//potentiometer wiper (middle terminal) \n // connected to analog pin 3 \nint val = 0; // variable to store the value read\n\nvoid setup() {\n Serial.begin(9600); // setup serial\n} \n\nvoid loop() {\n val = analogRead(analogPin); // read the input pin\n Serial.println(val); // debug value\n}" }, { "code": null, "e": 10620, "s": 10585, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 10631, "s": 10620, "text": " Amit Rana" }, { "code": null, "e": 10664, "s": 10631, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 10675, "s": 10664, "text": " Amit Rana" }, { "code": null, "e": 10708, "s": 10675, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 10721, "s": 10708, "text": " Ashraf Said" }, { "code": null, "e": 10756, "s": 10721, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10769, "s": 10756, "text": " Ashraf Said" }, { "code": null, "e": 10801, "s": 10769, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 10814, "s": 10801, "text": " Ashraf Said" }, { "code": null, "e": 10845, "s": 10814, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 10858, "s": 10845, "text": " Ashraf Said" }, { "code": null, "e": 10865, "s": 10858, "text": " Print" }, { "code": null, "e": 10876, "s": 10865, "text": " Add Notes" } ]
How to Display an OpenCV image in Python with Matplotlib? - GeeksforGeeks
16 Aug, 2021 The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV. First, let’s look at how to display images using OpenCV: Now there is one function called cv2.imread() which will take the path of an image as an argument. Using this function you will read that particular image and simply display it using the cv2.imshow() function. Python3 # import required moduleimport cv2 # read the Image by giving pathimage = cv2.imread('gfg.png') # display that imagecv2.imshow('GFG', image) Output: DIsplay image using OpenCV Now let’s jump into displaying the images with Matplotlib module. It is an amazing visualization library in Python for 2D plots of arrays. The Matplotlib module is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. We are doing minor changes to the above code to display our image with Matplotlib module. Python3 # import required moduleimport cv2import matplotlib.pyplot as plt # read imageimage = cv2.imread('gfg.png') # call imshow() using plt objectplt.imshow(image) # display that imageplt.show() Output: image plot with Matplotlib One can also display gray scale OpenCV images with Matplotlib module for that you just need to convert colored image into a gray scale image. Python3 # import required modulesimport cv2import matplotlib.pyplot as plt # read the imageimage = cv2.imread('gfg.png') # convert color image into grayscale imageimg1 = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # plot that grayscale image with Matplotlib# cmap stands for colormapplt.imshow(img1, cmap='gray') # display that imageplt.show() Output: Display grayscale image plot with Matplotlib This is how we can display OpenCV images in python with Matplotlib module. gabaa406 simmytarika5 Python-matplotlib Python-OpenCV Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 30426, "s": 30398, "text": "\n16 Aug, 2021" }, { "code": null, "e": 31041, "s": 30426, "text": "The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV." }, { "code": null, "e": 31098, "s": 31041, "text": "First, let’s look at how to display images using OpenCV:" }, { "code": null, "e": 31309, "s": 31098, "text": "Now there is one function called cv2.imread() which will take the path of an image as an argument. Using this function you will read that particular image and simply display it using the cv2.imshow() function. " }, { "code": null, "e": 31317, "s": 31309, "text": "Python3" }, { "code": "# import required moduleimport cv2 # read the Image by giving pathimage = cv2.imread('gfg.png') # display that imagecv2.imshow('GFG', image)", "e": 31458, "s": 31317, "text": null }, { "code": null, "e": 31466, "s": 31458, "text": "Output:" }, { "code": null, "e": 31493, "s": 31466, "text": "DIsplay image using OpenCV" }, { "code": null, "e": 31774, "s": 31493, "text": "Now let’s jump into displaying the images with Matplotlib module. It is an amazing visualization library in Python for 2D plots of arrays. The Matplotlib module is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 31865, "s": 31774, "text": "We are doing minor changes to the above code to display our image with Matplotlib module. " }, { "code": null, "e": 31873, "s": 31865, "text": "Python3" }, { "code": "# import required moduleimport cv2import matplotlib.pyplot as plt # read imageimage = cv2.imread('gfg.png') # call imshow() using plt objectplt.imshow(image) # display that imageplt.show()", "e": 32062, "s": 31873, "text": null }, { "code": null, "e": 32070, "s": 32062, "text": "Output:" }, { "code": null, "e": 32097, "s": 32070, "text": "image plot with Matplotlib" }, { "code": null, "e": 32239, "s": 32097, "text": "One can also display gray scale OpenCV images with Matplotlib module for that you just need to convert colored image into a gray scale image." }, { "code": null, "e": 32247, "s": 32239, "text": "Python3" }, { "code": "# import required modulesimport cv2import matplotlib.pyplot as plt # read the imageimage = cv2.imread('gfg.png') # convert color image into grayscale imageimg1 = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # plot that grayscale image with Matplotlib# cmap stands for colormapplt.imshow(img1, cmap='gray') # display that imageplt.show()", "e": 32579, "s": 32247, "text": null }, { "code": null, "e": 32587, "s": 32579, "text": "Output:" }, { "code": null, "e": 32632, "s": 32587, "text": "Display grayscale image plot with Matplotlib" }, { "code": null, "e": 32707, "s": 32632, "text": "This is how we can display OpenCV images in python with Matplotlib module." }, { "code": null, "e": 32716, "s": 32707, "text": "gabaa406" }, { "code": null, "e": 32729, "s": 32716, "text": "simmytarika5" }, { "code": null, "e": 32747, "s": 32729, "text": "Python-matplotlib" }, { "code": null, "e": 32761, "s": 32747, "text": "Python-OpenCV" }, { "code": null, "e": 32785, "s": 32761, "text": "Technical Scripter 2020" }, { "code": null, "e": 32792, "s": 32785, "text": "Python" }, { "code": null, "e": 32811, "s": 32792, "text": "Technical Scripter" }, { "code": null, "e": 32909, "s": 32811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32937, "s": 32909, "text": "Read JSON file using Python" }, { "code": null, "e": 32987, "s": 32937, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 33009, "s": 32987, "text": "Python map() function" }, { "code": null, "e": 33053, "s": 33009, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 33071, "s": 33053, "text": "Python Dictionary" }, { "code": null, "e": 33094, "s": 33071, "text": "Taking input in Python" }, { "code": null, "e": 33129, "s": 33094, "text": "Read a file line by line in Python" }, { "code": null, "e": 33161, "s": 33129, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33183, "s": 33161, "text": "Enumerate() in Python" } ]
How to create a Snackbar using HMTL, CSS & JavaScript? - GeeksforGeeks
15 Jul, 2020 Snackbars in web design are notifications that are displayed on the website. Sometimes developers want to display additional notifications to the users, making them aware of certain information which is important but at the same time should not affect the user experience. This information can be about some kind of event which has occurred or will occur within the website, whether it was successful or not or that requires some quick user input or intervention. Snackbars inform the users of processes that a website will perform or provide feedback on the processes that the website has already performed. For example, an unsuccessful API call, etc. They usually occur at the bottom of the screen within the website and should not hamper with the current flow or user experience. They usually disappear on their own unless some user intervention is required. The Snackbars should only be displayed one at a time to avoid clogging the screen. They usually contain a single action such as Dismiss/Cancel/Ok and can be used as a part of the error handling as well. They can also be triggered by custom actions such as when the user clicks on a button. Bootstrap and jQuery provide an extensive support for snackbar notification via classes and plugins but they can also be designed and implemented without any external libraries by simply using HTML, CSS and JavaScript only. It is also important to know that many web frameworks such as Angular 4+, ReactJS, etc and Android applications also provide support for Snackbar notifications and they can be implemented using their own classes and methods. For a detailed Explanation, refer the articles: How to add a Snackbar in Android How to create a SnackBar service? In this tutorial, we will implement Snackbar notifications for a website using HTML, CSS and JavaScript only.We assume that you are familiar with HTML, and CSS rules and have a basic knowledge of CSS animations. Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML website, CSS Animation and to load the respective JavaScript files. We will install Browsersync globally.npm install -g browser-sync npm install -g browser-sync Step 2: Create an “index.html” file, an index.css file and an index.js in your project root folder.index.html: Add the following code snippet in that file.htmlhtml<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel="stylesheet" href="index.css"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class="btn btn-lg" onclick="showSnackbar()"> Show Snackbar </button> <div id="snackbar">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src="index.js"></script></body></html>index.css: By default, we have set the #snackbar HTML element to be hidden using the CSS visibility property. We have also defined the position: fixed; and z-index: 1; CSS properties for the Snackbar notification so that when it is made visible it will always be displayed above the screen for the User. Refer to the code comments for better understanding. The !important CSS property states that all other conflicting rules on an HTML DOM element are to be ignored, and the rule denoted by !important is to be applied. This rule overrides all before set CSS rules. We have used simple CSS animations to display the Snackbar notification to the users by fading into the screen and fading out of it. A detailed explanation of which can be found here. The total time set for the CSS animations depends upon the time limit for which we want the notification to be visible to the user. The time for the fadeout CSS Animation is calculated accordingly by subtracting 0.5 seconds from the total time in our case.csscss#snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }}index.js: We have used JavaScript to dynamically append a class to the HTML div element at the time when the Show Snackbar button is clicked. The showSnackbar() function is triggered by the onClick HTML Button property. The dynamically appended class, adds the CSS Rules to the #snackbar HTML element which makes it visible to the user. We have used the setTimeout() JavaScript function to dynamically remove the previously appended Class after 5 seconds, which will make the Snackar notification disappear.JSJSfunction showSnackbar() { var snackBar = document.getElementById("snackbar") // Dynamically Appending class // to HTML element snackBar.className = "show-bar"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace("show-bar", ""); }, 5000);} index.html: Add the following code snippet in that file.htmlhtml<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel="stylesheet" href="index.css"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class="btn btn-lg" onclick="showSnackbar()"> Show Snackbar </button> <div id="snackbar">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src="index.js"></script></body></html> html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel="stylesheet" href="index.css"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class="btn btn-lg" onclick="showSnackbar()"> Show Snackbar </button> <div id="snackbar">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src="index.js"></script></body></html> index.css: By default, we have set the #snackbar HTML element to be hidden using the CSS visibility property. We have also defined the position: fixed; and z-index: 1; CSS properties for the Snackbar notification so that when it is made visible it will always be displayed above the screen for the User. Refer to the code comments for better understanding. The !important CSS property states that all other conflicting rules on an HTML DOM element are to be ignored, and the rule denoted by !important is to be applied. This rule overrides all before set CSS rules. We have used simple CSS animations to display the Snackbar notification to the users by fading into the screen and fading out of it. A detailed explanation of which can be found here. The total time set for the CSS animations depends upon the time limit for which we want the notification to be visible to the user. The time for the fadeout CSS Animation is calculated accordingly by subtracting 0.5 seconds from the total time in our case.csscss#snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }} css #snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }} index.js: We have used JavaScript to dynamically append a class to the HTML div element at the time when the Show Snackbar button is clicked. The showSnackbar() function is triggered by the onClick HTML Button property. The dynamically appended class, adds the CSS Rules to the #snackbar HTML element which makes it visible to the user. We have used the setTimeout() JavaScript function to dynamically remove the previously appended Class after 5 seconds, which will make the Snackar notification disappear.JSJSfunction showSnackbar() { var snackBar = document.getElementById("snackbar") // Dynamically Appending class // to HTML element snackBar.className = "show-bar"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace("show-bar", ""); }, 5000);} JS function showSnackbar() { var snackBar = document.getElementById("snackbar") // Dynamically Appending class // to HTML element snackBar.className = "show-bar"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace("show-bar", ""); }, 5000);} Step 3: We have successfully implemented Snackbar notifications using HTML,CSS and JavaScript. In HTML, we have defined a custom Show Snackbar button which will trigger the Snackbar notification on the Screen. The Snackbar notification is a simple Text message which is being displayed to the user. Since the Snackbar is a simple HTML “div” element, we can add custom actions to the Snackbar notification. For example, an “input box” or a “dismiss button”, if required. In our case, the snackbar notification will automatically disappear from the screen after 5 seconds.Output: Step 4: At this Point our Snackbar Notification is ready. To launch the application using Browsersync, run the following command in the project directory or you can run the HTML file directly into your browser.browser-sync start --server --files "*"This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output: browser-sync start --server --files "*" This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default. Output: JavaScript-Misc Bootstrap CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26087, "s": 26059, "text": "\n15 Jul, 2020" }, { "code": null, "e": 26551, "s": 26087, "text": "Snackbars in web design are notifications that are displayed on the website. Sometimes developers want to display additional notifications to the users, making them aware of certain information which is important but at the same time should not affect the user experience. This information can be about some kind of event which has occurred or will occur within the website, whether it was successful or not or that requires some quick user input or intervention." }, { "code": null, "e": 27239, "s": 26551, "text": "Snackbars inform the users of processes that a website will perform or provide feedback on the processes that the website has already performed. For example, an unsuccessful API call, etc. They usually occur at the bottom of the screen within the website and should not hamper with the current flow or user experience. They usually disappear on their own unless some user intervention is required. The Snackbars should only be displayed one at a time to avoid clogging the screen. They usually contain a single action such as Dismiss/Cancel/Ok and can be used as a part of the error handling as well. They can also be triggered by custom actions such as when the user clicks on a button." }, { "code": null, "e": 27736, "s": 27239, "text": "Bootstrap and jQuery provide an extensive support for snackbar notification via classes and plugins but they can also be designed and implemented without any external libraries by simply using HTML, CSS and JavaScript only. It is also important to know that many web frameworks such as Angular 4+, ReactJS, etc and Android applications also provide support for Snackbar notifications and they can be implemented using their own classes and methods. For a detailed Explanation, refer the articles:" }, { "code": null, "e": 27769, "s": 27736, "text": "How to add a Snackbar in Android" }, { "code": null, "e": 27803, "s": 27769, "text": "How to create a SnackBar service?" }, { "code": null, "e": 28015, "s": 27803, "text": "In this tutorial, we will implement Snackbar notifications for a website using HTML, CSS and JavaScript only.We assume that you are familiar with HTML, and CSS rules and have a basic knowledge of CSS animations." }, { "code": null, "e": 28264, "s": 28015, "text": "Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML website, CSS Animation and to load the respective JavaScript files. We will install Browsersync globally.npm install -g browser-sync" }, { "code": null, "e": 28292, "s": 28264, "text": "npm install -g browser-sync" }, { "code": null, "e": 32125, "s": 28292, "text": "Step 2: Create an “index.html” file, an index.css file and an index.js in your project root folder.index.html: Add the following code snippet in that file.htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel=\"stylesheet\" href=\"index.css\"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class=\"btn btn-lg\" onclick=\"showSnackbar()\"> Show Snackbar </button> <div id=\"snackbar\">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src=\"index.js\"></script></body></html>index.css: By default, we have set the #snackbar HTML element to be hidden using the CSS visibility property. We have also defined the position: fixed; and z-index: 1; CSS properties for the Snackbar notification so that when it is made visible it will always be displayed above the screen for the User. Refer to the code comments for better understanding. The !important CSS property states that all other conflicting rules on an HTML DOM element are to be ignored, and the rule denoted by !important is to be applied. This rule overrides all before set CSS rules. We have used simple CSS animations to display the Snackbar notification to the users by fading into the screen and fading out of it. A detailed explanation of which can be found here. The total time set for the CSS animations depends upon the time limit for which we want the notification to be visible to the user. The time for the fadeout CSS Animation is calculated accordingly by subtracting 0.5 seconds from the total time in our case.csscss#snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }}index.js: We have used JavaScript to dynamically append a class to the HTML div element at the time when the Show Snackbar button is clicked. The showSnackbar() function is triggered by the onClick HTML Button property. The dynamically appended class, adds the CSS Rules to the #snackbar HTML element which makes it visible to the user. We have used the setTimeout() JavaScript function to dynamically remove the previously appended Class after 5 seconds, which will make the Snackar notification disappear.JSJSfunction showSnackbar() { var snackBar = document.getElementById(\"snackbar\") // Dynamically Appending class // to HTML element snackBar.className = \"show-bar\"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace(\"show-bar\", \"\"); }, 5000);}" }, { "code": null, "e": 32852, "s": 32125, "text": "index.html: Add the following code snippet in that file.htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel=\"stylesheet\" href=\"index.css\"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class=\"btn btn-lg\" onclick=\"showSnackbar()\"> Show Snackbar </button> <div id=\"snackbar\">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src=\"index.js\"></script></body></html>" }, { "code": null, "e": 32857, "s": 32852, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>GeeksforGeeks</title> <!-- Loading External index.css file --> <link rel=\"stylesheet\" href=\"index.css\"></head><body> <h2> GeeksforGeeks - Snackbar using HTML, CSS & JS </h2> <!-- Custom Action to Trigger the Snackbar --> <button class=\"btn btn-lg\" onclick=\"showSnackbar()\"> Show Snackbar </button> <div id=\"snackbar\">Hello GeeksforGeeks</div> <!-- Loading External index.js file --> <script src=\"index.js\"></script></body></html>", "e": 33520, "s": 32857, "text": null }, { "code": null, "e": 35574, "s": 33520, "text": "index.css: By default, we have set the #snackbar HTML element to be hidden using the CSS visibility property. We have also defined the position: fixed; and z-index: 1; CSS properties for the Snackbar notification so that when it is made visible it will always be displayed above the screen for the User. Refer to the code comments for better understanding. The !important CSS property states that all other conflicting rules on an HTML DOM element are to be ignored, and the rule denoted by !important is to be applied. This rule overrides all before set CSS rules. We have used simple CSS animations to display the Snackbar notification to the users by fading into the screen and fading out of it. A detailed explanation of which can be found here. The total time set for the CSS animations depends upon the time limit for which we want the notification to be visible to the user. The time for the fadeout CSS Animation is calculated accordingly by subtracting 0.5 seconds from the total time in our case.csscss#snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }}" }, { "code": null, "e": 35578, "s": 35574, "text": "css" }, { "code": "#snackbar { /* By Default, Hidden */ visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: left; border-radius: 2px; padding: 16px; /* To always Keep on Top of screen */ position: fixed; /* To be displayed above Parent HTML DOM element */ z-index: 1; /* Position Bottom Left Corner of Screen */ left: 10px; bottom: 30px;} /* Dynamically Appending this Class to #snackbar via JS */.show-bar { visibility: visible !important; /* fadeout Time decided in accordance to Total Time */ /* In case, Time = 3s, fadeout 0.5s 2.5s */ animation: fadein 0.5s, fadeout 0.5s 4.5s;} /* when the Snackbar Appears */@keyframes fadein { from { bottom: 0; opacity: 0; } to { bottom: 30px; opacity: 1; }} /* when the Snackbar Disappears from the Screen */@keyframes fadeout { from { bottom: 30px; opacity: 1; } to { bottom: 0; opacity: 0; }}", "e": 36620, "s": 35578, "text": null }, { "code": null, "e": 37575, "s": 36620, "text": "index.js: We have used JavaScript to dynamically append a class to the HTML div element at the time when the Show Snackbar button is clicked. The showSnackbar() function is triggered by the onClick HTML Button property. The dynamically appended class, adds the CSS Rules to the #snackbar HTML element which makes it visible to the user. We have used the setTimeout() JavaScript function to dynamically remove the previously appended Class after 5 seconds, which will make the Snackar notification disappear.JSJSfunction showSnackbar() { var snackBar = document.getElementById(\"snackbar\") // Dynamically Appending class // to HTML element snackBar.className = \"show-bar\"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace(\"show-bar\", \"\"); }, 5000);}" }, { "code": null, "e": 37578, "s": 37575, "text": "JS" }, { "code": "function showSnackbar() { var snackBar = document.getElementById(\"snackbar\") // Dynamically Appending class // to HTML element snackBar.className = \"show-bar\"; setTimeout(function () { // Dynamically Removing the Class // from HTML element // By Replacing it with an Empty // String after 5 seconds snackBar.className = snackBar.className.replace(\"show-bar\", \"\"); }, 5000);}", "e": 38022, "s": 37578, "text": null }, { "code": null, "e": 38600, "s": 38022, "text": "Step 3: We have successfully implemented Snackbar notifications using HTML,CSS and JavaScript. In HTML, we have defined a custom Show Snackbar button which will trigger the Snackbar notification on the Screen. The Snackbar notification is a simple Text message which is being displayed to the user. Since the Snackbar is a simple HTML “div” element, we can add custom actions to the Snackbar notification. For example, an “input box” or a “dismiss button”, if required. In our case, the snackbar notification will automatically disappear from the screen after 5 seconds.Output:" }, { "code": null, "e": 39057, "s": 38600, "text": "Step 4: At this Point our Snackbar Notification is ready. To launch the application using Browsersync, run the following command in the project directory or you can run the HTML file directly into your browser.browser-sync start --server --files \"*\"This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default.Output:" }, { "code": null, "e": 39097, "s": 39057, "text": "browser-sync start --server --files \"*\"" }, { "code": null, "e": 39298, "s": 39097, "text": "This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default." }, { "code": null, "e": 39306, "s": 39298, "text": "Output:" }, { "code": null, "e": 39322, "s": 39306, "text": "JavaScript-Misc" }, { "code": null, "e": 39332, "s": 39322, "text": "Bootstrap" }, { "code": null, "e": 39336, "s": 39332, "text": "CSS" }, { "code": null, "e": 39341, "s": 39336, "text": "HTML" }, { "code": null, "e": 39352, "s": 39341, "text": "JavaScript" }, { "code": null, "e": 39369, "s": 39352, "text": "Web Technologies" }, { "code": null, "e": 39374, "s": 39369, "text": "HTML" }, { "code": null, "e": 39472, "s": 39374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39513, "s": 39472, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 39554, "s": 39513, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 39617, "s": 39554, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 39650, "s": 39617, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 39697, "s": 39650, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 39747, "s": 39697, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39809, "s": 39747, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39857, "s": 39809, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39915, "s": 39857, "text": "How to create footer to stay at the bottom of a Web page?" } ]
How to split string by a delimiter str in Python?
Python's String class has a method called split() which takes a delimiter as optional argument. Default delimiter for it is whitespace. You can use it in the following way: >>> 'aa-ab-ca'.split('-') ['aa', 'ab', 'ca'] >>> 'abc mno rst'.split(' ') ['abc', 'mno', 'rst'] You can also use regex for this operation. The re.split method takes a delimiter regex and the string and returns the list. For example: >>> import re >>> re.split('-', 'aa-ab-ca') ['aa', 'ab', 'ca'] >>>re.split(' ', 'abc mno rst') ['abc', 'mno', 'rst']
[ { "code": null, "e": 1235, "s": 1062, "text": "Python's String class has a method called split() which takes a delimiter as optional argument. Default delimiter for it is whitespace. You can use it in the following way:" }, { "code": null, "e": 1331, "s": 1235, "text": ">>> 'aa-ab-ca'.split('-')\n['aa', 'ab', 'ca']\n>>> 'abc mno rst'.split(' ')\n['abc', 'mno', 'rst']" }, { "code": null, "e": 1468, "s": 1331, "text": "You can also use regex for this operation. The re.split method takes a delimiter regex and the string and returns the list. For example:" }, { "code": null, "e": 1585, "s": 1468, "text": ">>> import re\n>>> re.split('-', 'aa-ab-ca')\n['aa', 'ab', 'ca']\n>>>re.split(' ', 'abc mno rst')\n['abc', 'mno', 'rst']" } ]
Collect maximum points in a grid using two traversals - GeeksforGeeks
31 May, 2021 Given a matrix where every cell represents points. How to collect maximum points using two traversals under following conditions?Let the dimensions of given grid be R x C.1) The first traversal starts from top left corner, i.e., (0, 0) and should reach left bottom corner, i.e., (R-1, 0). The second traversal starts from top right corner, i.e., (0, C-1) and should reach bottom right corner, i.e., (R-1, C-1)/2) From a point (i, j), we can move to (i+1, j+1) or (i+1, j-1) or (i+1, j)3) A traversal gets all points of a particular cell through which it passes. If one traversal has already collected points of a cell, then the other traversal gets no points if goes through that cell again. Input : int arr[R][C] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; Output: 73 Explanation : First traversal collects total points of value 3 + 2 + 20 + 1 + 1 = 27 Second traversal collects total points of value 2 + 4 + 10 + 20 + 10 = 46. Total Points collected = 27 + 46 = 73. We strongly recommend you to minimize your browser and try this yourself first. The idea is to do both traversals concurrently. We start first from (0, 0) and second traversal from (0, C-1) simultaneously. The important thing to note is, at any particular step both traversals will be in same row as in all possible three moves, row number is increased. Let (x1, y1) and (x2, y2) denote current positions of first and second traversals respectively. Thus at any time x1 will be equal to x2 as both of them move forward but variation is possible along y. Since variation in y could occur in 3 ways no change (y), go left (y – 1), go right (y + 1). So in total 9 combinations among y1, y2 are possible. The 9 cases as mentioned below after base cases. Both traversals always move forward along x Base Cases: // If destinations reached if (x == R-1 && y1 == 0 && y2 == C-1) maxPoints(arr, x, y1, y2) = arr[x][y1] + arr[x][y2]; // If any of the two locations is invalid (going out of grid) if input is not valid maxPoints(arr, x, y1, y2) = -INF (minus infinite) // If both traversals are at same cell, then we count the value of cell // only once. If y1 and y2 are same result = arr[x][y1] Else result = arr[x][y1] + arr[x][y2] result += max { // Max of 9 cases maxPoints(arr, x+1, y1+1, y2), maxPoints(arr, x+1, y1+1, y2+1), maxPoints(arr, x+1, y1+1, y2-1), maxPoints(arr, x+1, y1-1, y2), maxPoints(arr, x+1, y1-1, y2+1), maxPoints(arr, x+1, y1-1, y2-1), maxPoints(arr, x+1, y1, y2), maxPoints(arr, x+1, y1, y2+1), maxPoints(arr, x+1, y1, y2-1) } The above recursive solution has many subproblems that are solved again and again. Therefore, we can use Dynamic Programming to solve the above problem more efficiently. Below is memoization (Memoization is alternative to table based iterative solution in Dynamic Programming) based implementation. In below implementation, we use a memoization table ‘mem’ to keep track of already solved problems. C++ Java Python3 C# Javascript // A Memoization based program to find maximum collection// using two traversals of a grid#include<bits/stdc++.h>using namespace std;#define R 5#define C 4 // checks whether a given input is valid or notbool isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect max valueint getMaxUtil(int arr[R][C], int mem[R][C][C], int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return INT_MIN; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last row but not at their destination if (x == R-1) return INT_MIN; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem int ans = INT_MIN; // this variable is used to store gain of current cell(s) int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive function getMaxUtil().// This function creates a table for memoization and calls// getMaxUtil()int geMaxCollection(int arr[R][C]){ // Create a memoization table and initialize all entries as -1 int mem[R][C][C]; memset(mem, -1, sizeof(mem)); // Calculation maximum value using memoization based function // getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver program to test above functionsint main(){ int arr[R][C] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; cout << "Maximum collection is " << geMaxCollection(arr); return 0;} // A Memoization based program to find maximum collection// using two traversals of a gridclass GFG{ static final int R = 5;static final int C = 4; // checks whether a given input is valid or notstatic boolean isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuestatic int getMaxUtil(int arr[][], int mem[][][], int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return Integer.MIN_VALUE; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return Integer.MIN_VALUE; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem int ans = Integer.MIN_VALUE; // this variable is used to store // gain of current cell(s) int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()static int geMaxCollection(int arr[][]){ // Create a memoization table and // initialize all entries as -1 int [][][]mem = new int[R][C][C]; for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { for(int l = 0; l < C; l++) mem[i][j][l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver codepublic static void main(String[] args){ int arr[][] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; System.out.print("Maximum collection is " + geMaxCollection(arr)); }} /* This code contributed by PrinciRaj1992 */ # A Memoization based program to find maximum collection# using two traversals of a grid R=5C=4intmin=-10000000intmax=10000000 # checks whether a given input is valid or notdef isValid(x,y1,y2): return ((x >= 0 and x < R and y1 >=0 and y1 < C and y2 >=0 and y2 < C)) # Driver function to collect max valuedef getMaxUtil(arr,mem,x,y1,y2): # ---------- BASE CASES ----------- if isValid(x, y1, y2)==False: return intmin # if both traversals reach their destinations if x == R-1 and y1 == 0 and y2 == C-1: if y1==y2: return arr[x][y1] else: return arr[x][y1]+arr[x][y2] # If both traversals are at last row # but not at their destination if x==R-1: return intmin # If subproblem is already solved if mem[x][y1][y2] != -1: return mem[x][y1][y2] # Initialize answer for this subproblem ans=intmin # this variable is used to store gain of current cell(s) temp=0 if y1==y2: temp=arr[x][y1] else: temp=arr[x][y1]+arr[x][y2] # Recur for all possible cases, then store and return the # one with max value ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)) mem[x][y1][y2] = ans return ans # This is mainly a wrapper over recursive# function getMaxUtil().# This function creates a table for memoization and calls# getMaxUtil() def geMaxCollection(arr): # Create a memoization table and # initialize all entries as -1 mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)] # Calculation maximum value using # memoization based function # getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1) # Driver program to test above functionsif __name__=='__main__': arr=[[3, 6, 8, 2], [5, 2, 4, 3], [1, 1, 20, 10], [1, 1, 20, 10], [1, 1, 20, 10], ] print('Maximum collection is ', geMaxCollection(arr)) #this code is contributed by sahilshelangia // A Memoization based program to find maximum collection// using two traversals of a gridusing System; class GFG{ static readonly int R = 5;static readonly int C = 4; // checks whether a given input is valid or notstatic bool isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuestatic int getMaxUtil(int [,]arr, int [,,]mem, int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return int.MinValue; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x, y1]: arr[x, y1] + arr[x, y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return int.MinValue; // If subproblem is already solved if (mem[x, y1, y2] != -1) return mem[x, y1, y2]; // Initialize answer for this subproblem int ans = int.MinValue; // this variable is used to store // gain of current cell(s) int temp = (y1 == y2)? arr[x, y1]: arr[x, y1] + arr[x, y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x, y1, y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()static int geMaxCollection(int [,]arr){ // Create a memoization table and // initialize all entries as -1 int [,,]mem = new int[R, C, C]; for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { for(int l = 0; l < C; l++) mem[i, j, l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver codepublic static void Main(String[] args){ int [,]arr = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; Console.Write("Maximum collection is " + geMaxCollection(arr)); }} // This code contributed by Rajput-Ji <script>// A Memoization based program to find maximum collection// using two traversals of a grid var R = 5; var C = 4; // checks whether a given input is valid or notfunction isValid(x , y1 , y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuefunction getMaxUtil(arr , mem, x , y1 , y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return Number.MIN_VALUE; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return Number.MIN_VALUE; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem var ans = Number.MIN_VALUE; // this variable is used to store // gain of current cell(s) var temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()function geMaxCollection(arr){ // Create a memoization table and // initialize all entries as -1 var mem = Array(R).fill().map(()=>Array(C).fill().map(()=>Array(C).fill(0))); for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { for(l = 0; l < C; l++) mem[i][j][l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver code var arr = [[3, 6, 8, 2], [5, 2, 4, 3], [1, 1, 20, 10], [1, 1, 20, 10], [1, 1, 20, 10], ]; document.write("Maximum collection is " + geMaxCollection(arr)); // This code is contributed by aashish1995</script> Output: Maximum collection is 73 Thanks to Gaurav Ahirwar for suggesting above problem and solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sahilshelangia princiraj1992 Rajput-Ji aashish1995 Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
[ { "code": null, "e": 26497, "s": 26469, "text": "\n31 May, 2021" }, { "code": null, "e": 27190, "s": 26497, "text": "Given a matrix where every cell represents points. How to collect maximum points using two traversals under following conditions?Let the dimensions of given grid be R x C.1) The first traversal starts from top left corner, i.e., (0, 0) and should reach left bottom corner, i.e., (R-1, 0). The second traversal starts from top right corner, i.e., (0, C-1) and should reach bottom right corner, i.e., (R-1, C-1)/2) From a point (i, j), we can move to (i+1, j+1) or (i+1, j-1) or (i+1, j)3) A traversal gets all points of a particular cell through which it passes. If one traversal has already collected points of a cell, then the other traversal gets no points if goes through that cell again. " }, { "code": null, "e": 27621, "s": 27190, "text": "Input :\n int arr[R][C] = {{3, 6, 8, 2},\n {5, 2, 4, 3},\n {1, 1, 20, 10},\n {1, 1, 20, 10},\n {1, 1, 20, 10},\n };\n\n Output: 73\n\nExplanation :\n\nFirst traversal collects total points of value 3 + 2 + 20 + 1 + 1 = 27\n\nSecond traversal collects total points of value 2 + 4 + 10 + 20 + 10 = 46.\nTotal Points collected = 27 + 46 = 73." }, { "code": null, "e": 28372, "s": 27621, "text": "We strongly recommend you to minimize your browser and try this yourself first. The idea is to do both traversals concurrently. We start first from (0, 0) and second traversal from (0, C-1) simultaneously. The important thing to note is, at any particular step both traversals will be in same row as in all possible three moves, row number is increased. Let (x1, y1) and (x2, y2) denote current positions of first and second traversals respectively. Thus at any time x1 will be equal to x2 as both of them move forward but variation is possible along y. Since variation in y could occur in 3 ways no change (y), go left (y – 1), go right (y + 1). So in total 9 combinations among y1, y2 are possible. The 9 cases as mentioned below after base cases. " }, { "code": null, "e": 29368, "s": 28372, "text": "Both traversals always move forward along x\nBase Cases:\n// If destinations reached\nif (x == R-1 && y1 == 0 && y2 == C-1)\nmaxPoints(arr, x, y1, y2) = arr[x][y1] + arr[x][y2];\n\n// If any of the two locations is invalid (going out of grid)\nif input is not valid\nmaxPoints(arr, x, y1, y2) = -INF (minus infinite)\n\n// If both traversals are at same cell, then we count the value of cell\n// only once.\nIf y1 and y2 are same\n result = arr[x][y1]\nElse\n result = arr[x][y1] + arr[x][y2] \n\nresult += max { // Max of 9 cases\n maxPoints(arr, x+1, y1+1, y2), \n maxPoints(arr, x+1, y1+1, y2+1),\n maxPoints(arr, x+1, y1+1, y2-1),\n maxPoints(arr, x+1, y1-1, y2), \n maxPoints(arr, x+1, y1-1, y2+1),\n maxPoints(arr, x+1, y1-1, y2-1),\n maxPoints(arr, x+1, y1, y2),\n maxPoints(arr, x+1, y1, y2+1),\n maxPoints(arr, x+1, y1, y2-1) \n }" }, { "code": null, "e": 29769, "s": 29368, "text": "The above recursive solution has many subproblems that are solved again and again. Therefore, we can use Dynamic Programming to solve the above problem more efficiently. Below is memoization (Memoization is alternative to table based iterative solution in Dynamic Programming) based implementation. In below implementation, we use a memoization table ‘mem’ to keep track of already solved problems. " }, { "code": null, "e": 29773, "s": 29769, "text": "C++" }, { "code": null, "e": 29778, "s": 29773, "text": "Java" }, { "code": null, "e": 29786, "s": 29778, "text": "Python3" }, { "code": null, "e": 29789, "s": 29786, "text": "C#" }, { "code": null, "e": 29800, "s": 29789, "text": "Javascript" }, { "code": "// A Memoization based program to find maximum collection// using two traversals of a grid#include<bits/stdc++.h>using namespace std;#define R 5#define C 4 // checks whether a given input is valid or notbool isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect max valueint getMaxUtil(int arr[R][C], int mem[R][C][C], int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return INT_MIN; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last row but not at their destination if (x == R-1) return INT_MIN; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem int ans = INT_MIN; // this variable is used to store gain of current cell(s) int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive function getMaxUtil().// This function creates a table for memoization and calls// getMaxUtil()int geMaxCollection(int arr[R][C]){ // Create a memoization table and initialize all entries as -1 int mem[R][C][C]; memset(mem, -1, sizeof(mem)); // Calculation maximum value using memoization based function // getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver program to test above functionsint main(){ int arr[R][C] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; cout << \"Maximum collection is \" << geMaxCollection(arr); return 0;}", "e": 32349, "s": 29800, "text": null }, { "code": "// A Memoization based program to find maximum collection// using two traversals of a gridclass GFG{ static final int R = 5;static final int C = 4; // checks whether a given input is valid or notstatic boolean isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuestatic int getMaxUtil(int arr[][], int mem[][][], int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return Integer.MIN_VALUE; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return Integer.MIN_VALUE; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem int ans = Integer.MIN_VALUE; // this variable is used to store // gain of current cell(s) int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()static int geMaxCollection(int arr[][]){ // Create a memoization table and // initialize all entries as -1 int [][][]mem = new int[R][C][C]; for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { for(int l = 0; l < C; l++) mem[i][j][l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver codepublic static void main(String[] args){ int arr[][] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; System.out.print(\"Maximum collection is \" + geMaxCollection(arr)); }} /* This code contributed by PrinciRaj1992 */", "e": 35351, "s": 32349, "text": null }, { "code": "# A Memoization based program to find maximum collection# using two traversals of a grid R=5C=4intmin=-10000000intmax=10000000 # checks whether a given input is valid or notdef isValid(x,y1,y2): return ((x >= 0 and x < R and y1 >=0 and y1 < C and y2 >=0 and y2 < C)) # Driver function to collect max valuedef getMaxUtil(arr,mem,x,y1,y2): # ---------- BASE CASES ----------- if isValid(x, y1, y2)==False: return intmin # if both traversals reach their destinations if x == R-1 and y1 == 0 and y2 == C-1: if y1==y2: return arr[x][y1] else: return arr[x][y1]+arr[x][y2] # If both traversals are at last row # but not at their destination if x==R-1: return intmin # If subproblem is already solved if mem[x][y1][y2] != -1: return mem[x][y1][y2] # Initialize answer for this subproblem ans=intmin # this variable is used to store gain of current cell(s) temp=0 if y1==y2: temp=arr[x][y1] else: temp=arr[x][y1]+arr[x][y2] # Recur for all possible cases, then store and return the # one with max value ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)) ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)) mem[x][y1][y2] = ans return ans # This is mainly a wrapper over recursive# function getMaxUtil().# This function creates a table for memoization and calls# getMaxUtil() def geMaxCollection(arr): # Create a memoization table and # initialize all entries as -1 mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)] # Calculation maximum value using # memoization based function # getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1) # Driver program to test above functionsif __name__=='__main__': arr=[[3, 6, 8, 2], [5, 2, 4, 3], [1, 1, 20, 10], [1, 1, 20, 10], [1, 1, 20, 10], ] print('Maximum collection is ', geMaxCollection(arr)) #this code is contributed by sahilshelangia", "e": 37870, "s": 35351, "text": null }, { "code": "// A Memoization based program to find maximum collection// using two traversals of a gridusing System; class GFG{ static readonly int R = 5;static readonly int C = 4; // checks whether a given input is valid or notstatic bool isValid(int x, int y1, int y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuestatic int getMaxUtil(int [,]arr, int [,,]mem, int x, int y1, int y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return int.MinValue; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x, y1]: arr[x, y1] + arr[x, y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return int.MinValue; // If subproblem is already solved if (mem[x, y1, y2] != -1) return mem[x, y1, y2]; // Initialize answer for this subproblem int ans = int.MinValue; // this variable is used to store // gain of current cell(s) int temp = (y1 == y2)? arr[x, y1]: arr[x, y1] + arr[x, y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.Max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x, y1, y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()static int geMaxCollection(int [,]arr){ // Create a memoization table and // initialize all entries as -1 int [,,]mem = new int[R, C, C]; for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { for(int l = 0; l < C; l++) mem[i, j, l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver codepublic static void Main(String[] args){ int [,]arr = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; Console.Write(\"Maximum collection is \" + geMaxCollection(arr)); }} // This code contributed by Rajput-Ji", "e": 40857, "s": 37870, "text": null }, { "code": "<script>// A Memoization based program to find maximum collection// using two traversals of a grid var R = 5; var C = 4; // checks whether a given input is valid or notfunction isValid(x , y1 , y2){ return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C);} // Driver function to collect Math.max valuefunction getMaxUtil(arr , mem, x , y1 , y2){ /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return Number.MIN_VALUE; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last // row but not at their destination if (x == R-1) return Number.MIN_VALUE; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem var ans = Number.MIN_VALUE; // this variable is used to store // gain of current cell(s) var temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = Math.max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans);} // This is mainly a wrapper over recursive// function getMaxUtil(). This function// creates a table for memoization and// calls getMaxUtil()function geMaxCollection(arr){ // Create a memoization table and // initialize all entries as -1 var mem = Array(R).fill().map(()=>Array(C).fill().map(()=>Array(C).fill(0))); for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { for(l = 0; l < C; l++) mem[i][j][l]=-1; } } // Calculation maximum value using memoization // based function getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1);} // Driver code var arr = [[3, 6, 8, 2], [5, 2, 4, 3], [1, 1, 20, 10], [1, 1, 20, 10], [1, 1, 20, 10], ]; document.write(\"Maximum collection is \" + geMaxCollection(arr)); // This code is contributed by aashish1995</script>", "e": 43763, "s": 40857, "text": null }, { "code": null, "e": 43772, "s": 43763, "text": "Output: " }, { "code": null, "e": 43797, "s": 43772, "text": "Maximum collection is 73" }, { "code": null, "e": 43990, "s": 43797, "text": "Thanks to Gaurav Ahirwar for suggesting above problem and solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 44005, "s": 43990, "text": "sahilshelangia" }, { "code": null, "e": 44019, "s": 44005, "text": "princiraj1992" }, { "code": null, "e": 44029, "s": 44019, "text": "Rajput-Ji" }, { "code": null, "e": 44041, "s": 44029, "text": "aashish1995" }, { "code": null, "e": 44061, "s": 44041, "text": "Dynamic Programming" }, { "code": null, "e": 44068, "s": 44061, "text": "Matrix" }, { "code": null, "e": 44088, "s": 44068, "text": "Dynamic Programming" }, { "code": null, "e": 44095, "s": 44088, "text": "Matrix" }, { "code": null, "e": 44193, "s": 44095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44224, "s": 44193, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 44257, "s": 44224, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 44292, "s": 44257, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 44360, "s": 44292, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 44381, "s": 44360, "text": "Edit Distance | DP-5" }, { "code": null, "e": 44416, "s": 44381, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 44460, "s": 44416, "text": "Program to find largest element in an array" }, { "code": null, "e": 44496, "s": 44460, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 44520, "s": 44496, "text": "Sudoku | Backtracking-7" } ]
Process Image
Now that we have seen how to get the basic information of process and its parent process, it is time to look into the details of process/program information. What exactly is process image? Process image is an executable file required while executing the program. This image usually contains the following sections − Code segment or text segment Data segment Stack segment Heap segment Following is the pictorial representation of the process image. Code segment is a portion of object file or program’s virtual address space that consists of executable instructions. This is usually read-only data segment and has a fixed size. Data segment is of two types. Initialized Un-initialized Initialized data segment is a portion of the object file or program’s virtual address space that consists of initialized static and global variables. Un-initialized data segment is a portion of the object file or program’s virtual address space that consists of uninitialized static and global variables. Un-initialized data segment is also called BSS (Block Started by Symbol) segment. Data segment is read-write, since the values of variables could be changed during run time. This segment also has a fixed size. Stack segment is an area of memory allotted for automatic variables and function parameters. It also stores a return address while executing function calls. Stack uses LIFO (Last-In-First-Out) mechanism for storing local or automatic variables, function parameters and storing next address or return address. The return address refers to the address to return after completion of function execution. This segment size is variable as per local variables, function parameters, and function calls. This segment grows from a higher address to a lower address. Heap segment is area of memory allotted for dynamic memory storage such as for malloc() and calloc() calls. This segment size is also variable as per user allocation. This segment grows from a lower address to a higher address. Let us now check how the segments (data and bss segments) size vary with a few sample programs. Segment size is known by executing the command “size”. #include<stdio.h> int main() { printf("Hello World\n"); return 0; } In the following program, an uninitialized static variable is added. This means uninitialized segment (BSS) size would increase by 4 Bytes. Note − In Linux operating system, the size of int is 4 bytes. Size of the integer data type depends on the compiler and operating system support. #include<stdio.h> int main() { static int mystaticint1; printf("Hello World\n"); return 0; } In the following program, an initialized static variable is added. This means initialized segment (DATA) size would increase by 4 Bytes. #include<stdio.h> int main() { static int mystaticint1; static int mystaticint2 = 100; printf("Hello World\n"); return 0; } In the following program, an initialized global variable is added. This means initialized segment (DATA) size would increase by 4 Bytes. #include<stdio.h> int myglobalint1 = 500; int main() { static int mystaticint1; static int mystaticint2 = 100; printf("Hello World\n"); return 0; } In the following program, an uninitialized global variable is added. This means uninitialized segment (BSS) size would increase by 4 Bytes. #include<stdio.h> int myglobalint1 = 500; int myglobalint2; int main() { static int mystaticint1; static int mystaticint2 = 100; printf("Hello World\n"); return 0; } babukrishnam $ gcc segment_size1.c -o segment_size1 babukrishnam $ gcc segment_size2.c -o segment_size2 babukrishnam $ gcc segment_size3.c -o segment_size3 babukrishnam $ gcc segment_size4.c -o segment_size4 babukrishnam $ gcc segment_size5.c -o segment_size5 babukrishnam size segment_size1 segment_size2 segment_size3 segment_size4 segment_size5 text data bss dec hex filename 878 252 8 1138 472 segment_size1 878 252 12 1142 476 segment_size2 878 256 12 1146 47a segment_size3 878 260 12 1150 47e segment_size4 878 260 16 1154 482 segment_size5 babukrishnam 21 Lectures 2.5 hours Asif Hussain 14 Lectures 57 mins Kaushik Roy Chowdhury 5 Lectures 2 hours Manish Gupta 35 Lectures 2.5 hours Manish Gupta 16 Lectures 2 hours Pranjal Srivastava 22 Lectures 2.5 hours J Aatish Rao Print Add Notes Bookmark this page
[ { "code": null, "e": 2029, "s": 1871, "text": "Now that we have seen how to get the basic information of process and its parent process, it is time to look into the details of process/program information." }, { "code": null, "e": 2187, "s": 2029, "text": "What exactly is process image? Process image is an executable file required while executing the program. This image usually contains the following sections −" }, { "code": null, "e": 2216, "s": 2187, "text": "Code segment or text segment" }, { "code": null, "e": 2229, "s": 2216, "text": "Data segment" }, { "code": null, "e": 2243, "s": 2229, "text": "Stack segment" }, { "code": null, "e": 2256, "s": 2243, "text": "Heap segment" }, { "code": null, "e": 2320, "s": 2256, "text": "Following is the pictorial representation of the process image." }, { "code": null, "e": 2499, "s": 2320, "text": "Code segment is a portion of object file or program’s virtual address space that consists of executable instructions. This is usually read-only data segment and has a fixed size." }, { "code": null, "e": 2529, "s": 2499, "text": "Data segment is of two types." }, { "code": null, "e": 2541, "s": 2529, "text": "Initialized" }, { "code": null, "e": 2556, "s": 2541, "text": "Un-initialized" }, { "code": null, "e": 2706, "s": 2556, "text": "Initialized data segment is a portion of the object file or program’s virtual address space that consists of initialized static and global variables." }, { "code": null, "e": 2943, "s": 2706, "text": "Un-initialized data segment is a portion of the object file or program’s virtual address space that consists of uninitialized static and global variables. Un-initialized data segment is also called BSS (Block Started by Symbol) segment." }, { "code": null, "e": 3071, "s": 2943, "text": "Data segment is read-write, since the values of variables could be changed during run time. This segment also has a fixed size." }, { "code": null, "e": 3627, "s": 3071, "text": "Stack segment is an area of memory allotted for automatic variables and function parameters. It also stores a return address while executing function calls. Stack uses LIFO (Last-In-First-Out) mechanism for storing local or automatic variables, function parameters and storing next address or return address. The return address refers to the address to return after completion of function execution. This segment size is variable as per local variables, function parameters, and function calls. This segment grows from a higher address to a lower address." }, { "code": null, "e": 3855, "s": 3627, "text": "Heap segment is area of memory allotted for dynamic memory storage such as for malloc() and calloc() calls. This segment size is also variable as per user allocation. This segment grows from a lower address to a higher address." }, { "code": null, "e": 4006, "s": 3855, "text": "Let us now check how the segments (data and bss segments) size vary with a few sample programs. Segment size is known by executing the command “size”." }, { "code": null, "e": 4081, "s": 4006, "text": "#include<stdio.h>\n\nint main() {\n printf(\"Hello World\\n\");\n return 0;\n}" }, { "code": null, "e": 4367, "s": 4081, "text": "In the following program, an uninitialized static variable is added. This means uninitialized segment (BSS) size would increase by 4 Bytes. Note − In Linux operating system, the size of int is 4 bytes. Size of the integer data type depends on the compiler and operating system support." }, { "code": null, "e": 4470, "s": 4367, "text": "#include<stdio.h>\n\nint main() {\n static int mystaticint1;\n printf(\"Hello World\\n\");\n return 0;\n}" }, { "code": null, "e": 4607, "s": 4470, "text": "In the following program, an initialized static variable is added. This means initialized segment (DATA) size would increase by 4 Bytes." }, { "code": null, "e": 4744, "s": 4607, "text": "#include<stdio.h>\n\nint main() {\n static int mystaticint1;\n static int mystaticint2 = 100;\n printf(\"Hello World\\n\");\n return 0;\n}" }, { "code": null, "e": 4881, "s": 4744, "text": "In the following program, an initialized global variable is added. This means initialized segment (DATA) size would increase by 4 Bytes." }, { "code": null, "e": 5042, "s": 4881, "text": "#include<stdio.h>\n\nint myglobalint1 = 500;\nint main() {\n static int mystaticint1;\n static int mystaticint2 = 100;\n printf(\"Hello World\\n\");\n return 0;\n}" }, { "code": null, "e": 5182, "s": 5042, "text": "In the following program, an uninitialized global variable is added. This means uninitialized segment (BSS) size would increase by 4 Bytes." }, { "code": null, "e": 5361, "s": 5182, "text": "#include<stdio.h>\n\nint myglobalint1 = 500;\nint myglobalint2;\nint main() {\n static int mystaticint1;\n static int mystaticint2 = 100;\n printf(\"Hello World\\n\");\n return 0;\n}" }, { "code": null, "e": 5621, "s": 5361, "text": "babukrishnam $ gcc segment_size1.c -o segment_size1\nbabukrishnam $ gcc segment_size2.c -o segment_size2\nbabukrishnam $ gcc segment_size3.c -o segment_size3\nbabukrishnam $ gcc segment_size4.c -o segment_size4\nbabukrishnam $ gcc segment_size5.c -o segment_size5" }, { "code": null, "e": 5986, "s": 5621, "text": "babukrishnam size segment_size1 segment_size2 segment_size3 segment_size4 segment_size5\n text data bss dec hex filename\n 878 252 8 1138 472 segment_size1 \n 878 252 12 1142 476 segment_size2 \n 878 256 12 1146 47a segment_size3 \n 878 260 12 1150 47e segment_size4 \n 878 260 16 1154 482 segment_size5\nbabukrishnam\n" }, { "code": null, "e": 6021, "s": 5986, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6035, "s": 6021, "text": " Asif Hussain" }, { "code": null, "e": 6067, "s": 6035, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 6090, "s": 6067, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6122, "s": 6090, "text": "\n 5 Lectures \n 2 hours \n" }, { "code": null, "e": 6136, "s": 6122, "text": " Manish Gupta" }, { "code": null, "e": 6171, "s": 6136, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6185, "s": 6171, "text": " Manish Gupta" }, { "code": null, "e": 6218, "s": 6185, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6238, "s": 6218, "text": " Pranjal Srivastava" }, { "code": null, "e": 6273, "s": 6238, "text": "\n 22 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6287, "s": 6273, "text": " J Aatish Rao" }, { "code": null, "e": 6294, "s": 6287, "text": " Print" }, { "code": null, "e": 6305, "s": 6294, "text": " Add Notes" } ]
How to Install Nipe tool in Kali Linux? - GeeksforGeeks
05 Oct, 2021 Nipe is a program that uses the Tor network as the user’s default gateway, routing all traffic on the Tor network, which is often used to provide privacy and anonymity. It should be emphasized that hiding an IP address alone will not provide anonymity when using a tool for privacy and anonymity, as DNS information may still be exposed. Both IP and DNS information must be hidden. Staying anonymous is a great way to protect yourself from all kinds of surveillance. However, we only have a few options because VPNs, especially free ones, are quite ineffective. We can be tracked because a free VPN maintains logs. We can just use the TOR network instead of the browser. Tor is quite difficult to track (close to practically impossible). In this article, we will see about Nipe. This Perl script allows us to quickly route all of our traffic from our computers to the Tor network, allowing us to access the Internet without fear or intimidation. Step 1: Open a terminal and navigate to the Desktop directory (or directory of your choice). Then, using the following command, we must clone this repository from GitHub: cd nipe Step 2: Then, using the following command, we must clone this repository from GitHub: git clone https://github.com/htrgouvea/nipe Enter the following command to go to the Nipe directory: cd nipe Step 3: Now we have to run the following command to install the libraries and dependencies: When prompted to perform an automatic installation, press Enter: sudo cpan install Try::Tiny Config::Simple JSON Step 4: After that, we can use the following command to install Nipe dependencies or a Perl script: Nipe must be run as root. sudo perl nipe.pl install The installation procedure will then begin. After installation, we received a notification that some services need to be restarted; At this point, we press the “Tab” button and select OK. Finally, our installation process is complete. To check the status of nipe, type the following command. And you will see that the current status is disabled. sudo perl nipe.pl status Type the following command to start the Nipe service: sudo perl nipe.pl start You will immediately receive a new anonymous IP address, which you can verify with the URL “https://www.whatismyip.com/”. When we’re finished, we may exit Tor and return to our original IP address by running the following command: sudo perl nipe.pl stop After running the above command, NIPE will be terminated, and we will be returned to our original IP address. We can also check the status. If you want to restart the nip service, you can use the following command: sudo perl nipe.pl restart Through its own system, the Tor Project allows users to access the Internet, chat, and send instant messages anonymously. It is used by a wide range of individuals, businesses, and organizations for both legal and illegal reasons. Tor has been widely used by intelligence agencies, hacker organizations, criminal operations, and even by regular people concerned about their online privacy. Nipe is a Perl engine that tries to make the Tor network your default network gateway. Knip can deliver traffic from your system to the Internet via the Tor network, allowing you to surf the Internet with a strong position on privacy and anonymity in cyberspace. how-to-install Kali-Linux Linux-Tools How To Installation Guide Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n05 Oct, 2021" }, { "code": null, "e": 26579, "s": 26197, "text": "Nipe is a program that uses the Tor network as the user’s default gateway, routing all traffic on the Tor network, which is often used to provide privacy and anonymity. It should be emphasized that hiding an IP address alone will not provide anonymity when using a tool for privacy and anonymity, as DNS information may still be exposed. Both IP and DNS information must be hidden." }, { "code": null, "e": 26935, "s": 26579, "text": "Staying anonymous is a great way to protect yourself from all kinds of surveillance. However, we only have a few options because VPNs, especially free ones, are quite ineffective. We can be tracked because a free VPN maintains logs. We can just use the TOR network instead of the browser. Tor is quite difficult to track (close to practically impossible)." }, { "code": null, "e": 27143, "s": 26935, "text": "In this article, we will see about Nipe. This Perl script allows us to quickly route all of our traffic from our computers to the Tor network, allowing us to access the Internet without fear or intimidation." }, { "code": null, "e": 27314, "s": 27143, "text": "Step 1: Open a terminal and navigate to the Desktop directory (or directory of your choice). Then, using the following command, we must clone this repository from GitHub:" }, { "code": null, "e": 27322, "s": 27314, "text": "cd nipe" }, { "code": null, "e": 27408, "s": 27322, "text": "Step 2: Then, using the following command, we must clone this repository from GitHub:" }, { "code": null, "e": 27452, "s": 27408, "text": "git clone https://github.com/htrgouvea/nipe" }, { "code": null, "e": 27509, "s": 27452, "text": "Enter the following command to go to the Nipe directory:" }, { "code": null, "e": 27517, "s": 27509, "text": "cd nipe" }, { "code": null, "e": 27609, "s": 27517, "text": "Step 3: Now we have to run the following command to install the libraries and dependencies:" }, { "code": null, "e": 27674, "s": 27609, "text": "When prompted to perform an automatic installation, press Enter:" }, { "code": null, "e": 27722, "s": 27674, "text": "sudo cpan install Try::Tiny Config::Simple JSON" }, { "code": null, "e": 27822, "s": 27722, "text": "Step 4: After that, we can use the following command to install Nipe dependencies or a Perl script:" }, { "code": null, "e": 27848, "s": 27822, "text": "Nipe must be run as root." }, { "code": null, "e": 27874, "s": 27848, "text": "sudo perl nipe.pl install" }, { "code": null, "e": 28062, "s": 27874, "text": "The installation procedure will then begin. After installation, we received a notification that some services need to be restarted; At this point, we press the “Tab” button and select OK." }, { "code": null, "e": 28109, "s": 28062, "text": "Finally, our installation process is complete." }, { "code": null, "e": 28220, "s": 28109, "text": "To check the status of nipe, type the following command. And you will see that the current status is disabled." }, { "code": null, "e": 28245, "s": 28220, "text": "sudo perl nipe.pl status" }, { "code": null, "e": 28299, "s": 28245, "text": "Type the following command to start the Nipe service:" }, { "code": null, "e": 28323, "s": 28299, "text": "sudo perl nipe.pl start" }, { "code": null, "e": 28445, "s": 28323, "text": "You will immediately receive a new anonymous IP address, which you can verify with the URL “https://www.whatismyip.com/”." }, { "code": null, "e": 28554, "s": 28445, "text": "When we’re finished, we may exit Tor and return to our original IP address by running the following command:" }, { "code": null, "e": 28577, "s": 28554, "text": "sudo perl nipe.pl stop" }, { "code": null, "e": 28717, "s": 28577, "text": "After running the above command, NIPE will be terminated, and we will be returned to our original IP address. We can also check the status." }, { "code": null, "e": 28792, "s": 28717, "text": "If you want to restart the nip service, you can use the following command:" }, { "code": null, "e": 28818, "s": 28792, "text": "sudo perl nipe.pl restart" }, { "code": null, "e": 29208, "s": 28818, "text": "Through its own system, the Tor Project allows users to access the Internet, chat, and send instant messages anonymously. It is used by a wide range of individuals, businesses, and organizations for both legal and illegal reasons. Tor has been widely used by intelligence agencies, hacker organizations, criminal operations, and even by regular people concerned about their online privacy." }, { "code": null, "e": 29471, "s": 29208, "text": "Nipe is a Perl engine that tries to make the Tor network your default network gateway. Knip can deliver traffic from your system to the Internet via the Tor network, allowing you to surf the Internet with a strong position on privacy and anonymity in cyberspace." }, { "code": null, "e": 29486, "s": 29471, "text": "how-to-install" }, { "code": null, "e": 29497, "s": 29486, "text": "Kali-Linux" }, { "code": null, "e": 29509, "s": 29497, "text": "Linux-Tools" }, { "code": null, "e": 29516, "s": 29509, "text": "How To" }, { "code": null, "e": 29535, "s": 29516, "text": "Installation Guide" }, { "code": null, "e": 29546, "s": 29535, "text": "Linux-Unix" }, { "code": null, "e": 29644, "s": 29546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29678, "s": 29644, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29736, "s": 29678, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29785, "s": 29736, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29832, "s": 29785, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 29892, "s": 29832, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29925, "s": 29892, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29959, "s": 29925, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29994, "s": 29959, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 30052, "s": 29994, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
CharBuffer flip() methods in Java with Examples - GeeksforGeeks
23 Jul, 2019 The flip() method of java.nio.CharBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations. For example: buf.put(magic); // Prepend headerin.read(buf); // Read data into rest of bufferbuf.flip(); // Flip bufferout.write(buf); // Write header + data to channel This method is often used in conjunction with the compact() method when transferring data from one place to another. Syntax: public final CharBuffer flip() Return Value: This method returns this buffer. Below are the examples to illustrate the flip() method: Examples 1: // Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the char array char[] cb = { 'a', 'b', 'c' }; // wrap the char array into CharBuffer // using wrap() method CharBuffer charBuffe r = CharBuffer.wrap(cb); // set position at index 1 charBuffer.position(1); // print the char buffer System.out.println("CharBuffer before flip: " + Arrays.toString( charBuffer.array()) + "\nPosition: " + charBuffer.position() + "\nLimit: " + charBuffer.limit()); // Flip the charBuffer // using flip() method charBuffer.flip(); // print the byte buffer System.out.println("\nCharBuffer after flip: " + Arrays.toString( charBuffer.array()) + "\nPosition: " + charBuffer.position() + "\nLimit: " + charBuffer.limit()); }} CharBuffer before flip: [a, b, c] Position: 1 Limit: 3 CharBuffer after flip: [a, b, c] Position: 0 Limit: 1 Examples 2: // Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating CharBuffer // using allocate() method CharBuffer charBuffer = CharBuffer.allocate(4); // append char value in charBuffer // using append() method charBuffer.append('a'); charBuffer.append('b'); // print the char buffer System.out.println("CharBuffer before flip: " + Arrays.toString( charBuffer.array()) + "\nPosition: " + charBuffer.position() + "\nLimit: " + charBuffer.limit()); // Flip the charBuffer // using flip() method charBuffer.flip(); // print the char buffer System.out.println("CharBuffer before flip: " + Arrays.toString( charBuffer.array()) + "\nPosition: " + charBuffer.position() + "\nLimit: " + charBuffer.limit()); }} CharBuffer before flip: [a, b, c, ] Position: 3 Limit: 4 CharBuffer before flip: [a, b, c, ] Position: 0 Limit: 3 Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#flip– Java-CharBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Multithreading in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24388, "s": 24360, "text": "\n23 Jul, 2019" }, { "code": null, "e": 24730, "s": 24388, "text": "The flip() method of java.nio.CharBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations." }, { "code": null, "e": 24743, "s": 24730, "text": "For example:" }, { "code": null, "e": 24898, "s": 24743, "text": "buf.put(magic); // Prepend headerin.read(buf); // Read data into rest of bufferbuf.flip(); // Flip bufferout.write(buf); // Write header + data to channel" }, { "code": null, "e": 25015, "s": 24898, "text": "This method is often used in conjunction with the compact() method when transferring data from one place to another." }, { "code": null, "e": 25023, "s": 25015, "text": "Syntax:" }, { "code": null, "e": 25054, "s": 25023, "text": "public final CharBuffer flip()" }, { "code": null, "e": 25101, "s": 25054, "text": "Return Value: This method returns this buffer." }, { "code": null, "e": 25157, "s": 25101, "text": "Below are the examples to illustrate the flip() method:" }, { "code": null, "e": 25169, "s": 25157, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the char array char[] cb = { 'a', 'b', 'c' }; // wrap the char array into CharBuffer // using wrap() method CharBuffer charBuffe r = CharBuffer.wrap(cb); // set position at index 1 charBuffer.position(1); // print the char buffer System.out.println(\"CharBuffer before flip: \" + Arrays.toString( charBuffer.array()) + \"\\nPosition: \" + charBuffer.position() + \"\\nLimit: \" + charBuffer.limit()); // Flip the charBuffer // using flip() method charBuffer.flip(); // print the byte buffer System.out.println(\"\\nCharBuffer after flip: \" + Arrays.toString( charBuffer.array()) + \"\\nPosition: \" + charBuffer.position() + \"\\nLimit: \" + charBuffer.limit()); }}", "e": 26457, "s": 25169, "text": null }, { "code": null, "e": 26568, "s": 26457, "text": "CharBuffer before flip: [a, b, c]\nPosition: 1\nLimit: 3\n\nCharBuffer after flip: [a, b, c]\nPosition: 0\nLimit: 1\n" }, { "code": null, "e": 26580, "s": 26568, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating CharBuffer // using allocate() method CharBuffer charBuffer = CharBuffer.allocate(4); // append char value in charBuffer // using append() method charBuffer.append('a'); charBuffer.append('b'); // print the char buffer System.out.println(\"CharBuffer before flip: \" + Arrays.toString( charBuffer.array()) + \"\\nPosition: \" + charBuffer.position() + \"\\nLimit: \" + charBuffer.limit()); // Flip the charBuffer // using flip() method charBuffer.flip(); // print the char buffer System.out.println(\"CharBuffer before flip: \" + Arrays.toString( charBuffer.array()) + \"\\nPosition: \" + charBuffer.position() + \"\\nLimit: \" + charBuffer.limit()); }}", "e": 27842, "s": 26580, "text": null }, { "code": null, "e": 27959, "s": 27842, "text": "CharBuffer before flip: [a, b, c, ]\nPosition: 3\nLimit: 4\nCharBuffer before flip: [a, b, c, ]\nPosition: 0\nLimit: 3\n" }, { "code": null, "e": 28043, "s": 27959, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#flip–" }, { "code": null, "e": 28059, "s": 28043, "text": "Java-CharBuffer" }, { "code": null, "e": 28074, "s": 28059, "text": "Java-Functions" }, { "code": null, "e": 28091, "s": 28074, "text": "Java-NIO package" }, { "code": null, "e": 28096, "s": 28091, "text": "Java" }, { "code": null, "e": 28101, "s": 28096, "text": "Java" }, { "code": null, "e": 28199, "s": 28101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28208, "s": 28199, "text": "Comments" }, { "code": null, "e": 28221, "s": 28208, "text": "Old Comments" }, { "code": null, "e": 28251, "s": 28221, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28302, "s": 28251, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28334, "s": 28302, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28353, "s": 28334, "text": "Interfaces in Java" }, { "code": null, "e": 28371, "s": 28353, "text": "ArrayList in Java" }, { "code": null, "e": 28402, "s": 28371, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28434, "s": 28402, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28457, "s": 28434, "text": "Multithreading in Java" }, { "code": null, "e": 28481, "s": 28457, "text": "Singleton Class in Java" } ]
Vertex cover Problem
For an undirected graph, the vertex cover is a subset of the vertices, where for every edge (u, v) of the graph either u or v is in the set. Using a binary tree, we can easily solve the vertex cover problem. This problem can be divided into two sub-problems. When the root is part of the vertex cover. For this case, the root covers all children edges. We can simply find the size of vertex cover for left and right sub-tree, and add 1 for the root. Input: A binary tree. Output: The vertex cover is 3. vertexCover(root node) In this problem, one binary tree will be formed, each node will hold the data and number of vertices covered by that node. Input − The root of the binary tree. Output − The number of vertices covered by root. Begin if root is φ, then return 0 if root has no child, then return 0 if vCover(root) ≠ 0, then return vCover(root) withRoot := 1 + vertexCover(left(root)) + vertexCover(right(root)) withoutRoot := 0 if root has left child, then withoutRoot := withoutRoot + vertexCover(left(left(root))) + vertexCover(left(right(root))) if root has right child, then withoutRoot := withoutRoot + vertexCover(right(left(root))) + vertexCover(right(right(root))) return vCover(root) End #include <iostream> #include <algorithm> using namespace std; struct node { int data; int vCover; node *left, *right; }; node *getNode(int data) { node *newNode = new (node); newNode->data = data; newNode->vCover = 0; //set vertex cover to 0 newNode->left = NULL; newNode->right = NULL; return newNode; //newly created node } int vertexCover(node *root) { if(root == NULL) //when tree is empty return 0; if(root->left == NULL && root->right == NULL) //when no other edge from root return 0; if(root->vCover != 0) //when vertex cover of this node is found, leave that node return root->vCover; int sizeWithRoot = 1 + vertexCover(root->left) + vertexCover(root->right); int sizeWithOutRoot = 0; if(root->left != NULL) //when root is not included and go for left child sizeWithOutRoot += 1 + vertexCover(root->left->left) + vertexCover(root->left->right); if(root->right != NULL) //when root is not included and go for right child sizeWithOutRoot += 1 + vertexCover(root->right->left) + vertexCover(root->right->right); root->vCover = (sizeWithRoot < sizeWithOutRoot)?sizeWithRoot:sizeWithOutRoot; //minimum vertex cover return root->vCover; } int main() { //create tree to check vertex cover node *root = getNode(20); root->left = getNode(8); root->right = getNode(22); root->left->left = getNode(4); root->left->right = getNode(12); root->left->right->left = getNode(10); root->left->right->right = getNode(14); root->right->right = getNode(25); cout << "Minimal vertex cover: " << vertexCover(root); } Minimal vertex cover: 3
[ { "code": null, "e": 1203, "s": 1062, "text": "For an undirected graph, the vertex cover is a subset of the vertices, where for every edge (u, v) of the graph either u or v is in the set." }, { "code": null, "e": 1270, "s": 1203, "text": "Using a binary tree, we can easily solve the vertex cover problem." }, { "code": null, "e": 1512, "s": 1270, "text": "This problem can be divided into two sub-problems. When the root is part of the vertex cover. For this case, the root covers all children edges. We can simply find the size of vertex cover for left and right sub-tree, and add 1 for the root." }, { "code": null, "e": 1567, "s": 1512, "text": "Input:\nA binary tree.\nOutput:\nThe vertex cover is 3.\n " }, { "code": null, "e": 1590, "s": 1567, "text": "vertexCover(root node)" }, { "code": null, "e": 1713, "s": 1590, "text": "In this problem, one binary tree will be formed, each node will hold the data and number of vertices covered by that node." }, { "code": null, "e": 1750, "s": 1713, "text": "Input − The root of the binary tree." }, { "code": null, "e": 1799, "s": 1750, "text": "Output − The number of vertices covered by root." }, { "code": null, "e": 2324, "s": 1799, "text": "Begin\n if root is φ, then\n return 0\n if root has no child, then\n return 0\n if vCover(root) ≠ 0, then\n return vCover(root)\n withRoot := 1 + vertexCover(left(root)) + vertexCover(right(root))\n withoutRoot := 0\n\n if root has left child, then\n withoutRoot := withoutRoot + vertexCover(left(left(root))) + vertexCover(left(right(root)))\n if root has right child, then\n withoutRoot := withoutRoot + vertexCover(right(left(root))) + vertexCover(right(right(root)))\n return vCover(root)\nEnd" }, { "code": null, "e": 3979, "s": 2324, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nstruct node {\n int data;\n int vCover;\n node *left, *right;\n};\n\nnode *getNode(int data) {\n node *newNode = new (node);\n newNode->data = data;\n newNode->vCover = 0; //set vertex cover to 0\n newNode->left = NULL;\n newNode->right = NULL;\n return newNode; //newly created node\n}\n\nint vertexCover(node *root) {\n if(root == NULL) //when tree is empty\n return 0;\n if(root->left == NULL && root->right == NULL) //when no other edge from root\n return 0;\n \n if(root->vCover != 0) //when vertex cover of this node is found, leave that node\n return root->vCover;\n \n int sizeWithRoot = 1 + vertexCover(root->left) + vertexCover(root->right);\n int sizeWithOutRoot = 0;\n \n if(root->left != NULL) //when root is not included and go for left child\n sizeWithOutRoot += 1 + vertexCover(root->left->left) + vertexCover(root->left->right);\n if(root->right != NULL) //when root is not included and go for right child\n sizeWithOutRoot += 1 + vertexCover(root->right->left) + vertexCover(root->right->right);\n \n root->vCover = (sizeWithRoot < sizeWithOutRoot)?sizeWithRoot:sizeWithOutRoot; //minimum vertex cover\n return root->vCover;\n}\n\nint main() {\n //create tree to check vertex cover\n node *root = getNode(20);\n root->left = getNode(8); root->right = getNode(22);\n root->left->left = getNode(4); root->left->right = getNode(12);\n root->left->right->left = getNode(10); root->left->right->right = getNode(14);\n root->right->right = getNode(25);\n cout << \"Minimal vertex cover: \" << vertexCover(root);\n}" }, { "code": null, "e": 4003, "s": 3979, "text": "Minimal vertex cover: 3" } ]
Python IMDbPY – Searching movies matching with keyword - GeeksforGeeks
11 May, 2021 In this article we will see how we can find movies that have similar keyword. Keyword is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discover titles.In order to get movies that have similar keywords we use get_keyword method. Syntax : imdb_object.get_keyword(keyword)Argument : It takes string as argument i.e keywordReturn : It return list of movies object Below is implementation. Python3 # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # keywordkeyword = "marvel" # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0]) Output : 50 Thor: Love and Thunder Another example Python3 # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # keywordkeyword = "heaven" # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0]) Output : 50 The Good Place (2016–2020)) sweetyty Python IMDbPY-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26409, "s": 26381, "text": "\n11 May, 2021" }, { "code": null, "e": 26843, "s": 26409, "text": "In this article we will see how we can find movies that have similar keyword. Keyword is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discover titles.In order to get movies that have similar keywords we use get_keyword method. " }, { "code": null, "e": 26977, "s": 26843, "text": "Syntax : imdb_object.get_keyword(keyword)Argument : It takes string as argument i.e keywordReturn : It return list of movies object " }, { "code": null, "e": 27004, "s": 26977, "text": "Below is implementation. " }, { "code": null, "e": 27012, "s": 27004, "text": "Python3" }, { "code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # keywordkeyword = \"marvel\" # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0])", "e": 27229, "s": 27012, "text": null }, { "code": null, "e": 27239, "s": 27229, "text": "Output : " }, { "code": null, "e": 27265, "s": 27239, "text": "50\nThor: Love and Thunder" }, { "code": null, "e": 27282, "s": 27265, "text": "Another example " }, { "code": null, "e": 27290, "s": 27282, "text": "Python3" }, { "code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # keywordkeyword = \"heaven\" # searching keywordsearch = ia.get_keyword(keyword) # printing the searchprint(len(search))print(search[0])", "e": 27507, "s": 27290, "text": null }, { "code": null, "e": 27517, "s": 27507, "text": "Output : " }, { "code": null, "e": 27548, "s": 27517, "text": "50\nThe Good Place (2016–2020))" }, { "code": null, "e": 27559, "s": 27550, "text": "sweetyty" }, { "code": null, "e": 27580, "s": 27559, "text": "Python IMDbPY-module" }, { "code": null, "e": 27587, "s": 27580, "text": "Python" }, { "code": null, "e": 27685, "s": 27587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27703, "s": 27685, "text": "Python Dictionary" }, { "code": null, "e": 27735, "s": 27703, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27757, "s": 27735, "text": "Enumerate() in Python" }, { "code": null, "e": 27799, "s": 27757, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27829, "s": 27799, "text": "Iterate over a list in Python" }, { "code": null, "e": 27855, "s": 27829, "text": "Python String | replace()" }, { "code": null, "e": 27899, "s": 27855, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27928, "s": 27899, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27965, "s": 27928, "text": "Create a Pandas DataFrame from Lists" } ]
Problems on Work and Wages - GeeksforGeeks
07 Oct, 2021 Question 1: Ram and Shyam undertake a piece of work for Rs 300. Ram can do it in 20 days and Shaym can do it in 60 days. With the help of Radha, they finish it in 10 days. How much should Radha be paid for her contribution? Solution: Ram alone takes 20 days and Shyam alone takes 60 days to finish the work. All together can finish in 10 days. Let the total work done is LCM(10, 20, 60) = 60 Ram’s efficiency = 60/20 = 3 Shyam’s efficiency = 60/60 = 1 Combined Efficiency = 60/10= 6 Radha’s efficiency = 6 – 3 -1 = 2 efficiency ratio = 3:1:2 therefore radha’s money = (2/6)*300=100 rs Question 2: A can do a piece of work in 30 days. He works only for 5 days and left, then B finishes the remaining work in 15 more days. In how many days will A and B together finish the work? Solution: 25 days work of A completed by B in 15 days. 25A=15B A/B=3/5 A’s efficiency = 3 B’s efficiency = 5 Total work done= 3 * 30 = 90 Work done by A and B together=total work done/total efficiency = 90/8 = 11.25 days Question 3: Twenty five employees can finish a project in 40 days.After how many days should 10 employees leave the job so that the project is finished in 50 days. Solution: Let n be the number of days when 10 employees left the project. Total work done= 25*40= 1000 25x + (50 – x)15 = 1000 25x + 750 – 15x = 1000 10x = 250 x = 25 Hence, after 25 days 10 employees left the job. Alternate: 25 employees * 40 days = 1000 units of work After leaving 10 employees the job, we have 50 days to complete the work. In 50 days only 15 employees will do the work work done by 15 employees = 15 * 50 =750 units of work Remaining units =1000-750 =250 Units of work done by 10 employees = 250/10 =25 So after 25 days 10 employees should leave the job. Question 4: A can type 85 pages in 10 hours. A and B together can type 500 pages in 40 hours.How much time B will take to type 80 pages. Solution: A can type 85 pages in 10 hours Then, A can type 340 pages in 40 hours. A and B together can type 500 pages in 40 hours So, B can type number of pages= 500 – 340 = 160 pages in 40 hours. Hence, B can type 80 pages in 20 hours. Question 5: A, B and C can do a piece of work in 10, 12 and 15 days respectively.They all start the work together but A leaves after the 2 days of work and B leaves 3 days before the work is completed.Find the number of days the work completed. Solution: Total work done is LCM(10, 12, 15)=60 unit A’s efficiency = 60/10= 6 B’s efficiency = 60/12= 5 C’s efficiency = 60/15= 4 First two days all work together So, the work completed in first two days= 15 x 2 = 30 unit Remaining work= 60 – 30 = 30 unit If B completes 3 day work also = 3 x 5 = 15 unit Total work remaining= 30 + 15 = 45 unit Number of days B and C works= 45/9=5 Total number of days to complete the work = 2 + 5 = 7 days. Question 6: A can do 1/6 work in 4 days and B can do 1/5 of the same work in 6 days. In how many days both will finish the work? Solution: A can complete the work in 6*4 = 24 days B can complete the work in 5*6 = 30 days Total work done LCM(24, 30)= 120 unit A’s efficiency = 120/24= 5 B’s efficiency = 120/30= 4 Total time taken = total work done/ total efficiency = 120/9 = 40/3 days Question 7: A company undertake a project to build 2000 m long bridge in 400 days and hire 50 men for the project. After 100 days, he finds only 400 m of bridge has been completed.Find the (approx )number of extra men he hire to complete the project on time. Solution: Use here M1 D1 / W1 = M2 D2 / W2 50 x 100/ 400 = [(50 + x) 300]/ 1600 4 x 5000 = 15000 + 300x 20000 – 15000 = 300x 3x = 50 x= 16.66 x =17 men to hire to complete the project on time. Question 8: In a hostel mess there was sufficient food for 400 students for 31 days of a month. After 26 days 150 students go to their home. For how many extra days will the rest of food last for the remaining students. Solution: After 26 days food left in mess= 5 * 400 Students remaining in hostel mess =400 – 150 = 250 Let x be the extra days. 5 * 400 = (5 + x ) * 250 2000 = 1250 + 250x 250x = 750 x = 3 days Hence, food will last for 3 extra days. Question 9: Two candles A and B of same height can burn completely in 6 hours and 8 hours respectively. If both start at same time with their respective constant speed, then calculate after how much time the ratio of their height will become 3:4. Solution: Total time is LCM (6, 8) =24 A’s efficiency = 24/6 = 4 B’s efficiency = 24/8= 3 After x time height will become 3:4 So, (24 – 4x) /( 24 – 3x) = 3/4 96 – 16x = 72 – 9x 7x = 24 x = 24/7 = 3.42 hours Question 10: A and B men can build a wall in 20 and 30 hours respectively but if they work together they use 220 less bricks per hour and build the wall in 15 hours. Find the number of bricks in the wall. Solution: Work done is LCM(20, 30) = 60 A’s efficiency= 60/20 = 3 B’s efficiency= 60/30 = 2 If they work together their efficiency will be 5. Working together their efficiency 60/15 = 4 Efficiency is less than by 5 – 4 = 1 1 -> 220 less bricks 60 -> 220 x 60 = 13200 bricks in the wall. Question 11: A + B and B + C can do a work in 12 days and 15 days respectively. If A work for 4 days and B work for 7 days then C complete the remain work in next 10 days. Then calculate in how much time C would complete the whole work? Solution: Total work done is LCM(12, 15)=60 A+B ‘s efficiency = 60/12 = 5 B+C ‘s efficiency = 60/15 = 4 A work for 4 days, B work for 7 days then A and B work together for 4 days. B work for 7 days, C work for 10 days then B and C work together for 3 days. A+B B+C C 4 days 3 days 7 days |x5 |x4 | 20 12 60-20-12=28 C’s efficiency = 28/7 = 4 Hence, C can complete the work in 60/4 = 15 days. Question 12: In a company there are three shifts for a day during the three shifts the average working efficiency of the workers is 80%, 70% and 50% respectively. A work is complete in 60 days by the group working in the first shift only. If the work is done in all the three shift per day then how many less days are required to complete the work. Solution: Shifts I II III 80% 70% 50% 8 7 5 Total work done obtain by using I shift only = 60 x 8 = 480 unit Total efficiency = 8 + 7 + 5 = 20 Total days required = 480/20 = 24 days Total less required days = 60 – 24 = 36 days Question 13: In a factory same number of women and children are present. Women works for 6 hours in a day and children work 4 hours in a day.In festival season workload increases by 60% and government does not allow children to work more than 6 hours per day.If their efficiency are equal and remain work is done by women then how many extra hours/day increased by women? Solution. Shortcut Let they earn 1 Rs/hr. Woman Child Earns 6 + 4 = 10 | | |60% __ max 6 = 16 Workload increases by 60% from 10 to 16. Children can work maximum 6 hours Then women work per day 16 – 6 = 10 So, it increases by 4 hours/day extra. Question 14: A start a work and left after 2 days and remaining work is done by B in 9 days. If A left after 3 days then B complete the remaining work in 6 days. Then in how many days A and B can complete the work individually. Solution. Work done is equal in both cases. 2A + 9B = 3A + 6B A=3B A/B=3/1 Total work done =3 x 2 + 9 x 1 = 15 A alone take 15/3 = 5 days. B alone take 15/1 = 15 days. Question 15: A and B can complete work together in 30 days. They start work together and after 23 days B left the work and the whole work is completed in 33 days. Find the work completed by A alone. Solution: Let work done is W.A+B’s efficiency = W/30 Total Work done in 23 days = A+B’s efficiency * 23 = 23W/30 unitsRemaining Work = W- 23W/30 = 7W/30 unitsRemaining Work done by A in 10 ( 33-23) days A’s efficiency = (7W/30 )/10 = 7W/300B’s efficiency = A+B’s efficiency – A’s efficiency = W/30 – 7W/300 = 3W/300 = W/100Work done by B in 23 days = B’s efficiency * 23 = 23W/100 = 23 % of total workWork done by alone A = W-23W/100 = 77W/100 = 77% of total work Question 16: A alone would take 64 hours more to complete a work then A + B work together. B take 4 hours more to complete a work alone than A and B work together.Find in how much time A alone complete the work. Solution: First method Let A and B take x hours to complete a work together. A alone would take (x + 64) and B alone would take (x + 4)hours to complete the work. A( x + 64) = x (A + B) 64A =x B ............(1) B(x + 4)= x(A + B) 4B = x A...............(2) from (1)and (2) 64A = x * x A/4 x2 = 256 x = 16 A alone = 16 + 64 = 80 hours Shortcut method – x2 = more of A * more of B x2= 64 * 4 x2= 256 x= 16 krinakanani aparnayadav49 rituraj735 tanujguptagwl ashleyaish111 Placements QA - Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 20 Puzzles Commonly Asked During SDE Interviews Codenation Recruitment Process Minimum changes required to make all Array elements Prime Interview Preparation Print the longest path from root to leaf in a Binary tree Mixture and Alligation Simple Interest Probability Algebra | Set -1 Problem on HCF and LCM
[ { "code": null, "e": 25475, "s": 25447, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25700, "s": 25475, "text": "Question 1: Ram and Shyam undertake a piece of work for Rs 300. Ram can do it in 20 days and Shaym can do it in 60 days. With the help of Radha, they finish it in 10 days. How much should Radha be paid for her contribution? " }, { "code": null, "e": 25994, "s": 25700, "text": "Solution: Ram alone takes 20 days and Shyam alone takes 60 days to finish the work. All together can finish in 10 days. Let the total work done is LCM(10, 20, 60) = 60 Ram’s efficiency = 60/20 = 3 Shyam’s efficiency = 60/60 = 1 Combined Efficiency = 60/10= 6 Radha’s efficiency = 6 – 3 -1 = 2 " }, { "code": null, "e": 26019, "s": 25994, "text": "efficiency ratio = 3:1:2" }, { "code": null, "e": 26062, "s": 26019, "text": "therefore radha’s money = (2/6)*300=100 rs" }, { "code": null, "e": 26255, "s": 26062, "text": "Question 2: A can do a piece of work in 30 days. He works only for 5 days and left, then B finishes the remaining work in 15 more days. In how many days will A and B together finish the work? " }, { "code": null, "e": 26477, "s": 26255, "text": "Solution: 25 days work of A completed by B in 15 days. 25A=15B A/B=3/5 A’s efficiency = 3 B’s efficiency = 5 Total work done= 3 * 30 = 90 Work done by A and B together=total work done/total efficiency = 90/8 = 11.25 days " }, { "code": null, "e": 26642, "s": 26477, "text": "Question 3: Twenty five employees can finish a project in 40 days.After how many days should 10 employees leave the job so that the project is finished in 50 days. " }, { "code": null, "e": 26858, "s": 26642, "text": "Solution: Let n be the number of days when 10 employees left the project. Total work done= 25*40= 1000 25x + (50 – x)15 = 1000 25x + 750 – 15x = 1000 10x = 250 x = 25 Hence, after 25 days 10 employees left the job. " }, { "code": null, "e": 26913, "s": 26858, "text": "Alternate: 25 employees * 40 days = 1000 units of work" }, { "code": null, "e": 26987, "s": 26913, "text": "After leaving 10 employees the job, we have 50 days to complete the work." }, { "code": null, "e": 27033, "s": 26987, "text": "In 50 days only 15 employees will do the work" }, { "code": null, "e": 27088, "s": 27033, "text": "work done by 15 employees = 15 * 50 =750 units of work" }, { "code": null, "e": 27119, "s": 27088, "text": "Remaining units =1000-750 =250" }, { "code": null, "e": 27167, "s": 27119, "text": "Units of work done by 10 employees = 250/10 =25" }, { "code": null, "e": 27219, "s": 27167, "text": "So after 25 days 10 employees should leave the job." }, { "code": null, "e": 27357, "s": 27219, "text": "Question 4: A can type 85 pages in 10 hours. A and B together can type 500 pages in 40 hours.How much time B will take to type 80 pages. " }, { "code": null, "e": 27595, "s": 27357, "text": "Solution: A can type 85 pages in 10 hours Then, A can type 340 pages in 40 hours. A and B together can type 500 pages in 40 hours So, B can type number of pages= 500 – 340 = 160 pages in 40 hours. Hence, B can type 80 pages in 20 hours. " }, { "code": null, "e": 27841, "s": 27595, "text": "Question 5: A, B and C can do a piece of work in 10, 12 and 15 days respectively.They all start the work together but A leaves after the 2 days of work and B leaves 3 days before the work is completed.Find the number of days the work completed. " }, { "code": null, "e": 28225, "s": 27841, "text": "Solution: Total work done is LCM(10, 12, 15)=60 unit A’s efficiency = 60/10= 6 B’s efficiency = 60/12= 5 C’s efficiency = 60/15= 4 First two days all work together So, the work completed in first two days= 15 x 2 = 30 unit Remaining work= 60 – 30 = 30 unit If B completes 3 day work also = 3 x 5 = 15 unit Total work remaining= 30 + 15 = 45 unit Number of days B and C works= 45/9=5 " }, { "code": null, "e": 28286, "s": 28225, "text": "Total number of days to complete the work = 2 + 5 = 7 days. " }, { "code": null, "e": 28416, "s": 28286, "text": "Question 6: A can do 1/6 work in 4 days and B can do 1/5 of the same work in 6 days. In how many days both will finish the work? " }, { "code": null, "e": 28674, "s": 28416, "text": "Solution: A can complete the work in 6*4 = 24 days B can complete the work in 5*6 = 30 days Total work done LCM(24, 30)= 120 unit A’s efficiency = 120/24= 5 B’s efficiency = 120/30= 4 Total time taken = total work done/ total efficiency = 120/9 = 40/3 days " }, { "code": null, "e": 28934, "s": 28674, "text": "Question 7: A company undertake a project to build 2000 m long bridge in 400 days and hire 50 men for the project. After 100 days, he finds only 400 m of bridge has been completed.Find the (approx )number of extra men he hire to complete the project on time. " }, { "code": null, "e": 29128, "s": 28934, "text": "Solution: Use here M1 D1 / W1 = M2 D2 / W2 50 x 100/ 400 = [(50 + x) 300]/ 1600 4 x 5000 = 15000 + 300x 20000 – 15000 = 300x 3x = 50 x= 16.66 x =17 men to hire to complete the project on time. " }, { "code": null, "e": 29349, "s": 29128, "text": "Question 8: In a hostel mess there was sufficient food for 400 students for 31 days of a month. After 26 days 150 students go to their home. For how many extra days will the rest of food last for the remaining students. " }, { "code": null, "e": 29583, "s": 29349, "text": "Solution: After 26 days food left in mess= 5 * 400 Students remaining in hostel mess =400 – 150 = 250 Let x be the extra days. 5 * 400 = (5 + x ) * 250 2000 = 1250 + 250x 250x = 750 x = 3 days Hence, food will last for 3 extra days. " }, { "code": null, "e": 29831, "s": 29583, "text": "Question 9: Two candles A and B of same height can burn completely in 6 hours and 8 hours respectively. If both start at same time with their respective constant speed, then calculate after how much time the ratio of their height will become 3:4. " }, { "code": null, "e": 30039, "s": 29831, "text": "Solution: Total time is LCM (6, 8) =24 A’s efficiency = 24/6 = 4 B’s efficiency = 24/8= 3 After x time height will become 3:4 So, (24 – 4x) /( 24 – 3x) = 3/4 96 – 16x = 72 – 9x 7x = 24 x = 24/7 = 3.42 hours " }, { "code": null, "e": 30245, "s": 30039, "text": "Question 10: A and B men can build a wall in 20 and 30 hours respectively but if they work together they use 220 less bricks per hour and build the wall in 15 hours. Find the number of bricks in the wall. " }, { "code": null, "e": 30533, "s": 30245, "text": "Solution: Work done is LCM(20, 30) = 60 A’s efficiency= 60/20 = 3 B’s efficiency= 60/30 = 2 If they work together their efficiency will be 5. Working together their efficiency 60/15 = 4 Efficiency is less than by 5 – 4 = 1 1 -> 220 less bricks 60 -> 220 x 60 = 13200 bricks in the wall. " }, { "code": null, "e": 30771, "s": 30533, "text": "Question 11: A + B and B + C can do a work in 12 days and 15 days respectively. If A work for 4 days and B work for 7 days then C complete the remain work in next 10 days. Then calculate in how much time C would complete the whole work? " }, { "code": null, "e": 31030, "s": 30771, "text": "Solution: Total work done is LCM(12, 15)=60 A+B ‘s efficiency = 60/12 = 5 B+C ‘s efficiency = 60/15 = 4 A work for 4 days, B work for 7 days then A and B work together for 4 days. B work for 7 days, C work for 10 days then B and C work together for 3 days. " }, { "code": null, "e": 31149, "s": 31030, "text": "A+B B+C C\n4 days 3 days 7 days\n|x5 |x4 |\n20 12 60-20-12=28" }, { "code": null, "e": 31226, "s": 31149, "text": "C’s efficiency = 28/7 = 4 Hence, C can complete the work in 60/4 = 15 days. " }, { "code": null, "e": 31576, "s": 31226, "text": "Question 12: In a company there are three shifts for a day during the three shifts the average working efficiency of the workers is 80%, 70% and 50% respectively. A work is complete in 60 days by the group working in the first shift only. If the work is done in all the three shift per day then how many less days are required to complete the work. " }, { "code": null, "e": 31587, "s": 31576, "text": "Solution: " }, { "code": null, "e": 31679, "s": 31587, "text": "Shifts I II III\n 80% 70% 50%\n 8 7 5" }, { "code": null, "e": 31863, "s": 31679, "text": "Total work done obtain by using I shift only = 60 x 8 = 480 unit Total efficiency = 8 + 7 + 5 = 20 Total days required = 480/20 = 24 days Total less required days = 60 – 24 = 36 days " }, { "code": null, "e": 32279, "s": 31863, "text": "Question 13: In a factory same number of women and children are present. Women works for 6 hours in a day and children work 4 hours in a day.In festival season workload increases by 60% and government does not allow children to work more than 6 hours per day.If their efficiency are equal and remain work is done by women then how many extra hours/day increased by women? Solution. Shortcut Let they earn 1 Rs/hr. " }, { "code": null, "e": 32383, "s": 32279, "text": "Woman Child Earns\n 6 + 4 = 10\n | | |60%\n __ max 6 = 16" }, { "code": null, "e": 32534, "s": 32383, "text": "Workload increases by 60% from 10 to 16. Children can work maximum 6 hours Then women work per day 16 – 6 = 10 So, it increases by 4 hours/day extra. " }, { "code": null, "e": 32763, "s": 32534, "text": "Question 14: A start a work and left after 2 days and remaining work is done by B in 9 days. If A left after 3 days then B complete the remaining work in 6 days. Then in how many days A and B can complete the work individually. " }, { "code": null, "e": 32932, "s": 32763, "text": "Solution. Work done is equal in both cases. 2A + 9B = 3A + 6B A=3B A/B=3/1 Total work done =3 x 2 + 9 x 1 = 15 A alone take 15/3 = 5 days. B alone take 15/1 = 15 days. " }, { "code": null, "e": 33132, "s": 32932, "text": "Question 15: A and B can complete work together in 30 days. They start work together and after 23 days B left the work and the whole work is completed in 33 days. Find the work completed by A alone. " }, { "code": null, "e": 33598, "s": 33132, "text": "Solution: Let work done is W.A+B’s efficiency = W/30 Total Work done in 23 days = A+B’s efficiency * 23 = 23W/30 unitsRemaining Work = W- 23W/30 = 7W/30 unitsRemaining Work done by A in 10 ( 33-23) days A’s efficiency = (7W/30 )/10 = 7W/300B’s efficiency = A+B’s efficiency – A’s efficiency = W/30 – 7W/300 = 3W/300 = W/100Work done by B in 23 days = B’s efficiency * 23 = 23W/100 = 23 % of total workWork done by alone A = W-23W/100 = 77W/100 = 77% of total work" }, { "code": null, "e": 33811, "s": 33598, "text": "Question 16: A alone would take 64 hours more to complete a work then A + B work together. B take 4 hours more to complete a work alone than A and B work together.Find in how much time A alone complete the work. " }, { "code": null, "e": 34146, "s": 33811, "text": "Solution: First method Let A and B take x hours to complete a work together. A alone would take (x + 64) and B alone would take (x + 4)hours to complete the work. A( x + 64) = x (A + B) 64A =x B ............(1) B(x + 4)= x(A + B) 4B = x A...............(2) from (1)and (2) 64A = x * x A/4 x2 = 256 x = 16 A alone = 16 + 64 = 80 hours " }, { "code": null, "e": 34217, "s": 34146, "text": "Shortcut method – x2 = more of A * more of B x2= 64 * 4 x2= 256 x= 16 " }, { "code": null, "e": 34229, "s": 34217, "text": "krinakanani" }, { "code": null, "e": 34243, "s": 34229, "text": "aparnayadav49" }, { "code": null, "e": 34254, "s": 34243, "text": "rituraj735" }, { "code": null, "e": 34268, "s": 34254, "text": "tanujguptagwl" }, { "code": null, "e": 34282, "s": 34268, "text": "ashleyaish111" }, { "code": null, "e": 34293, "s": 34282, "text": "Placements" }, { "code": null, "e": 34309, "s": 34293, "text": "QA - Placements" }, { "code": null, "e": 34407, "s": 34309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34459, "s": 34407, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 34490, "s": 34459, "text": "Codenation Recruitment Process" }, { "code": null, "e": 34548, "s": 34490, "text": "Minimum changes required to make all Array elements Prime" }, { "code": null, "e": 34570, "s": 34548, "text": "Interview Preparation" }, { "code": null, "e": 34628, "s": 34570, "text": "Print the longest path from root to leaf in a Binary tree" }, { "code": null, "e": 34651, "s": 34628, "text": "Mixture and Alligation" }, { "code": null, "e": 34667, "s": 34651, "text": "Simple Interest" }, { "code": null, "e": 34679, "s": 34667, "text": "Probability" }, { "code": null, "e": 34696, "s": 34679, "text": "Algebra | Set -1" } ]
Working with missing values in Pandas | by B. Chen | Towards Data Science
The real-world data is rarely clean and homogeneous. In particular, many interesting datasets will have some amount of values missing. In this article, we will discuss how missing value is represented in Pandas, how to deal with other characters representations and Pandas built-in methods for handling missing values. Outline Missing values in Pandas Dealing with other characters representations Handling missing values Schemes for indicating the presence of missing values are generally around one of two strategies [1]: A mask that globally indicates missing values.A sentinel value that indicates a missing entry. A mask that globally indicates missing values. A sentinel value that indicates a missing entry. In the mask approach, it might be a same-sized Boolean array representation or use one bit to represent the local state of missing entry. In the sentinel value approach, a tag value is used for indicating the missing value, such as NaN (Not a Number), null or a special value which is part of the programming language. None of these approaches is without trade-offs [1]. The mask approach requires allocations of an additional Boolean array, which adds overhead in both storage and computation. A sentinel value reduces the range of valid values that can be represented and may require extra logic in CPU and GPU arithmetic. Pandas use sentinels to handle missing values, and more specifically Pandas use two already-existing Python null value: the Python None object. the special floating-point NaN value, The first sentinel value used by Pandas is None, a Python ‘object’ data that is most often used for missing data in Python code. Because it is a Python object, None cannot be used in any arbitrary NumPy/Pandas array, but only in arrays with data type ‘object’. import numpy as npimport pandas as pdarr1 = np.array([1, None, 2, 3])arr1 That will output array([1, None, 2, 3], dtype=object) The use of Python object in an array also means that you will generally get an error if you perform aggregations like sum() or min(). The second sentinel value used by Pandas is NaN, is acronym for Not a Number and a special floating-point value use the standard IEEE floating-point representation. arr2 = np.array([1, np.nan, 3, 4]) arr2.dtype That will output dtype('float64') Keep in mind that NaN is specifically a floating-point value; there is no equivalent value for integers, strings or other types. And you should be aware that regardless of the operations, the result of arithmetic with NaN will be another NaN . For example arr2.sum()arr2.min()arr2.max() Will all output NaN. NumPy does provide some special aggregations that will ignore the missing data, such as nansum() , nanmin() , and nanmax() . Pandas is built to handle the None and NaN nearly interchangeably, converting between them where appropriate: pd.Series([1, np.nan, 2, None])0 1.01 NaN2 2.03 NaNdtype: float64 For types that don’t have an available sentinel value, Pandas automatically type-casts when NaN values are present. For example, let’s create a Panda Series with dtype=int. x = pd.Series(range(2), dtype=int)x0 01 1dtype: int64 If we set a value in an integer array to np.nan, it will automatically be upcast to a floating-point type to accommodate the NaN: x[0] = Nonex0 NaN1 1.0dtype: float64 Not all missing values come in nice and clean np.nan . If we know what kind of characters used as missing values in the dataset, we can handle them while creating the DataFrame using na_values parameter: df = pd.read_csv("source.csv", na_values = ['?', '&']) When the DataFrame is already created, we can use pandas replace() function to handle these values: df_clean = df.replace({ "?": np.nan, "&": np.nan }) Before we diving into the details, let’s create a DataFrame with some missing values: import numpy as npimport pandas as pddf = pd.DataFrame({'A': [20, 15, 20], 'B': [np.nan, 50, 4], 'C': [30, 5, 30,], 'D': [15, 2, np.nan], 'E': [8, 5, 10], 'F': [45, 7, np.nan], 'G': [35, 10, 35]}, index = ['Row 1', 'Row 2', 'Row 3'])df Pandas has two useful methods for detecting missing values: isnull() and notnull() . Either one will return a Boolean mask over the data. For example: df.isnull() returns a Boolean same-sized DataFrame indicating if values are missing df.notnull() returns a Boolean same-sized DataFrame which is just opposite of isnull() When the dataset is large, you can count the number of missing values instead. df.isnull().sum() returns the number of missing values for each column (Pandas Series) df.isnull().sum()A 0B 1C 0D 1E 0F 1G 0dtype: int64 df.isnull().sum().sum() returns the total number of missing values df.isnull().sum().sum()3 In addition to the masking used before, there is the convenience method dropna() to remove missing values [2]. The method is defined as: dropna(axis=0, how=’any’, thresh=None, subset=None, inplace=False) axis: 0 for row and 1 for column how: ‘any’ for dropping row or column if any NaN values are present. ‘all’ to drop row of column if all values are NaN. thresh: require that many non-NaN values subset: array-like value. Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include. inplace: If True, do operation inplace and return None. To recap, here is the DataFrame df we are using To drop row if any NaN values are present: df.dropna(axis = 0) To drop column if any NaN values are present: df.dropna(axis = 1) To drop row if the number of non-NaN is less than 6. df.dropna(axis = 0, thresh = 6) Data is a valuable asset so we should not give it up easily. Also, machine learning models almost always tend to perform better with more data. Therefore, depending on the situation, we may prefer replacing missing values instead of dropping. There is the convenience method fillna() to replace missing values [3]. The method is defined as: fillna(value=None, method=None, axis=None, inplace=False) value: value to use to replace NaN method: method to use for replacing NaN. method='ffill' does the forward replacement. method='bfill' does the backword replacement. axis: 0 for row and 1 for column. inplace: If True, do operation inplace and return None. To recap, here is the DataFrane df we are using To replace all NaN values with a scalar df.fillna(value=10) To replaces NaN values with the values in the previous row. df.fillna(axis=0, method='ffill') To replace NaN values with the values in the previous column. df.fillna(axis=1, method='ffill') The same, you can also replace NaN values with the values in the next row or column. # Replace with the values in the next rowdf.fillna(axis=0, method='bfill')# Replace with the values in the next columndf.fillna(axis=1, method='bfill') The other common replacement is to replace NaN values with the mean. For example to replace NaN values in column B with the mean. df['B'].fillna(value=df['B'].mean(), inplace=True) And that’s about it. Thanks for reading. [1] Python Data Science Handbook [2] Pandas Official documentation — dropna [3] Pandas Official documentation — fillna
[ { "code": null, "e": 307, "s": 172, "text": "The real-world data is rarely clean and homogeneous. In particular, many interesting datasets will have some amount of values missing." }, { "code": null, "e": 491, "s": 307, "text": "In this article, we will discuss how missing value is represented in Pandas, how to deal with other characters representations and Pandas built-in methods for handling missing values." }, { "code": null, "e": 499, "s": 491, "text": "Outline" }, { "code": null, "e": 524, "s": 499, "text": "Missing values in Pandas" }, { "code": null, "e": 570, "s": 524, "text": "Dealing with other characters representations" }, { "code": null, "e": 594, "s": 570, "text": "Handling missing values" }, { "code": null, "e": 696, "s": 594, "text": "Schemes for indicating the presence of missing values are generally around one of two strategies [1]:" }, { "code": null, "e": 791, "s": 696, "text": "A mask that globally indicates missing values.A sentinel value that indicates a missing entry." }, { "code": null, "e": 838, "s": 791, "text": "A mask that globally indicates missing values." }, { "code": null, "e": 887, "s": 838, "text": "A sentinel value that indicates a missing entry." }, { "code": null, "e": 1025, "s": 887, "text": "In the mask approach, it might be a same-sized Boolean array representation or use one bit to represent the local state of missing entry." }, { "code": null, "e": 1206, "s": 1025, "text": "In the sentinel value approach, a tag value is used for indicating the missing value, such as NaN (Not a Number), null or a special value which is part of the programming language." }, { "code": null, "e": 1512, "s": 1206, "text": "None of these approaches is without trade-offs [1]. The mask approach requires allocations of an additional Boolean array, which adds overhead in both storage and computation. A sentinel value reduces the range of valid values that can be represented and may require extra logic in CPU and GPU arithmetic." }, { "code": null, "e": 1632, "s": 1512, "text": "Pandas use sentinels to handle missing values, and more specifically Pandas use two already-existing Python null value:" }, { "code": null, "e": 1656, "s": 1632, "text": "the Python None object." }, { "code": null, "e": 1694, "s": 1656, "text": "the special floating-point NaN value," }, { "code": null, "e": 1955, "s": 1694, "text": "The first sentinel value used by Pandas is None, a Python ‘object’ data that is most often used for missing data in Python code. Because it is a Python object, None cannot be used in any arbitrary NumPy/Pandas array, but only in arrays with data type ‘object’." }, { "code": null, "e": 2029, "s": 1955, "text": "import numpy as npimport pandas as pdarr1 = np.array([1, None, 2, 3])arr1" }, { "code": null, "e": 2046, "s": 2029, "text": "That will output" }, { "code": null, "e": 2083, "s": 2046, "text": "array([1, None, 2, 3], dtype=object)" }, { "code": null, "e": 2217, "s": 2083, "text": "The use of Python object in an array also means that you will generally get an error if you perform aggregations like sum() or min()." }, { "code": null, "e": 2382, "s": 2217, "text": "The second sentinel value used by Pandas is NaN, is acronym for Not a Number and a special floating-point value use the standard IEEE floating-point representation." }, { "code": null, "e": 2428, "s": 2382, "text": "arr2 = np.array([1, np.nan, 3, 4]) arr2.dtype" }, { "code": null, "e": 2445, "s": 2428, "text": "That will output" }, { "code": null, "e": 2462, "s": 2445, "text": "dtype('float64')" }, { "code": null, "e": 2718, "s": 2462, "text": "Keep in mind that NaN is specifically a floating-point value; there is no equivalent value for integers, strings or other types. And you should be aware that regardless of the operations, the result of arithmetic with NaN will be another NaN . For example" }, { "code": null, "e": 2749, "s": 2718, "text": "arr2.sum()arr2.min()arr2.max()" }, { "code": null, "e": 2895, "s": 2749, "text": "Will all output NaN. NumPy does provide some special aggregations that will ignore the missing data, such as nansum() , nanmin() , and nanmax() ." }, { "code": null, "e": 3005, "s": 2895, "text": "Pandas is built to handle the None and NaN nearly interchangeably, converting between them where appropriate:" }, { "code": null, "e": 3083, "s": 3005, "text": "pd.Series([1, np.nan, 2, None])0 1.01 NaN2 2.03 NaNdtype: float64" }, { "code": null, "e": 3199, "s": 3083, "text": "For types that don’t have an available sentinel value, Pandas automatically type-casts when NaN values are present." }, { "code": null, "e": 3256, "s": 3199, "text": "For example, let’s create a Panda Series with dtype=int." }, { "code": null, "e": 3316, "s": 3256, "text": "x = pd.Series(range(2), dtype=int)x0 01 1dtype: int64" }, { "code": null, "e": 3446, "s": 3316, "text": "If we set a value in an integer array to np.nan, it will automatically be upcast to a floating-point type to accommodate the NaN:" }, { "code": null, "e": 3489, "s": 3446, "text": "x[0] = Nonex0 NaN1 1.0dtype: float64" }, { "code": null, "e": 3693, "s": 3489, "text": "Not all missing values come in nice and clean np.nan . If we know what kind of characters used as missing values in the dataset, we can handle them while creating the DataFrame using na_values parameter:" }, { "code": null, "e": 3748, "s": 3693, "text": "df = pd.read_csv(\"source.csv\", na_values = ['?', '&'])" }, { "code": null, "e": 3848, "s": 3748, "text": "When the DataFrame is already created, we can use pandas replace() function to handle these values:" }, { "code": null, "e": 3900, "s": 3848, "text": "df_clean = df.replace({ \"?\": np.nan, \"&\": np.nan })" }, { "code": null, "e": 3986, "s": 3900, "text": "Before we diving into the details, let’s create a DataFrame with some missing values:" }, { "code": null, "e": 4342, "s": 3986, "text": "import numpy as npimport pandas as pddf = pd.DataFrame({'A': [20, 15, 20], 'B': [np.nan, 50, 4], 'C': [30, 5, 30,], 'D': [15, 2, np.nan], 'E': [8, 5, 10], 'F': [45, 7, np.nan], 'G': [35, 10, 35]}, index = ['Row 1', 'Row 2', 'Row 3'])df" }, { "code": null, "e": 4493, "s": 4342, "text": "Pandas has two useful methods for detecting missing values: isnull() and notnull() . Either one will return a Boolean mask over the data. For example:" }, { "code": null, "e": 4577, "s": 4493, "text": "df.isnull() returns a Boolean same-sized DataFrame indicating if values are missing" }, { "code": null, "e": 4664, "s": 4577, "text": "df.notnull() returns a Boolean same-sized DataFrame which is just opposite of isnull()" }, { "code": null, "e": 4743, "s": 4664, "text": "When the dataset is large, you can count the number of missing values instead." }, { "code": null, "e": 4830, "s": 4743, "text": "df.isnull().sum() returns the number of missing values for each column (Pandas Series)" }, { "code": null, "e": 4902, "s": 4830, "text": "df.isnull().sum()A 0B 1C 0D 1E 0F 1G 0dtype: int64" }, { "code": null, "e": 4969, "s": 4902, "text": "df.isnull().sum().sum() returns the total number of missing values" }, { "code": null, "e": 4994, "s": 4969, "text": "df.isnull().sum().sum()3" }, { "code": null, "e": 5131, "s": 4994, "text": "In addition to the masking used before, there is the convenience method dropna() to remove missing values [2]. The method is defined as:" }, { "code": null, "e": 5198, "s": 5131, "text": "dropna(axis=0, how=’any’, thresh=None, subset=None, inplace=False)" }, { "code": null, "e": 5231, "s": 5198, "text": "axis: 0 for row and 1 for column" }, { "code": null, "e": 5351, "s": 5231, "text": "how: ‘any’ for dropping row or column if any NaN values are present. ‘all’ to drop row of column if all values are NaN." }, { "code": null, "e": 5392, "s": 5351, "text": "thresh: require that many non-NaN values" }, { "code": null, "e": 5530, "s": 5392, "text": "subset: array-like value. Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include." }, { "code": null, "e": 5586, "s": 5530, "text": "inplace: If True, do operation inplace and return None." }, { "code": null, "e": 5634, "s": 5586, "text": "To recap, here is the DataFrame df we are using" }, { "code": null, "e": 5677, "s": 5634, "text": "To drop row if any NaN values are present:" }, { "code": null, "e": 5697, "s": 5677, "text": "df.dropna(axis = 0)" }, { "code": null, "e": 5743, "s": 5697, "text": "To drop column if any NaN values are present:" }, { "code": null, "e": 5763, "s": 5743, "text": "df.dropna(axis = 1)" }, { "code": null, "e": 5816, "s": 5763, "text": "To drop row if the number of non-NaN is less than 6." }, { "code": null, "e": 5848, "s": 5816, "text": "df.dropna(axis = 0, thresh = 6)" }, { "code": null, "e": 6091, "s": 5848, "text": "Data is a valuable asset so we should not give it up easily. Also, machine learning models almost always tend to perform better with more data. Therefore, depending on the situation, we may prefer replacing missing values instead of dropping." }, { "code": null, "e": 6189, "s": 6091, "text": "There is the convenience method fillna() to replace missing values [3]. The method is defined as:" }, { "code": null, "e": 6247, "s": 6189, "text": "fillna(value=None, method=None, axis=None, inplace=False)" }, { "code": null, "e": 6282, "s": 6247, "text": "value: value to use to replace NaN" }, { "code": null, "e": 6414, "s": 6282, "text": "method: method to use for replacing NaN. method='ffill' does the forward replacement. method='bfill' does the backword replacement." }, { "code": null, "e": 6448, "s": 6414, "text": "axis: 0 for row and 1 for column." }, { "code": null, "e": 6504, "s": 6448, "text": "inplace: If True, do operation inplace and return None." }, { "code": null, "e": 6552, "s": 6504, "text": "To recap, here is the DataFrane df we are using" }, { "code": null, "e": 6592, "s": 6552, "text": "To replace all NaN values with a scalar" }, { "code": null, "e": 6613, "s": 6592, "text": "df.fillna(value=10) " }, { "code": null, "e": 6673, "s": 6613, "text": "To replaces NaN values with the values in the previous row." }, { "code": null, "e": 6707, "s": 6673, "text": "df.fillna(axis=0, method='ffill')" }, { "code": null, "e": 6769, "s": 6707, "text": "To replace NaN values with the values in the previous column." }, { "code": null, "e": 6803, "s": 6769, "text": "df.fillna(axis=1, method='ffill')" }, { "code": null, "e": 6888, "s": 6803, "text": "The same, you can also replace NaN values with the values in the next row or column." }, { "code": null, "e": 7040, "s": 6888, "text": "# Replace with the values in the next rowdf.fillna(axis=0, method='bfill')# Replace with the values in the next columndf.fillna(axis=1, method='bfill')" }, { "code": null, "e": 7170, "s": 7040, "text": "The other common replacement is to replace NaN values with the mean. For example to replace NaN values in column B with the mean." }, { "code": null, "e": 7221, "s": 7170, "text": "df['B'].fillna(value=df['B'].mean(), inplace=True)" }, { "code": null, "e": 7262, "s": 7221, "text": "And that’s about it. Thanks for reading." }, { "code": null, "e": 7295, "s": 7262, "text": "[1] Python Data Science Handbook" }, { "code": null, "e": 7338, "s": 7295, "text": "[2] Pandas Official documentation — dropna" } ]
Reduce decimals while printing in Arduino
Often some functions can output really long floating-point numbers, with several decimal digits. Several times, we are just interested in the first couple of decimal digits, and the remaining digits just reduce the readability and make the Serial Monitor window cluttered. In order to round of floating-point numbers when printing to the Serial Monitor, you can just add the number of decimal places required as the second argument to serial.print. An example is shown below − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("Printing decimals"); Serial.println(9.6745,0); //This prints 10 Serial.println(9.6745,1); //This prints 9.7 Serial.println(9.6745,2); //This prints 9.67 } void loop() { // put your main code here, to run repeatedly: } The output of the above program on the Serial Monitor will be − As indicated in the comments, for the same floating-point number, the output will be different each time because we have specified different number of decimal places to use. Try it out yourself. Please note that this works only when your first argument to Serial.print() is a pure floating-point number. If it is a string, this won't work. Thus, Serial.println("9.6745",0); won't print just '9'. In fact, this line will give you an error − no matching function for call to 'println(const char [7], int)'
[ { "code": null, "e": 1335, "s": 1062, "text": "Often some functions can output really long floating-point numbers, with several decimal digits. Several times, we are just interested in the first couple of decimal digits, and the remaining digits just reduce the readability and make the Serial Monitor window cluttered." }, { "code": null, "e": 1511, "s": 1335, "text": "In order to round of floating-point numbers when printing to the Serial Monitor, you can just add the number of decimal places required as the second argument to serial.print." }, { "code": null, "e": 1539, "s": 1511, "text": "An example is shown below −" }, { "code": null, "e": 1877, "s": 1539, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println(\"Printing decimals\");\n Serial.println(9.6745,0); //This prints 10\n Serial.println(9.6745,1); //This prints 9.7\n Serial.println(9.6745,2); //This prints 9.67 \n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n \n}" }, { "code": null, "e": 1941, "s": 1877, "text": "The output of the above program on the Serial Monitor will be −" }, { "code": null, "e": 2281, "s": 1941, "text": "As indicated in the comments, for the same floating-point number, the output will be different each time because we have specified different number of decimal places to use. Try it out yourself. Please note that this works only when your first argument to Serial.print() is a pure floating-point number. If it is a string, this won't work." }, { "code": null, "e": 2381, "s": 2281, "text": "Thus, Serial.println(\"9.6745\",0); won't print just '9'. In fact, this line will give you an error −" }, { "code": null, "e": 2445, "s": 2381, "text": "no matching function for call to 'println(const char [7], int)'" } ]
How to get innerHTML of whole page in selenium driver?
We can get the innerHTML of the whole page in Selenium. We shall use the method getPageSource and print the values captured by it in the console. String s = driver.getPageSource(); We can also get the HTML source code via Javascript commands in Selenium. We shall utilize executeScript method and pass the command return document.body.innerHTML as a parameter to the method. JavascriptExecutor j = (JavascriptExecutor) driver; String s = (String) j.executeScript("return document.body.innerHTML;"); Code Implementation with getPageSource. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class PageHTMLcode{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); // getPageSource method to obtain HTML of page System.out.println("Get HTML of page: "+ driver.getPageSource()); driver.quit(); } } Code Implementation with Javascript Executor. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class PageHTMLcodeJS{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); // Javascript executor to obtain page HTML JavascriptExecutor j = (JavascriptExecutor) driver; String s = (String) j.executeScript("return document.body.innerHTML;"); System.out.println("Get HTML of page: "+ s); driver.quit(); } }
[ { "code": null, "e": 1208, "s": 1062, "text": "We can get the innerHTML of the whole page in Selenium. We shall use the method getPageSource and print the values captured by it in the console." }, { "code": null, "e": 1243, "s": 1208, "text": "String s = driver.getPageSource();" }, { "code": null, "e": 1437, "s": 1243, "text": "We can also get the HTML source code via Javascript commands in Selenium. We shall utilize executeScript method and pass the command return document.body.innerHTML as a parameter to the method." }, { "code": null, "e": 1561, "s": 1437, "text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nString s = (String) j.executeScript(\"return document.body.innerHTML;\");" }, { "code": null, "e": 1601, "s": 1561, "text": "Code Implementation with getPageSource." }, { "code": null, "e": 2328, "s": 1601, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class PageHTMLcode{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n // getPageSource method to obtain HTML of page\n System.out.println(\"Get HTML of page: \"+ driver.getPageSource());\n driver.quit();\n }\n}" }, { "code": null, "e": 2374, "s": 2328, "text": "Code Implementation with Javascript Executor." }, { "code": null, "e": 3261, "s": 2374, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class PageHTMLcodeJS{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n // Javascript executor to obtain page HTML\n JavascriptExecutor j = (JavascriptExecutor) driver;\n String s = (String) j.executeScript(\"return document.body.innerHTML;\");\n System.out.println(\"Get HTML of page: \"+ s);\n driver.quit();\n }\n}" } ]
Move last m elements to the front of a given Linked List - GeeksforGeeks
18 Jun, 2021 Given the head of a Singly Linked List and a value m, the task is to move the last m elements to the front. Examples: Input: 4->5->6->1->2->3 ; m = 3 Output: 1->2->3->4->5->6Input: 0->1->2->3->4->5 ; m = 4 Output: 2->3->4->5->0->1 Algorithm: Use two pointers: one to store the address of the last node and other for the address of the first node.Traverse the list till the first node of last m nodes.Maintain two pointers p, q i.e., p as the first node of last m nodes & q as just before node of p.Make the last node next as the original list head.Make the next of node q as NULL.Set the p as the head. Use two pointers: one to store the address of the last node and other for the address of the first node. Traverse the list till the first node of last m nodes. Maintain two pointers p, q i.e., p as the first node of last m nodes & q as just before node of p. Make the last node next as the original list head. Make the next of node q as NULL. Set the p as the head. Below is the implementation of the above approach. C++ C Java Python3 C# Javascript // C++ Program to move last m elements// to front in a given linked list#include <iostream>using namespace std; // A linked list nodestruct Node{ int data; struct Node* next;} * first, *last; int length = 0; // Function to print nodes// in a given linked listvoid printList(struct Node* node){ while (node != NULL) { cout << node->data <<" "; node = node->next; }} // Pointer head and p are being// used here because, the head// of the linked list is changed in this function.void moveToFront(struct Node* head, struct Node* p, int m){ // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == NULL) return; p = head; head = head->next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p->next = NULL; // connecting last to first & // will make another node as head last->next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m);} // UTILITY FUNCTIONS // Function to add a node at// the beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; // making first & last nodes if (length == 0) last = *head_ref; else first = *head_ref; // increase the length length++;} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5 push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); push(&start, 0); cout << "Initial Linked list\n"; printList(start); int m = 4; // no.of nodes to change struct Node* temp; moveToFront(start, temp, m); cout << "\n Final Linked list\n"; start = first; printList(start); return 0;} // This code is contributed by SHUBHAMSINGH10 // C Program to move last m elements// to front in a given linked list#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node { int data; struct Node* next;} * first, *last; int length = 0; // Function to print nodes// in a given linked listvoid printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Pointer head and p are being// used here because, the head// of the linked list is changed in this function.void moveToFront(struct Node* head, struct Node* p, int m){ // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == NULL) return; p = head; head = head->next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p->next = NULL; // connecting last to first & // will make another node as head last->next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m);} // UTILITY FUNCTIONS // Function to add a node at// the beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; // making first & last nodes if (length == 0) last = *head_ref; else first = *head_ref; // increase the length length++;} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5 push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); push(&start, 0); printf("\n Initial Linked list\n"); printList(start); int m = 4; // no.of nodes to change struct Node* temp; moveToFront(start, temp, m); printf("\n Final Linked list\n"); start = first; printList(start); return 0;} // Java Program to move last m elements// to front in a given linked listclass GFG{ // A linked list node static class Node { int data; Node next; } static Node first, last; static int length = 0; // Function to print nodes // in a given linked list static void printList(Node node) { while (node != null) { System.out.printf("%d ", node.data); node = node.next; } } // Pointer head and p are being // used here because, the head // of the linked list is changed in this function. static void moveToFront(Node head, Node p, int m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code public static void main(String[] args) { Node start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); System.out.printf("\n Initial Linked list\n"); printList(start); int m = 4; // no.of nodes to change Node temp = new Node(); moveToFront(start, temp, m); System.out.printf("\n Final Linked list\n"); start = first; printList(start); }} // This code is contributed by 29AjayKumar # Python Program to move last m elements# to front in a given linked list # A linked list nodeclass Node : def __init__(self): self.data = 0 self.next = None first = Nonelast = None length = 0 # Function to print nodes# in a given linked listdef printList( node): while (node != None) : print( node.data, end=" ") node = node.next # Pointer head and p are being# used here because, the head# of the linked list is changed in this function.def moveToFront( head, p, m): global first global last global length # If the linked list is empty, # or it contains only one node, # then nothing needs to be done, simply return if (head == None): return head p = head head = head.next m= m + 1 # if m value reaches length, # the recursion will end if (length == m) : # breaking the link p.next = None # connecting last to first & # will make another node as head last.next = first # Making the first node of # last m nodes as root first = head else: moveToFront(head, p, m) # UTILITY FUNCTIONS # Function to add a node at# the beginning of Linked Listdef push( head_ref, new_data): global first global last global length # allocate node new_node = Node() # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node # making first & last nodes if (length == 0): last = head_ref else: first = head_ref # increase the length length= length + 1 return head_ref # Driver code start = None # The constructed linked list is:# 1.2.3.4.5start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1)start = push(start, 0) print("\n Initial Linked list")printList(start)m = 4 # no.of nodes to changetemp = NonemoveToFront(start, temp, m) print("\n Final Linked list")start = firstprintList(start) # This code is contributed by Arnab Kundu // C# Program to move last m elements// to front in a given linked listusing System; class GFG{ // A linked list node class Node { public int data; public Node next; } static Node first, last; static int length = 0; // Function to print nodes // in a given linked list static void printList(Node node) { while (node != null) { Console.Write("{0} ", node.data); node = node.next; } } // Pointer head and p are being used here // because, the head of the linked list // is changed in this function. static void moveToFront(Node head, Node p, int m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, // simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code public static void Main(String[] args) { Node start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); Console.Write("Initial Linked list\n"); printList(start); int m = 4; // no.of nodes to change Node temp = new Node(); moveToFront(start, temp, m); Console.Write("\nFinal Linked list\n"); start = first; printList(start); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript Program to move last m elements // to front in a given linked list // A linked list node class Node { constructor() { this.data = 0; this.next = null; } } var first, last; var length = 0; // Function to print nodes // in a given linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Pointer head and p are being used here // because, the head of the linked list // is changed in this function. function moveToFront(head, p, m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, // simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code var start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); document.write("Initial Linked list <br>"); printList(start); var m = 4; // no.of nodes to change var temp = new Node(); moveToFront(start, temp, m); document.write("<br> Final Linked list <br>"); start = first; printList(start); // This code is contributed by rdtank. </script> Initial Linked list 0 1 2 3 4 5 Final Linked list 2 3 4 5 0 1 29AjayKumar princiraj1992 andrew1234 SHUBHAMSINGH10 rdtank Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Swap nodes in a linked list without swapping data Delete a node in a Doubly Linked List Circular Linked List | Set 2 (Traversal) Insert a node at a specific position in a linked list Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Insertion Sort for Singly Linked List Real-time application of Data Structures
[ { "code": null, "e": 24958, "s": 24930, "text": "\n18 Jun, 2021" }, { "code": null, "e": 25078, "s": 24958, "text": "Given the head of a Singly Linked List and a value m, the task is to move the last m elements to the front. Examples: " }, { "code": null, "e": 25193, "s": 25078, "text": "Input: 4->5->6->1->2->3 ; m = 3 Output: 1->2->3->4->5->6Input: 0->1->2->3->4->5 ; m = 4 Output: 2->3->4->5->0->1 " }, { "code": null, "e": 25208, "s": 25195, "text": "Algorithm: " }, { "code": null, "e": 25569, "s": 25208, "text": "Use two pointers: one to store the address of the last node and other for the address of the first node.Traverse the list till the first node of last m nodes.Maintain two pointers p, q i.e., p as the first node of last m nodes & q as just before node of p.Make the last node next as the original list head.Make the next of node q as NULL.Set the p as the head." }, { "code": null, "e": 25674, "s": 25569, "text": "Use two pointers: one to store the address of the last node and other for the address of the first node." }, { "code": null, "e": 25729, "s": 25674, "text": "Traverse the list till the first node of last m nodes." }, { "code": null, "e": 25828, "s": 25729, "text": "Maintain two pointers p, q i.e., p as the first node of last m nodes & q as just before node of p." }, { "code": null, "e": 25879, "s": 25828, "text": "Make the last node next as the original list head." }, { "code": null, "e": 25912, "s": 25879, "text": "Make the next of node q as NULL." }, { "code": null, "e": 25935, "s": 25912, "text": "Set the p as the head." }, { "code": null, "e": 25988, "s": 25935, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25992, "s": 25988, "text": "C++" }, { "code": null, "e": 25994, "s": 25992, "text": "C" }, { "code": null, "e": 25999, "s": 25994, "text": "Java" }, { "code": null, "e": 26007, "s": 25999, "text": "Python3" }, { "code": null, "e": 26010, "s": 26007, "text": "C#" }, { "code": null, "e": 26021, "s": 26010, "text": "Javascript" }, { "code": "// C++ Program to move last m elements// to front in a given linked list#include <iostream>using namespace std; // A linked list nodestruct Node{ int data; struct Node* next;} * first, *last; int length = 0; // Function to print nodes// in a given linked listvoid printList(struct Node* node){ while (node != NULL) { cout << node->data <<\" \"; node = node->next; }} // Pointer head and p are being// used here because, the head// of the linked list is changed in this function.void moveToFront(struct Node* head, struct Node* p, int m){ // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == NULL) return; p = head; head = head->next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p->next = NULL; // connecting last to first & // will make another node as head last->next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m);} // UTILITY FUNCTIONS // Function to add a node at// the beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; // making first & last nodes if (length == 0) last = *head_ref; else first = *head_ref; // increase the length length++;} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5 push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); push(&start, 0); cout << \"Initial Linked list\\n\"; printList(start); int m = 4; // no.of nodes to change struct Node* temp; moveToFront(start, temp, m); cout << \"\\n Final Linked list\\n\"; start = first; printList(start); return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 28295, "s": 26021, "text": null }, { "code": "// C Program to move last m elements// to front in a given linked list#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node { int data; struct Node* next;} * first, *last; int length = 0; // Function to print nodes// in a given linked listvoid printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Pointer head and p are being// used here because, the head// of the linked list is changed in this function.void moveToFront(struct Node* head, struct Node* p, int m){ // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == NULL) return; p = head; head = head->next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p->next = NULL; // connecting last to first & // will make another node as head last->next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m);} // UTILITY FUNCTIONS // Function to add a node at// the beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; // making first & last nodes if (length == 0) last = *head_ref; else first = *head_ref; // increase the length length++;} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5 push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); push(&start, 0); printf(\"\\n Initial Linked list\\n\"); printList(start); int m = 4; // no.of nodes to change struct Node* temp; moveToFront(start, temp, m); printf(\"\\n Final Linked list\\n\"); start = first; printList(start); return 0;}", "e": 30521, "s": 28295, "text": null }, { "code": "// Java Program to move last m elements// to front in a given linked listclass GFG{ // A linked list node static class Node { int data; Node next; } static Node first, last; static int length = 0; // Function to print nodes // in a given linked list static void printList(Node node) { while (node != null) { System.out.printf(\"%d \", node.data); node = node.next; } } // Pointer head and p are being // used here because, the head // of the linked list is changed in this function. static void moveToFront(Node head, Node p, int m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code public static void main(String[] args) { Node start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); System.out.printf(\"\\n Initial Linked list\\n\"); printList(start); int m = 4; // no.of nodes to change Node temp = new Node(); moveToFront(start, temp, m); System.out.printf(\"\\n Final Linked list\\n\"); start = first; printList(start); }} // This code is contributed by 29AjayKumar", "e": 33148, "s": 30521, "text": null }, { "code": "# Python Program to move last m elements# to front in a given linked list # A linked list nodeclass Node : def __init__(self): self.data = 0 self.next = None first = Nonelast = None length = 0 # Function to print nodes# in a given linked listdef printList( node): while (node != None) : print( node.data, end=\" \") node = node.next # Pointer head and p are being# used here because, the head# of the linked list is changed in this function.def moveToFront( head, p, m): global first global last global length # If the linked list is empty, # or it contains only one node, # then nothing needs to be done, simply return if (head == None): return head p = head head = head.next m= m + 1 # if m value reaches length, # the recursion will end if (length == m) : # breaking the link p.next = None # connecting last to first & # will make another node as head last.next = first # Making the first node of # last m nodes as root first = head else: moveToFront(head, p, m) # UTILITY FUNCTIONS # Function to add a node at# the beginning of Linked Listdef push( head_ref, new_data): global first global last global length # allocate node new_node = Node() # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node # making first & last nodes if (length == 0): last = head_ref else: first = head_ref # increase the length length= length + 1 return head_ref # Driver code start = None # The constructed linked list is:# 1.2.3.4.5start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1)start = push(start, 0) print(\"\\n Initial Linked list\")printList(start)m = 4 # no.of nodes to changetemp = NonemoveToFront(start, temp, m) print(\"\\n Final Linked list\")start = firstprintList(start) # This code is contributed by Arnab Kundu", "e": 35317, "s": 33148, "text": null }, { "code": "// C# Program to move last m elements// to front in a given linked listusing System; class GFG{ // A linked list node class Node { public int data; public Node next; } static Node first, last; static int length = 0; // Function to print nodes // in a given linked list static void printList(Node node) { while (node != null) { Console.Write(\"{0} \", node.data); node = node.next; } } // Pointer head and p are being used here // because, the head of the linked list // is changed in this function. static void moveToFront(Node head, Node p, int m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, // simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code public static void Main(String[] args) { Node start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); Console.Write(\"Initial Linked list\\n\"); printList(start); int m = 4; // no.of nodes to change Node temp = new Node(); moveToFront(start, temp, m); Console.Write(\"\\nFinal Linked list\\n\"); start = first; printList(start); }} // This code is contributed by PrinciRaj1992", "e": 37987, "s": 35317, "text": null }, { "code": "<script> // JavaScript Program to move last m elements // to front in a given linked list // A linked list node class Node { constructor() { this.data = 0; this.next = null; } } var first, last; var length = 0; // Function to print nodes // in a given linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Pointer head and p are being used here // because, the head of the linked list // is changed in this function. function moveToFront(head, p, m) { // If the linked list is empty, // or it contains only one node, // then nothing needs to be done, // simply return if (head == null) return; p = head; head = head.next; m++; // if m value reaches length, // the recursion will end if (length == m) { // breaking the link p.next = null; // connecting last to first & // will make another node as head last.next = first; // Making the first node of // last m nodes as root first = head; } else moveToFront(head, p, m); } // UTILITY FUNCTIONS // Function to add a node at // the beginning of Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; // making first & last nodes if (length == 0) last = head_ref; else first = head_ref; // increase the length length++; return head_ref; } // Driver code var start = null; // The constructed linked list is: // 1.2.3.4.5 start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); start = push(start, 0); document.write(\"Initial Linked list <br>\"); printList(start); var m = 4; // no.of nodes to change var temp = new Node(); moveToFront(start, temp, m); document.write(\"<br> Final Linked list <br>\"); start = first; printList(start); // This code is contributed by rdtank. </script>", "e": 40497, "s": 37987, "text": null }, { "code": null, "e": 40561, "s": 40497, "text": "Initial Linked list\n0 1 2 3 4 5 \n Final Linked list\n2 3 4 5 0 1" }, { "code": null, "e": 40575, "s": 40563, "text": "29AjayKumar" }, { "code": null, "e": 40589, "s": 40575, "text": "princiraj1992" }, { "code": null, "e": 40600, "s": 40589, "text": "andrew1234" }, { "code": null, "e": 40615, "s": 40600, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 40622, "s": 40615, "text": "rdtank" }, { "code": null, "e": 40634, "s": 40622, "text": "Linked List" }, { "code": null, "e": 40646, "s": 40634, "text": "Linked List" }, { "code": null, "e": 40744, "s": 40646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40784, "s": 40744, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 40855, "s": 40784, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 40905, "s": 40855, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 40943, "s": 40905, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 40984, "s": 40943, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 41038, "s": 40984, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 41097, "s": 41038, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 41130, "s": 41097, "text": "Priority Queue using Linked List" }, { "code": null, "e": 41168, "s": 41130, "text": "Insertion Sort for Singly Linked List" } ]
How to find the area of an image contour Java OpenCV library?
Contours are nothing but the line joining all the points along the boundary of a particular shape. Using this you can − Find the shape of an object. Find the shape of an object. Calculate the area of an object. Calculate the area of an object. Detect an object. Detect an object. Recognize an object. Recognize an object. You can find the contours of various shapes, objects in an image using the findContours() method. In the same way you can draw You can also find the area of the shapes in the given input images. To do so you need to invoke the contourArea() method of the Imgproc class. This method accepts the contour of a particular shape, finds and returns its area. Following java example finds the area of each shape/object in the given image, draw the outlines of the shapes with an area less great than 5000 in red and the remaining in white. import java.util.ArrayList; import java.util.List; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class FindContourArea { public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the contents of the image String file ="D:\\Images\\javafx_graphical.jpg"; Mat src = Imgcodecs.imread(file); //Converting the source image to binary Mat gray = new Mat(src.rows(), src.cols(), src.type()); Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY); Mat binary = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0)); Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV); //Finding Contours List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchey = new Mat(); Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE); Mat draw = Mat.zeros(src.size(), CvType.CV_8UC3); for (int i = 0; i < contours.size(); i++) { Scalar color = new Scalar(0, 0, 255); //Calculating the area double cont_area = Imgproc.contourArea(contours.get(i)); System.out.println(cont_area); if(cont_area>5000.0){ Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8, hierarchey, 2, new Point() ) ; } else { color = new Scalar(255, 255, 255); Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8, hierarchey, 2, new Point() ) ; } } HighGui.imshow("Contours operation", draw); HighGui.waitKey(); } } Input Image 4091.0 6336.0 189.0 6439.0 4903.0 In addition to the above output, the above program generates the following window −
[ { "code": null, "e": 1182, "s": 1062, "text": "Contours are nothing but the line joining all the points along the boundary of a particular shape. Using this you can −" }, { "code": null, "e": 1211, "s": 1182, "text": "Find the shape of an object." }, { "code": null, "e": 1240, "s": 1211, "text": "Find the shape of an object." }, { "code": null, "e": 1273, "s": 1240, "text": "Calculate the area of an object." }, { "code": null, "e": 1306, "s": 1273, "text": "Calculate the area of an object." }, { "code": null, "e": 1324, "s": 1306, "text": "Detect an object." }, { "code": null, "e": 1342, "s": 1324, "text": "Detect an object." }, { "code": null, "e": 1363, "s": 1342, "text": "Recognize an object." }, { "code": null, "e": 1384, "s": 1363, "text": "Recognize an object." }, { "code": null, "e": 1511, "s": 1384, "text": "You can find the contours of various shapes, objects in an image using the findContours() method. In the same way you can draw" }, { "code": null, "e": 1737, "s": 1511, "text": "You can also find the area of the shapes in the given input images. To do so you need to invoke the contourArea() method of the Imgproc class. This method accepts the contour of a particular shape, finds and returns its area." }, { "code": null, "e": 1917, "s": 1737, "text": "Following java example finds the area of each shape/object in the given image, draw the outlines of the shapes with an area less great than 5000 in red and the remaining in white." }, { "code": null, "e": 3860, "s": 1917, "text": "import java.util.ArrayList;\nimport java.util.List;\nimport org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfPoint;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class FindContourArea {\n public static void main(String args[]) throws Exception {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the contents of the image\n String file =\"D:\\\\Images\\\\javafx_graphical.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Converting the source image to binary\n Mat gray = new Mat(src.rows(), src.cols(), src.type());\n Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);\n Mat binary = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0));\n Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV);\n //Finding Contours\n List<MatOfPoint> contours = new ArrayList<>();\n Mat hierarchey = new Mat();\n Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE,\n Imgproc.CHAIN_APPROX_SIMPLE);\n Mat draw = Mat.zeros(src.size(), CvType.CV_8UC3);\n for (int i = 0; i < contours.size(); i++) {\n Scalar color = new Scalar(0, 0, 255);\n //Calculating the area\n double cont_area = Imgproc.contourArea(contours.get(i));\n System.out.println(cont_area);\n if(cont_area>5000.0){\n Imgproc.drawContours(draw, contours, i, color, 2,\n Imgproc.LINE_8, hierarchey, 2, new Point() ) ;\n } else {\n color = new Scalar(255, 255, 255);\n Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8,\n hierarchey, 2, new Point() ) ;\n }\n }\n HighGui.imshow(\"Contours operation\", draw);\n HighGui.waitKey();\n }\n}" }, { "code": null, "e": 3872, "s": 3860, "text": "Input Image" }, { "code": null, "e": 3906, "s": 3872, "text": "4091.0\n6336.0\n189.0\n6439.0\n4903.0" }, { "code": null, "e": 3990, "s": 3906, "text": "In addition to the above output, the above program generates the following window −" } ]
HTML Tutorial
HTML stands for Hyper Text Markup Language, which is the most widely used language on Web to develop web pages. HTML was created by Berners-Lee in late 1991 but "HTML 2.0" was the first standard HTML specification which was published in 1995. HTML 4.01 was a major version of HTML and it was published in late 1999. Though HTML 4.01 version is widely used but currently we are having HTML-5 version which is an extension to HTML 4.01, and this version was published in 2012. Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between researchers. Now, HTML is being widely used to format web pages with the help of different tags available in HTML language. HTML is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning HTML: Create Web site - You can create a website or customize an existing web template if you know HTML well. Create Web site - You can create a website or customize an existing web template if you know HTML well. Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill. Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill. Understand web - If you want to optimize your website, to boost its speed and performance, it is good to know HTML to yield best results. Understand web - If you want to optimize your website, to boost its speed and performance, it is good to know HTML to yield best results. Learn other languages - Once you understands the basic of HTML then other related technologies like javascript, php, or angular are become easier to understand. Learn other languages - Once you understands the basic of HTML then other related technologies like javascript, php, or angular are become easier to understand. Just to give you a little excitement about HTML, I'm going to give you a small conventional HTML Hello World program, You can try it using Demo link. <!DOCTYPE html> <html> <head> <title>This is document title</title> </head> <body> <h1>This is a heading</h1> <p>Hello World!</p> </body> </html> As mentioned before, HTML is one of the most widely used language over the web. I'm going to list few of them here: Web pages development - HTML is used to create pages which are rendered over the web. Almost every page of web is having html tags in it to render its details in browser. Web pages development - HTML is used to create pages which are rendered over the web. Almost every page of web is having html tags in it to render its details in browser. Internet Navigation - HTML provides tags which are used to navigate from one page to another and is heavily used in internet navigation. Internet Navigation - HTML provides tags which are used to navigate from one page to another and is heavily used in internet navigation. Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop or laptops owing to responsive design strategy. Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop or laptops owing to responsive design strategy. Offline support HTML pages once loaded can be made available offline on the machine without any need of internet. Offline support HTML pages once loaded can be made available offline on the machine without any need of internet. Game development- HTML5 has native support for rich experience and is now useful in gaming developent arena as well. Game development- HTML5 has native support for rich experience and is now useful in gaming developent arena as well. This HTML tutorial is designed for the aspiring Web Designers and Developers with a need to understand the HTML in enough detail along with its simple overview, and practical examples. This tutorial will give you enough ingredients to start with HTML from where you can take yourself at higher level of expertise. Before proceeding with this tutorial you should have a basic working knowledge with Windows or Linux operating system, additionally you must be familiar with − Experience with any text editor like notepad, notepad++, or Edit plus etc. How to create directories and files on your computer. How to navigate through different directories. How to type content in a file and save them on a computer. Understanding about images in different formats like JPEG, PNG format. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2849, "s": 2374, "text": "HTML stands for Hyper Text Markup Language, which is the most widely used language on Web to develop web pages. HTML was created by Berners-Lee in late 1991 but \"HTML 2.0\" was the first standard HTML specification which was published in 1995. HTML 4.01 was a major version of HTML and it was published in late 1999. Though HTML 4.01 version is widely used but currently we are having HTML-5 version which is an extension to HTML 4.01, and this version was published in 2012." }, { "code": null, "e": 3166, "s": 2849, "text": "Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between researchers. Now, HTML is being widely used to format web pages with the help of different tags available in HTML language." }, { "code": null, "e": 3377, "s": 3166, "text": "HTML is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning HTML:" }, { "code": null, "e": 3481, "s": 3377, "text": "Create Web site - You can create a website or customize an existing web template if you know HTML well." }, { "code": null, "e": 3585, "s": 3481, "text": "Create Web site - You can create a website or customize an existing web template if you know HTML well." }, { "code": null, "e": 3711, "s": 3585, "text": "Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill." }, { "code": null, "e": 3837, "s": 3711, "text": "Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill." }, { "code": null, "e": 3975, "s": 3837, "text": "Understand web - If you want to optimize your website, to boost its speed and performance, it is good to know HTML to yield best results." }, { "code": null, "e": 4113, "s": 3975, "text": "Understand web - If you want to optimize your website, to boost its speed and performance, it is good to know HTML to yield best results." }, { "code": null, "e": 4274, "s": 4113, "text": "Learn other languages - Once you understands the basic of HTML then other related technologies like javascript, php, or angular are become easier to understand." }, { "code": null, "e": 4435, "s": 4274, "text": "Learn other languages - Once you understands the basic of HTML then other related technologies like javascript, php, or angular are become easier to understand." }, { "code": null, "e": 4585, "s": 4435, "text": "Just to give you a little excitement about HTML, I'm going to give you a small conventional HTML Hello World program, You can try it using Demo link." }, { "code": null, "e": 4763, "s": 4585, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>This is document title</title>\n </head>\t\n <body>\n <h1>This is a heading</h1>\n <p>Hello World!</p>\n </body>\t\n</html>" }, { "code": null, "e": 4879, "s": 4763, "text": "As mentioned before, HTML is one of the most widely used language over the web. I'm going to list few of them here:" }, { "code": null, "e": 5050, "s": 4879, "text": "Web pages development - HTML is used to create pages which are rendered over the web. Almost every page of web is having html tags in it to render its details in browser." }, { "code": null, "e": 5221, "s": 5050, "text": "Web pages development - HTML is used to create pages which are rendered over the web. Almost every page of web is having html tags in it to render its details in browser." }, { "code": null, "e": 5358, "s": 5221, "text": "Internet Navigation - HTML provides tags which are used to navigate from one page to another and is heavily used in internet navigation." }, { "code": null, "e": 5495, "s": 5358, "text": "Internet Navigation - HTML provides tags which are used to navigate from one page to another and is heavily used in internet navigation." }, { "code": null, "e": 5631, "s": 5495, "text": "Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop or laptops owing to responsive design strategy." }, { "code": null, "e": 5767, "s": 5631, "text": "Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop or laptops owing to responsive design strategy." }, { "code": null, "e": 5883, "s": 5769, "text": "Offline support HTML pages once loaded can be made available offline on the machine without any need of internet." }, { "code": null, "e": 5997, "s": 5883, "text": "Offline support HTML pages once loaded can be made available offline on the machine without any need of internet." }, { "code": null, "e": 6114, "s": 5997, "text": "Game development- HTML5 has native support for rich experience and is now useful in gaming developent arena as well." }, { "code": null, "e": 6231, "s": 6114, "text": "Game development- HTML5 has native support for rich experience and is now useful in gaming developent arena as well." }, { "code": null, "e": 6545, "s": 6231, "text": "This HTML tutorial is designed for the aspiring Web Designers and Developers with a need to understand the HTML in enough detail along with its simple overview, and practical examples. This tutorial will give you enough ingredients to start with HTML from where you can take yourself at higher level of expertise." }, { "code": null, "e": 6705, "s": 6545, "text": "Before proceeding with this tutorial you should have a basic working knowledge with Windows or Linux operating system, additionally you must be familiar with −" }, { "code": null, "e": 6780, "s": 6705, "text": "Experience with any text editor like notepad, notepad++, or Edit plus etc." }, { "code": null, "e": 6834, "s": 6780, "text": "How to create directories and files on your computer." }, { "code": null, "e": 6881, "s": 6834, "text": "How to navigate through different directories." }, { "code": null, "e": 6940, "s": 6881, "text": "How to type content in a file and save them on a computer." }, { "code": null, "e": 7011, "s": 6940, "text": "Understanding about images in different formats like JPEG, PNG format." }, { "code": null, "e": 7044, "s": 7011, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7058, "s": 7044, "text": " Anadi Sharma" }, { "code": null, "e": 7093, "s": 7058, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7107, "s": 7093, "text": " Anadi Sharma" }, { "code": null, "e": 7142, "s": 7107, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7159, "s": 7142, "text": " Frahaan Hussain" }, { "code": null, "e": 7194, "s": 7159, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7225, "s": 7194, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7258, "s": 7225, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 7289, "s": 7258, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7324, "s": 7289, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7355, "s": 7324, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7362, "s": 7355, "text": " Print" }, { "code": null, "e": 7373, "s": 7362, "text": " Add Notes" } ]
Gentle Introduction To Text Representation - Part - 1 | by Sundaresh Chandran | Towards Data Science
Computers are brilliant when dealing with numbers. They are faster than humans in calculations & decoding patterns by many orders of magnitude. But what if the data is not numerical? What if it's language? What happens when the data is in characters, words & sentences? How do we make computers process our language? How does Alexa, Google Home & many other smart assistants understand & reply to our speech? If you are looking to get answers to some of these questions, this article will be a stepping stone for you in the right direction. Natural Language Processing is a sub-field of artificial intelligence that works on making machines understand & process human language. The most basic step for the majority of natural language processing (NLP) tasks is to convert words into numbers for machines to understand & decode patterns within a language. We call this step text representation. This step, though iterative, plays a significant role in deciding features for your machine learning model/algorithm. Text representations can be broadly classified into two sections: Discrete text representations Distributed/Continuous text representations This article will focus on discrete text representations & we will dive into some of the frequently used ones with basic Sklearn implementations. These are representations where words are represented by their corresponding indexes to their position in a dictionary from a larger corpus or corpora. Famous representations that fall within this category are: One-Hot encoding Bag-of-words representation (BOW) Basic BOW — CountVectorizer Advanced BOW — TF-IDF It is a type of representation that assigns 0 to all elements in a vector except for one, which has a value of 1. This value represents a category of an element. For example: If i had a sentence, “I love my dog”, each word in the sentence would be represented as below: I → [1 0 0 0], love → [0 1 0 0], my → [0 0 1 0], dog → [0 0 0 1] The entire sentence is then represented as: sentence = [ [1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1] ] The intuition behind one-hot encoding is that each bit represents a possible category & if a particular variable cannot fall into multiple categories, then a single bit is enough to represent it As you may have grasped, the length of an array of word depends on the vocabulary size. This is not scalable for a very large corpus which could contain up to 100,000 unique words or even more. Lets now implement this using Sklearn: from sklearn.preprocessing import OneHotEncoderimport itertools# two example documentsdocs = ["cat","dog","bat","ate"]# split documents to tokenstokens_docs = [doc.split(" ") for doc in docs]# convert list of of token-lists to one flat list of tokens# and then create a dictionary that maps word to id of word,all_tokens = itertools.chain.from_iterable(tokens_docs)word_to_id = {token: idx for idx, token in enumerate(set(all_tokens))}# convert token lists to token-id liststoken_ids = [[word_to_id[token] for token in tokens_doc] for tokens_doc in tokens_docs]# convert list of token-id lists to one-hot representationvec = OneHotEncoder(categories="auto")X = vec.fit_transform(token_ids)print(X.toarray()) [[0. 0. 1. 0.] [0. 1. 0. 0.] [0. 0. 0. 1.] [1. 0. 0. 0.]] scikit-learn.org Easy to understand & implement Explosion in feature space if number of categories are very high The vector representation of words is orthogonal and cannot determine or measure relationship between different words Cannot measure importance of a word in a sentence but understand mere presence/absence of a word in a sentence High dimensional sparse matrix representation can be memory & computationally expensive Bag-of-words representation as the name suggests intutively, puts words in a “bag” & computes frequency of occurrence of each word. It does not take into account the word order or lexical information for text representation The intuition behind BOW representation is that document having similar words are similar irrespective of the word positioning The CountVectorizer computes the frequency of occurrence of a word in a document. It converts the corpus of multiple sentences (say product reviews) into a matrix of reviews & words & fills it with frequency of each word in a sentence Lets see how we can use Sklearn CountVectorizer: from sklearn.feature_extraction.text import CountVectorizertext = ["i love nlp. nlp is so cool"]vectorizer = CountVectorizer()# tokenize and build vocabvectorizer.fit(text)print(vectorizer.vocabulary_)# Output: {'love': 2, 'nlp': 3, 'is': 1, 'so': 4, 'cool': 0}# encode documentvector = vectorizer.transform(text)# summarize encoded vectorprint(vector.shape) # Output: (1, 5)print(vector.toarray()) [[1 1 1 2 1]] As you see the word “nlp” occurs twice in the sentence & also falls in index 3. Which we can see as the output of the final print statement The “weight” of a word in a sentence is its frequency There are various parameters that can be tweaked as part of the CountVectorizer to get the desired results including text preprocessing parameters like lowercase, strp_accents, preprocessor A complete list of parameters can be found in Sklearn documentation below: scikit-learn.org CountVectorizer also gives us frequency of words in a text document/sentence which One-hot encoding fails to provide Length of the encoded vector is the length of the dictionary This method ignores the location information of the word. It is not possible to grasp the meaning of a word from this representation The intuition that high-frequency words are more important or give more information about the sentence fails when it comes to stop words like “is, the, an, I” & when the corpus is context-specific. For example, in a corpus about covid-19, the word coronavirus may not add a lot of value To suppress the very high-frequency words & ignore the low-frequency words, there is a need to normalize the “weights” of the words accordingly TF-IDF representation: The full form of TF-IDF is term frequency-inverse document frequency is a product of 2 factors Where, TF(w, d) is frequency of word ‘w’ in document ‘d’ IDF(w) can be further broken down as: Where, N is total number of documents, & df(w) is the frequency of documents containing the word ‘w’ Intuition behind TF-IDF is that the weight assigned to each word not only depends on a words frequency, but also how frequent that particular word is in the entire corpus/corpora It takes the CountVectorizer discussed in the section above & multiplies it by the IDF score. The resultant output weights for the words from the process is low for very highly frequent words (like stop-words) & very low frequency words (noise terms) Lets now try to implement this using Sklearn from sklearn.feature_extraction.text import TfidfVectorizertext1 = ['i love nlp', 'nlp is so cool', 'nlp is all about helping machines process language', 'this tutorial is on baisc nlp technique']tf = TfidfVectorizer()txt_fitted = tf.fit(text1)txt_transformed = txt_fitted.transform(text1)print ("The text: ", text1)# Output: The text: ['i love nlp', 'nlp is so cool', # 'nlp is all about helping machines process language', # 'this tutorial is on basic nlp technique']idf = tf.idf_print(dict(zip(txt_fitted.get_feature_names(), idf))) {'about': 1.916290731874155, 'all': 1.916290731874155, 'basic': 1.916290731874155, 'cool': 1.916290731874155, 'helping': 1.916290731874155, 'is': 1.2231435513142097, 'language': 1.916290731874155, 'love': 1.916290731874155, 'machines': 1.916290731874155, 'nlp': 1.0, 'on': 1.916290731874155, 'process': 1.916290731874155, 'so': 1.916290731874155, 'technique': 1.916290731874155, 'this': 1.916290731874155, 'tutorial': 1.916290731874155} Note the weightage of word ‘nlp’. Since it is present in all the sentences, it is given a low weightage of 1.0. Similarly, the stop-word ‘is’ is also given a comparatively low weightage of 1.22 since it is present in 3 out of 4 sentences given. Similar to CountVectorizer, there are various parameters that can be tweaked to achieve desired results. Some of the important parameters (apart from the text preprocessing parameters like lowercase, strip_accent, stop_words etc.) are max_df, min_df, norm, ngram_range & sublinear_tf. The impact of these parameters on outputs weights is beyond scope of this article & will be covered separately. You can find the complete documentation of TF-IDF vectorizer below: scikit-learn.org Simple, easy to understand & interpret implementation Builds over CountVectorizer to penalise highly frequent words & low frequency terms in a corpus. So in a way, IDF achieves in reducing noise in our matrix. Positional information of the word is still not captured in this representation TF-IDF is highly corpus dependent. A matrix representation generated out of cricket data cannot be used for football or volleyball. Therefore, there is a need to have high quality training data Discrete representation is where each word is considered unique & converted into numerical based on various techniques we discussed above. We’ve seen few overlapping advantages & disadvantages across various discrete representations, lets summarise it as a whole Simple representations that are easy to understand, implement & interpret Algorithms like TF-IDF can be used to filter out uncommon & irrelevant words easily helping model train & converge faster The representation is directly proportional to vocabulary size. High vocabulary size can lead to memory constraints It does not leverage co-occurrence statistics between words. It assumes all words are independent of each other This leads to highly sparse vectors with few non zero values They do not capture the context or semantics of the word. It does not consider spooky & scary as similar but as two independent terms with no commonality between them Discrete representations are widely used across both classical machine learning & deep learning applications for solving complicated use cases like document similarity, sentiment classification, spam classification & topic modeling to name a few. In the next part, we will discuss distributed or a continuous text representation of text & how it is better (or worse) than discrete representations. Hope you enjoyed this article. See you soon! Edit: Part-2 of the series: https://medium.com/@sundareshchandran/introduction-to-text-representations-for-language-processing-part-2-54fe6907868 github.com Like my article? Buy me a coffee
[ { "code": null, "e": 713, "s": 172, "text": "Computers are brilliant when dealing with numbers. They are faster than humans in calculations & decoding patterns by many orders of magnitude. But what if the data is not numerical? What if it's language? What happens when the data is in characters, words & sentences? How do we make computers process our language? How does Alexa, Google Home & many other smart assistants understand & reply to our speech? If you are looking to get answers to some of these questions, this article will be a stepping stone for you in the right direction." }, { "code": null, "e": 1184, "s": 713, "text": "Natural Language Processing is a sub-field of artificial intelligence that works on making machines understand & process human language. The most basic step for the majority of natural language processing (NLP) tasks is to convert words into numbers for machines to understand & decode patterns within a language. We call this step text representation. This step, though iterative, plays a significant role in deciding features for your machine learning model/algorithm." }, { "code": null, "e": 1250, "s": 1184, "text": "Text representations can be broadly classified into two sections:" }, { "code": null, "e": 1280, "s": 1250, "text": "Discrete text representations" }, { "code": null, "e": 1324, "s": 1280, "text": "Distributed/Continuous text representations" }, { "code": null, "e": 1470, "s": 1324, "text": "This article will focus on discrete text representations & we will dive into some of the frequently used ones with basic Sklearn implementations." }, { "code": null, "e": 1622, "s": 1470, "text": "These are representations where words are represented by their corresponding indexes to their position in a dictionary from a larger corpus or corpora." }, { "code": null, "e": 1681, "s": 1622, "text": "Famous representations that fall within this category are:" }, { "code": null, "e": 1698, "s": 1681, "text": "One-Hot encoding" }, { "code": null, "e": 1732, "s": 1698, "text": "Bag-of-words representation (BOW)" }, { "code": null, "e": 1760, "s": 1732, "text": "Basic BOW — CountVectorizer" }, { "code": null, "e": 1782, "s": 1760, "text": "Advanced BOW — TF-IDF" }, { "code": null, "e": 1944, "s": 1782, "text": "It is a type of representation that assigns 0 to all elements in a vector except for one, which has a value of 1. This value represents a category of an element." }, { "code": null, "e": 1957, "s": 1944, "text": "For example:" }, { "code": null, "e": 2052, "s": 1957, "text": "If i had a sentence, “I love my dog”, each word in the sentence would be represented as below:" }, { "code": null, "e": 2117, "s": 2052, "text": "I → [1 0 0 0], love → [0 1 0 0], my → [0 0 1 0], dog → [0 0 0 1]" }, { "code": null, "e": 2161, "s": 2117, "text": "The entire sentence is then represented as:" }, { "code": null, "e": 2216, "s": 2161, "text": "sentence = [ [1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1] ]" }, { "code": null, "e": 2411, "s": 2216, "text": "The intuition behind one-hot encoding is that each bit represents a possible category & if a particular variable cannot fall into multiple categories, then a single bit is enough to represent it" }, { "code": null, "e": 2605, "s": 2411, "text": "As you may have grasped, the length of an array of word depends on the vocabulary size. This is not scalable for a very large corpus which could contain up to 100,000 unique words or even more." }, { "code": null, "e": 2644, "s": 2605, "text": "Lets now implement this using Sklearn:" }, { "code": null, "e": 3352, "s": 2644, "text": "from sklearn.preprocessing import OneHotEncoderimport itertools# two example documentsdocs = [\"cat\",\"dog\",\"bat\",\"ate\"]# split documents to tokenstokens_docs = [doc.split(\" \") for doc in docs]# convert list of of token-lists to one flat list of tokens# and then create a dictionary that maps word to id of word,all_tokens = itertools.chain.from_iterable(tokens_docs)word_to_id = {token: idx for idx, token in enumerate(set(all_tokens))}# convert token lists to token-id liststoken_ids = [[word_to_id[token] for token in tokens_doc] for tokens_doc in tokens_docs]# convert list of token-id lists to one-hot representationvec = OneHotEncoder(categories=\"auto\")X = vec.fit_transform(token_ids)print(X.toarray())" }, { "code": null, "e": 3410, "s": 3352, "text": "[[0. 0. 1. 0.] [0. 1. 0. 0.] [0. 0. 0. 1.] [1. 0. 0. 0.]]" }, { "code": null, "e": 3427, "s": 3410, "text": "scikit-learn.org" }, { "code": null, "e": 3458, "s": 3427, "text": "Easy to understand & implement" }, { "code": null, "e": 3523, "s": 3458, "text": "Explosion in feature space if number of categories are very high" }, { "code": null, "e": 3641, "s": 3523, "text": "The vector representation of words is orthogonal and cannot determine or measure relationship between different words" }, { "code": null, "e": 3752, "s": 3641, "text": "Cannot measure importance of a word in a sentence but understand mere presence/absence of a word in a sentence" }, { "code": null, "e": 3840, "s": 3752, "text": "High dimensional sparse matrix representation can be memory & computationally expensive" }, { "code": null, "e": 4064, "s": 3840, "text": "Bag-of-words representation as the name suggests intutively, puts words in a “bag” & computes frequency of occurrence of each word. It does not take into account the word order or lexical information for text representation" }, { "code": null, "e": 4191, "s": 4064, "text": "The intuition behind BOW representation is that document having similar words are similar irrespective of the word positioning" }, { "code": null, "e": 4426, "s": 4191, "text": "The CountVectorizer computes the frequency of occurrence of a word in a document. It converts the corpus of multiple sentences (say product reviews) into a matrix of reviews & words & fills it with frequency of each word in a sentence" }, { "code": null, "e": 4475, "s": 4426, "text": "Lets see how we can use Sklearn CountVectorizer:" }, { "code": null, "e": 4874, "s": 4475, "text": "from sklearn.feature_extraction.text import CountVectorizertext = [\"i love nlp. nlp is so cool\"]vectorizer = CountVectorizer()# tokenize and build vocabvectorizer.fit(text)print(vectorizer.vocabulary_)# Output: {'love': 2, 'nlp': 3, 'is': 1, 'so': 4, 'cool': 0}# encode documentvector = vectorizer.transform(text)# summarize encoded vectorprint(vector.shape) # Output: (1, 5)print(vector.toarray())" }, { "code": null, "e": 4888, "s": 4874, "text": "[[1 1 1 2 1]]" }, { "code": null, "e": 5028, "s": 4888, "text": "As you see the word “nlp” occurs twice in the sentence & also falls in index 3. Which we can see as the output of the final print statement" }, { "code": null, "e": 5082, "s": 5028, "text": "The “weight” of a word in a sentence is its frequency" }, { "code": null, "e": 5272, "s": 5082, "text": "There are various parameters that can be tweaked as part of the CountVectorizer to get the desired results including text preprocessing parameters like lowercase, strp_accents, preprocessor" }, { "code": null, "e": 5347, "s": 5272, "text": "A complete list of parameters can be found in Sklearn documentation below:" }, { "code": null, "e": 5364, "s": 5347, "text": "scikit-learn.org" }, { "code": null, "e": 5481, "s": 5364, "text": "CountVectorizer also gives us frequency of words in a text document/sentence which One-hot encoding fails to provide" }, { "code": null, "e": 5542, "s": 5481, "text": "Length of the encoded vector is the length of the dictionary" }, { "code": null, "e": 5675, "s": 5542, "text": "This method ignores the location information of the word. It is not possible to grasp the meaning of a word from this representation" }, { "code": null, "e": 5962, "s": 5675, "text": "The intuition that high-frequency words are more important or give more information about the sentence fails when it comes to stop words like “is, the, an, I” & when the corpus is context-specific. For example, in a corpus about covid-19, the word coronavirus may not add a lot of value" }, { "code": null, "e": 6106, "s": 5962, "text": "To suppress the very high-frequency words & ignore the low-frequency words, there is a need to normalize the “weights” of the words accordingly" }, { "code": null, "e": 6224, "s": 6106, "text": "TF-IDF representation: The full form of TF-IDF is term frequency-inverse document frequency is a product of 2 factors" }, { "code": null, "e": 6281, "s": 6224, "text": "Where, TF(w, d) is frequency of word ‘w’ in document ‘d’" }, { "code": null, "e": 6319, "s": 6281, "text": "IDF(w) can be further broken down as:" }, { "code": null, "e": 6420, "s": 6319, "text": "Where, N is total number of documents, & df(w) is the frequency of documents containing the word ‘w’" }, { "code": null, "e": 6599, "s": 6420, "text": "Intuition behind TF-IDF is that the weight assigned to each word not only depends on a words frequency, but also how frequent that particular word is in the entire corpus/corpora" }, { "code": null, "e": 6850, "s": 6599, "text": "It takes the CountVectorizer discussed in the section above & multiplies it by the IDF score. The resultant output weights for the words from the process is low for very highly frequent words (like stop-words) & very low frequency words (noise terms)" }, { "code": null, "e": 6895, "s": 6850, "text": "Lets now try to implement this using Sklearn" }, { "code": null, "e": 7432, "s": 6895, "text": "from sklearn.feature_extraction.text import TfidfVectorizertext1 = ['i love nlp', 'nlp is so cool', 'nlp is all about helping machines process language', 'this tutorial is on baisc nlp technique']tf = TfidfVectorizer()txt_fitted = tf.fit(text1)txt_transformed = txt_fitted.transform(text1)print (\"The text: \", text1)# Output: The text: ['i love nlp', 'nlp is so cool', # 'nlp is all about helping machines process language', # 'this tutorial is on basic nlp technique']idf = tf.idf_print(dict(zip(txt_fitted.get_feature_names(), idf)))" }, { "code": null, "e": 7869, "s": 7432, "text": "{'about': 1.916290731874155, 'all': 1.916290731874155, 'basic': 1.916290731874155, 'cool': 1.916290731874155, 'helping': 1.916290731874155, 'is': 1.2231435513142097, 'language': 1.916290731874155, 'love': 1.916290731874155, 'machines': 1.916290731874155, 'nlp': 1.0, 'on': 1.916290731874155, 'process': 1.916290731874155, 'so': 1.916290731874155, 'technique': 1.916290731874155, 'this': 1.916290731874155, 'tutorial': 1.916290731874155}" }, { "code": null, "e": 8114, "s": 7869, "text": "Note the weightage of word ‘nlp’. Since it is present in all the sentences, it is given a low weightage of 1.0. Similarly, the stop-word ‘is’ is also given a comparatively low weightage of 1.22 since it is present in 3 out of 4 sentences given." }, { "code": null, "e": 8511, "s": 8114, "text": "Similar to CountVectorizer, there are various parameters that can be tweaked to achieve desired results. Some of the important parameters (apart from the text preprocessing parameters like lowercase, strip_accent, stop_words etc.) are max_df, min_df, norm, ngram_range & sublinear_tf. The impact of these parameters on outputs weights is beyond scope of this article & will be covered separately." }, { "code": null, "e": 8579, "s": 8511, "text": "You can find the complete documentation of TF-IDF vectorizer below:" }, { "code": null, "e": 8596, "s": 8579, "text": "scikit-learn.org" }, { "code": null, "e": 8650, "s": 8596, "text": "Simple, easy to understand & interpret implementation" }, { "code": null, "e": 8806, "s": 8650, "text": "Builds over CountVectorizer to penalise highly frequent words & low frequency terms in a corpus. So in a way, IDF achieves in reducing noise in our matrix." }, { "code": null, "e": 8886, "s": 8806, "text": "Positional information of the word is still not captured in this representation" }, { "code": null, "e": 9080, "s": 8886, "text": "TF-IDF is highly corpus dependent. A matrix representation generated out of cricket data cannot be used for football or volleyball. Therefore, there is a need to have high quality training data" }, { "code": null, "e": 9343, "s": 9080, "text": "Discrete representation is where each word is considered unique & converted into numerical based on various techniques we discussed above. We’ve seen few overlapping advantages & disadvantages across various discrete representations, lets summarise it as a whole" }, { "code": null, "e": 9417, "s": 9343, "text": "Simple representations that are easy to understand, implement & interpret" }, { "code": null, "e": 9539, "s": 9417, "text": "Algorithms like TF-IDF can be used to filter out uncommon & irrelevant words easily helping model train & converge faster" }, { "code": null, "e": 9655, "s": 9539, "text": "The representation is directly proportional to vocabulary size. High vocabulary size can lead to memory constraints" }, { "code": null, "e": 9767, "s": 9655, "text": "It does not leverage co-occurrence statistics between words. It assumes all words are independent of each other" }, { "code": null, "e": 9828, "s": 9767, "text": "This leads to highly sparse vectors with few non zero values" }, { "code": null, "e": 9995, "s": 9828, "text": "They do not capture the context or semantics of the word. It does not consider spooky & scary as similar but as two independent terms with no commonality between them" }, { "code": null, "e": 10242, "s": 9995, "text": "Discrete representations are widely used across both classical machine learning & deep learning applications for solving complicated use cases like document similarity, sentiment classification, spam classification & topic modeling to name a few." }, { "code": null, "e": 10393, "s": 10242, "text": "In the next part, we will discuss distributed or a continuous text representation of text & how it is better (or worse) than discrete representations." }, { "code": null, "e": 10438, "s": 10393, "text": "Hope you enjoyed this article. See you soon!" }, { "code": null, "e": 10584, "s": 10438, "text": "Edit: Part-2 of the series: https://medium.com/@sundareshchandran/introduction-to-text-representations-for-language-processing-part-2-54fe6907868" }, { "code": null, "e": 10595, "s": 10584, "text": "github.com" } ]
Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images) - GeeksforGeeks
12 Oct, 2021 Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT AND OR XOR NOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can be helpful in enhancing the properties of the input images. NOTE: The Bitwise operations should be applied on input images of same dimensionsInput Image 1: Input Image 2: Bit-wise conjunction of input array elements. Syntax: cv2.bitwise_and(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask Python3 # Python program to illustrate# arithmetic operation of# bitwise AND of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_and is applied over the# image inputs with applied parametersdest_and = cv2.bitwise_and(img2, img1, mask = None) # the window showing output image# with the Bitwise AND operation# on the input imagescv2.imshow('Bitwise And', dest_and) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: Bit-wise disjunction of input array elements. Syntax: cv2.bitwise_or(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask Python3 # Python program to illustrate# arithmetic operation of# bitwise OR of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_or is applied over the# image inputs with applied parametersdest_or = cv2.bitwise_or(img2, img1, mask = None) # the window showing output image# with the Bitwise OR operation# on the input imagescv2.imshow('Bitwise OR', dest_or) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: Bit-wise exclusive-OR operation on input array elements. Syntax: cv2.bitwise_xor(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask Python3 # Python program to illustrate# arithmetic operation of# bitwise XOR of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_xor is applied over the# image inputs with applied parametersdest_xor = cv2.bitwise_xor(img1, img2, mask = None) # the window showing output image# with the Bitwise XOR operation# on the input imagescv2.imshow('Bitwise XOR', dest_xor) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: Inversion of input array elements. Syntax: cv2.bitwise_not(source, destination, mask)Parameters: source: Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask Python3 # Python program to illustrate# arithmetic operation of# bitwise NOT on input image # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_not is applied over the# image input with applied parametersdest_not1 = cv2.bitwise_not(img1, mask = None)dest_not2 = cv2.bitwise_not(img2, mask = None) # the windows showing output image# with the Bitwise NOT operation# on the 1st and 2nd input imagecv2.imshow('Bitwise NOT on image 1', dest_not1)cv2.imshow('Bitwise NOT on image 2', dest_not2) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: Bitwise NOT on Image 1 Bitwise NOT on Image 2 joeblues khushboogoyal499 Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41552, "s": 41524, "text": "\n12 Oct, 2021" }, { "code": null, "e": 41758, "s": 41552, "text": "Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : " }, { "code": null, "e": 41770, "s": 41758, "text": "ANDORXORNOT" }, { "code": null, "e": 41774, "s": 41770, "text": "AND" }, { "code": null, "e": 41777, "s": 41774, "text": "OR" }, { "code": null, "e": 41781, "s": 41777, "text": "XOR" }, { "code": null, "e": 41785, "s": 41781, "text": "NOT" }, { "code": null, "e": 42078, "s": 41785, "text": "Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can be helpful in enhancing the properties of the input images. NOTE: The Bitwise operations should be applied on input images of same dimensionsInput Image 1: " }, { "code": null, "e": 42095, "s": 42078, "text": "Input Image 2: " }, { "code": null, "e": 42145, "s": 42097, "text": "Bit-wise conjunction of input array elements. " }, { "code": null, "e": 42508, "s": 42145, "text": "Syntax: cv2.bitwise_and(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask " }, { "code": null, "e": 42518, "s": 42510, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# bitwise AND of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_and is applied over the# image inputs with applied parametersdest_and = cv2.bitwise_and(img2, img1, mask = None) # the window showing output image# with the Bitwise AND operation# on the input imagescv2.imshow('Bitwise And', dest_and) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 43153, "s": 42518, "text": null }, { "code": null, "e": 43163, "s": 43153, "text": "Output: " }, { "code": null, "e": 43213, "s": 43165, "text": "Bit-wise disjunction of input array elements. " }, { "code": null, "e": 43575, "s": 43213, "text": "Syntax: cv2.bitwise_or(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask " }, { "code": null, "e": 43585, "s": 43577, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# bitwise OR of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_or is applied over the# image inputs with applied parametersdest_or = cv2.bitwise_or(img2, img1, mask = None) # the window showing output image# with the Bitwise OR operation# on the input imagescv2.imshow('Bitwise OR', dest_or) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 44213, "s": 43585, "text": null }, { "code": null, "e": 44223, "s": 44213, "text": "Output: " }, { "code": null, "e": 44284, "s": 44225, "text": "Bit-wise exclusive-OR operation on input array elements. " }, { "code": null, "e": 44647, "s": 44284, "text": "Syntax: cv2.bitwise_xor(source1, source2, destination, mask)Parameters: source1: First Input Image array(Single-channel, 8-bit or floating-point) source2: Second Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask " }, { "code": null, "e": 44657, "s": 44649, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# bitwise XOR of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_xor is applied over the# image inputs with applied parametersdest_xor = cv2.bitwise_xor(img1, img2, mask = None) # the window showing output image# with the Bitwise XOR operation# on the input imagescv2.imshow('Bitwise XOR', dest_xor) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 45292, "s": 44657, "text": null }, { "code": null, "e": 45302, "s": 45292, "text": "Output: " }, { "code": null, "e": 45341, "s": 45304, "text": "Inversion of input array elements. " }, { "code": null, "e": 45612, "s": 45341, "text": "Syntax: cv2.bitwise_not(source, destination, mask)Parameters: source: Input Image array(Single-channel, 8-bit or floating-point) dest: Output array (Similar to the dimensions and type of Input image array) mask: Operation mask, Input / output 8-bit single-channel mask " }, { "code": null, "e": 45622, "s": 45614, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# bitwise NOT on input image # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread command img1 = cv2.imread('input1.png') img2 = cv2.imread('input2.png') # cv2.bitwise_not is applied over the# image input with applied parametersdest_not1 = cv2.bitwise_not(img1, mask = None)dest_not2 = cv2.bitwise_not(img2, mask = None) # the windows showing output image# with the Bitwise NOT operation# on the 1st and 2nd input imagecv2.imshow('Bitwise NOT on image 1', dest_not1)cv2.imshow('Bitwise NOT on image 2', dest_not2) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 46369, "s": 45622, "text": null }, { "code": null, "e": 46402, "s": 46369, "text": "Output: Bitwise NOT on Image 1 " }, { "code": null, "e": 46427, "s": 46402, "text": "Bitwise NOT on Image 2 " }, { "code": null, "e": 46438, "s": 46429, "text": "joeblues" }, { "code": null, "e": 46455, "s": 46438, "text": "khushboogoyal499" }, { "code": null, "e": 46472, "s": 46455, "text": "Image-Processing" }, { "code": null, "e": 46479, "s": 46472, "text": "OpenCV" }, { "code": null, "e": 46486, "s": 46479, "text": "Python" }, { "code": null, "e": 46584, "s": 46486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46593, "s": 46584, "text": "Comments" }, { "code": null, "e": 46606, "s": 46593, "text": "Old Comments" }, { "code": null, "e": 46634, "s": 46606, "text": "Read JSON file using Python" }, { "code": null, "e": 46684, "s": 46634, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 46706, "s": 46684, "text": "Python map() function" }, { "code": null, "e": 46750, "s": 46706, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 46785, "s": 46750, "text": "Read a file line by line in Python" }, { "code": null, "e": 46807, "s": 46785, "text": "Enumerate() in Python" }, { "code": null, "e": 46839, "s": 46807, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 46869, "s": 46839, "text": "Iterate over a list in Python" }, { "code": null, "e": 46911, "s": 46869, "text": "Different ways to create Pandas Dataframe" } ]
A backtracking approach to generate n bit Gray Codes - GeeksforGeeks
11 Jun, 2021 Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2 Explanation : 00 - 0 01 - 1 11 - 3 10 - 2 Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-bit Gray CodesThis article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is. C++ Java Python3 C# Javascript // CPP program to find the gray sequence of n bits.#include <iostream>#include <vector>using namespace std; /* we have 2 choices for each of the n bits either we can include i.e invert the bit or we can exclude the bit i.e we can leave the number as it is. */void grayCodeUtil(vector<int>& res, int n, int& num){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.push_back(num); return; } // ignore the bit. grayCodeUtil(res, n - 1, num); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1, num);} // returns the vector containing the gray// code sequence of n bits.vector<int> grayCodes(int n){ vector<int> res; // num is passed by reference to keep // track of current code. int num = 0; grayCodeUtil(res, n, num); return res;} // Driver function.int main(){ int n = 3; vector<int> code = grayCodes(n); for (int i = 0; i < code.size(); i++) cout << code[i] << endl; return 0;} // JAVA program to find the gray sequence of n bits.import java.util.*; class GFG{ static int num; /* we have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */static void grayCodeUtil(Vector<Integer> res, int n){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.add(num); return; } // ignore the bit. grayCodeUtil(res, n - 1); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1);} // returns the vector containing the gray// code sequence of n bits.static Vector<Integer> grayCodes(int n){ Vector<Integer> res = new Vector<Integer>(); // num is passed by reference to keep // track of current code. num = 0; grayCodeUtil(res, n); return res;} // Driver function.public static void main(String[] args){ int n = 3; Vector<Integer> code = grayCodes(n); for (int i = 0; i < code.size(); i++) System.out.print(code.get(i) +"\n");}} // This code is contributed by Rajput-Ji # Python3 program to find the# gray sequence of n bits. """ we have 2 choices for each of the n bitseither we can include i.e invert the bit orwe can exclude the bit i.e we can leavethe number as it is. """def grayCodeUtil(res, n, num): # base case when we run out bits to process # we simply include it in gray code sequence. if (n == 0): res.append(num[0]) return # ignore the bit. grayCodeUtil(res, n - 1, num) # invert the bit. num[0] = num[0] ^ (1 << (n - 1)) grayCodeUtil(res, n - 1, num) # returns the vector containing the gray# code sequence of n bits.def grayCodes(n): res = [] # num is passed by reference to keep # track of current code. num = [0] grayCodeUtil(res, n, num) return res # Driver Coden = 3code = grayCodes(n)for i in range(len(code)): print(code[i]) # This code is contributed by SHUBHAMSINGH10 // C# program to find the gray sequence of n bits.using System;using System.Collections.Generic; class GFG{ static int num; /* we have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */static void grayCodeUtil(List<int> res, int n){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.Add(num); return; } // ignore the bit. grayCodeUtil(res, n - 1); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1);} // returns the vector containing the gray// code sequence of n bits.static List<int> grayCodes(int n){ List<int> res = new List<int>(); // num is passed by reference to keep // track of current code. num = 0; grayCodeUtil(res, n); return res;} // Driver function.public static void Main(String[] args){ int n = 3; List<int> code = grayCodes(n); for (int i = 0; i < code.Count; i++) Console.Write(code[i] +"\n");}} // This code is contributed by 29AjayKumar <script> // Javascript program to find the gray sequence of n bits. /* We have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */function grayCodeUtil(res, n, num){ // Base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.push(num[0]); return; } // Ignore the bit. grayCodeUtil(res, n - 1, num); // Invert the bit. num[0] = num[0] ^ (1 << (n - 1)); grayCodeUtil(res, n - 1, num);} // Returns the vector containing the gray// code sequence of n bits.function grayCodes(n){ let res = []; // num is passed by reference to keep // track of current code. let num = [0]; grayCodeUtil(res, n, num); return res;} // Driver codelet n = 3;let code = grayCodes(n);for(let i = 0; i < code.length; i++) document.write(code[i] + "<br>"); // This code is contributed by gfgking </script> Output: 0 1 3 2 6 7 5 4 SHUBHAMSINGH10 Rajput-Ji 29AjayKumar gfgking gray-code Backtracking Bit Magic Bit Magic Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Print all paths from a given source to a destination Subset Sum | Backtracking-4 Backtracking to find all subsets Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24934, "s": 24906, "text": "\n11 Jun, 2021" }, { "code": null, "e": 25082, "s": 24934, "text": "Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) " }, { "code": null, "e": 25093, "s": 25082, "text": "Examples: " }, { "code": null, "e": 25203, "s": 25093, "text": "Input : 2 \nOutput : 0 1 3 2\nExplanation : \n00 - 0\n01 - 1\n11 - 3\n10 - 2\n\nInput : 3 \nOutput : 0 1 3 2 6 7 5 4\n " }, { "code": null, "e": 25583, "s": 25203, "text": "We have discussed an approach in Generate n-bit Gray CodesThis article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is. " }, { "code": null, "e": 25587, "s": 25583, "text": "C++" }, { "code": null, "e": 25592, "s": 25587, "text": "Java" }, { "code": null, "e": 25600, "s": 25592, "text": "Python3" }, { "code": null, "e": 25603, "s": 25600, "text": "C#" }, { "code": null, "e": 25614, "s": 25603, "text": "Javascript" }, { "code": "// CPP program to find the gray sequence of n bits.#include <iostream>#include <vector>using namespace std; /* we have 2 choices for each of the n bits either we can include i.e invert the bit or we can exclude the bit i.e we can leave the number as it is. */void grayCodeUtil(vector<int>& res, int n, int& num){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.push_back(num); return; } // ignore the bit. grayCodeUtil(res, n - 1, num); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1, num);} // returns the vector containing the gray// code sequence of n bits.vector<int> grayCodes(int n){ vector<int> res; // num is passed by reference to keep // track of current code. int num = 0; grayCodeUtil(res, n, num); return res;} // Driver function.int main(){ int n = 3; vector<int> code = grayCodes(n); for (int i = 0; i < code.size(); i++) cout << code[i] << endl; return 0;}", "e": 26662, "s": 25614, "text": null }, { "code": "// JAVA program to find the gray sequence of n bits.import java.util.*; class GFG{ static int num; /* we have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */static void grayCodeUtil(Vector<Integer> res, int n){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.add(num); return; } // ignore the bit. grayCodeUtil(res, n - 1); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1);} // returns the vector containing the gray// code sequence of n bits.static Vector<Integer> grayCodes(int n){ Vector<Integer> res = new Vector<Integer>(); // num is passed by reference to keep // track of current code. num = 0; grayCodeUtil(res, n); return res;} // Driver function.public static void main(String[] args){ int n = 3; Vector<Integer> code = grayCodes(n); for (int i = 0; i < code.size(); i++) System.out.print(code.get(i) +\"\\n\");}} // This code is contributed by Rajput-Ji", "e": 27782, "s": 26662, "text": null }, { "code": "# Python3 program to find the# gray sequence of n bits. \"\"\" we have 2 choices for each of the n bitseither we can include i.e invert the bit orwe can exclude the bit i.e we can leavethe number as it is. \"\"\"def grayCodeUtil(res, n, num): # base case when we run out bits to process # we simply include it in gray code sequence. if (n == 0): res.append(num[0]) return # ignore the bit. grayCodeUtil(res, n - 1, num) # invert the bit. num[0] = num[0] ^ (1 << (n - 1)) grayCodeUtil(res, n - 1, num) # returns the vector containing the gray# code sequence of n bits.def grayCodes(n): res = [] # num is passed by reference to keep # track of current code. num = [0] grayCodeUtil(res, n, num) return res # Driver Coden = 3code = grayCodes(n)for i in range(len(code)): print(code[i]) # This code is contributed by SHUBHAMSINGH10", "e": 28690, "s": 27782, "text": null }, { "code": "// C# program to find the gray sequence of n bits.using System;using System.Collections.Generic; class GFG{ static int num; /* we have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */static void grayCodeUtil(List<int> res, int n){ // base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.Add(num); return; } // ignore the bit. grayCodeUtil(res, n - 1); // invert the bit. num = num ^ (1 << (n - 1)); grayCodeUtil(res, n - 1);} // returns the vector containing the gray// code sequence of n bits.static List<int> grayCodes(int n){ List<int> res = new List<int>(); // num is passed by reference to keep // track of current code. num = 0; grayCodeUtil(res, n); return res;} // Driver function.public static void Main(String[] args){ int n = 3; List<int> code = grayCodes(n); for (int i = 0; i < code.Count; i++) Console.Write(code[i] +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 29799, "s": 28690, "text": null }, { "code": "<script> // Javascript program to find the gray sequence of n bits. /* We have 2 choices for each of the n bits either wecan include i.e invert the bit or we can exclude thebit i.e we can leave the number as it is. */function grayCodeUtil(res, n, num){ // Base case when we run out bits to process // we simply include it in gray code sequence. if (n == 0) { res.push(num[0]); return; } // Ignore the bit. grayCodeUtil(res, n - 1, num); // Invert the bit. num[0] = num[0] ^ (1 << (n - 1)); grayCodeUtil(res, n - 1, num);} // Returns the vector containing the gray// code sequence of n bits.function grayCodes(n){ let res = []; // num is passed by reference to keep // track of current code. let num = [0]; grayCodeUtil(res, n, num); return res;} // Driver codelet n = 3;let code = grayCodes(n);for(let i = 0; i < code.length; i++) document.write(code[i] + \"<br>\"); // This code is contributed by gfgking </script>", "e": 30791, "s": 29799, "text": null }, { "code": null, "e": 30800, "s": 30791, "text": "Output: " }, { "code": null, "e": 30816, "s": 30800, "text": "0\n1\n3\n2\n6\n7\n5\n4" }, { "code": null, "e": 30833, "s": 30818, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30843, "s": 30833, "text": "Rajput-Ji" }, { "code": null, "e": 30855, "s": 30843, "text": "29AjayKumar" }, { "code": null, "e": 30863, "s": 30855, "text": "gfgking" }, { "code": null, "e": 30873, "s": 30863, "text": "gray-code" }, { "code": null, "e": 30886, "s": 30873, "text": "Backtracking" }, { "code": null, "e": 30896, "s": 30886, "text": "Bit Magic" }, { "code": null, "e": 30906, "s": 30896, "text": "Bit Magic" }, { "code": null, "e": 30919, "s": 30906, "text": "Backtracking" }, { "code": null, "e": 31017, "s": 30919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31052, "s": 31017, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 31088, "s": 31052, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 31141, "s": 31088, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 31169, "s": 31141, "text": "Subset Sum | Backtracking-4" }, { "code": null, "e": 31202, "s": 31169, "text": "Backtracking to find all subsets" }, { "code": null, "e": 31229, "s": 31202, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 31275, "s": 31229, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31343, "s": 31275, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31389, "s": 31343, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
How does ++ and -- operators work in Python?
In C, C++, Java etc ++ and -- operators increment and decrement value of a variable by 1. In Python these operators won't work. In Python variables are just labels to objects in memory. In Python numeric objects are immutable. Hence by a++ (if a=10) we are trying to increment value of 10 object to 11 which is not allowed. >>> a=10 >>> a++ SyntaxError: invalid syntax Instead we have to use += operator >>> a=a+1 >>> a 11
[ { "code": null, "e": 1191, "s": 1062, "text": "In C, C++, Java etc ++ and -- operators increment and decrement value of a variable by 1. In Python these operators won't work. " }, { "code": null, "e": 1387, "s": 1191, "text": "In Python variables are just labels to objects in memory. In Python numeric objects are immutable. Hence by a++ (if a=10) we are trying to increment value of 10 object to 11 which is not allowed." }, { "code": null, "e": 1432, "s": 1387, "text": ">>> a=10\n>>> a++\nSyntaxError: invalid syntax" }, { "code": null, "e": 1467, "s": 1432, "text": "Instead we have to use += operator" }, { "code": null, "e": 1486, "s": 1467, "text": ">>> a=a+1\n>>> a\n11" } ]
Data Warehousing - Schemas
Schema is a logical description of the entire database. It includes the name and description of records of all record types including all associated data-items and aggregates. Much like a database, a data warehouse also requires to maintain a schema. A database uses relational model, while a data warehouse uses Star, Snowflake, and Fact Constellation schema. In this chapter, we will discuss the schemas used in a data warehouse. Each dimension in a star schema is represented with only one-dimension table. Each dimension in a star schema is represented with only one-dimension table. This dimension table contains the set of attributes. This dimension table contains the set of attributes. The following diagram shows the sales data of a company with respect to the four dimensions, namely time, item, branch, and location. The following diagram shows the sales data of a company with respect to the four dimensions, namely time, item, branch, and location. There is a fact table at the center. It contains the keys to each of four dimensions. There is a fact table at the center. It contains the keys to each of four dimensions. The fact table also contains the attributes, namely dollars sold and units sold. The fact table also contains the attributes, namely dollars sold and units sold. Note − Each dimension has only one dimension table and each table holds a set of attributes. For example, the location dimension table contains the attribute set {location_key, street, city, province_or_state,country}. This constraint may cause data redundancy. For example, "Vancouver" and "Victoria" both the cities are in the Canadian province of British Columbia. The entries for such cities may cause data redundancy along the attributes province_or_state and country. Some dimension tables in the Snowflake schema are normalized. Some dimension tables in the Snowflake schema are normalized. The normalization splits up the data into additional tables. The normalization splits up the data into additional tables. Unlike Star schema, the dimensions table in a snowflake schema are normalized. For example, the item dimension table in star schema is normalized and split into two dimension tables, namely item and supplier table. Unlike Star schema, the dimensions table in a snowflake schema are normalized. For example, the item dimension table in star schema is normalized and split into two dimension tables, namely item and supplier table. Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key. Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key. The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type. The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type. Note − Due to normalization in the Snowflake schema, the redundancy is reduced and therefore, it becomes easy to maintain and the save storage space. A fact constellation has multiple fact tables. It is also known as galaxy schema. A fact constellation has multiple fact tables. It is also known as galaxy schema. The following diagram shows two fact tables, namely sales and shipping. The following diagram shows two fact tables, namely sales and shipping. The sales fact table is same as that in the star schema. The sales fact table is same as that in the star schema. The shipping fact table has the five dimensions, namely item_key, time_key, shipper_key, from_location, to_location. The shipping fact table has the five dimensions, namely item_key, time_key, shipper_key, from_location, to_location. The shipping fact table also contains two measures, namely dollars sold and units sold. The shipping fact table also contains two measures, namely dollars sold and units sold. It is also possible to share dimension tables between fact tables. For example, time, item, and location dimension tables are shared between the sales and shipping fact table. It is also possible to share dimension tables between fact tables. For example, time, item, and location dimension tables are shared between the sales and shipping fact table. Multidimensional schema is defined using Data Mining Query Language (DMQL). The two primitives, cube definition and dimension definition, can be used for defining the data warehouses and data marts. define cube < cube_name > [ < dimension-list > }: < measure_list > define dimension < dimension_name > as ( < attribute_or_dimension_list > ) The star schema that we have discussed can be defined using Data Mining Query Language (DMQL) as follows − define cube sales star [time, item, branch, location]: dollars sold = sum(sales in dollars), units sold = count(*) define dimension time as (time key, day, day of week, month, quarter, year) define dimension item as (item key, item name, brand, type, supplier type) define dimension branch as (branch key, branch name, branch type) define dimension location as (location key, street, city, province or state, country) Snowflake schema can be defined using DMQL as follows − define cube sales snowflake [time, item, branch, location]: dollars sold = sum(sales in dollars), units sold = count(*) define dimension time as (time key, day, day of week, month, quarter, year) define dimension item as (item key, item name, brand, type, supplier (supplier key, supplier type)) define dimension branch as (branch key, branch name, branch type) define dimension location as (location key, street, city (city key, city, province or state, country)) Fact constellation schema can be defined using DMQL as follows − define cube sales [time, item, branch, location]: dollars sold = sum(sales in dollars), units sold = count(*) define dimension time as (time key, day, day of week, month, quarter, year) define dimension item as (item key, item name, brand, type, supplier type) define dimension branch as (branch key, branch name, branch type) define dimension location as (location key, street, city, province or state,country) define cube shipping [time, item, shipper, from location, to location]: dollars cost = sum(cost in dollars), units shipped = count(*) define dimension time as time in cube sales define dimension item as item in cube sales define dimension shipper as (shipper key, shipper name, location as location in cube sales, shipper type) define dimension from location as location in cube sales define dimension to location as location in cube sales Print Add Notes Bookmark this page
[ { "code": null, "e": 2410, "s": 1978, "text": "Schema is a logical description of the entire database. It includes the name and description of records of all record types including all associated data-items and aggregates. Much like a database, a data warehouse also requires to maintain a schema. A database uses relational model, while a data warehouse uses Star, Snowflake, and Fact Constellation schema. In this chapter, we will discuss the schemas used in a data warehouse." }, { "code": null, "e": 2488, "s": 2410, "text": "Each dimension in a star schema is represented with only one-dimension table." }, { "code": null, "e": 2566, "s": 2488, "text": "Each dimension in a star schema is represented with only one-dimension table." }, { "code": null, "e": 2619, "s": 2566, "text": "This dimension table contains the set of attributes." }, { "code": null, "e": 2672, "s": 2619, "text": "This dimension table contains the set of attributes." }, { "code": null, "e": 2806, "s": 2672, "text": "The following diagram shows the sales data of a company with respect to the four dimensions, namely time, item, branch, and location." }, { "code": null, "e": 2940, "s": 2806, "text": "The following diagram shows the sales data of a company with respect to the four dimensions, namely time, item, branch, and location." }, { "code": null, "e": 3026, "s": 2940, "text": "There is a fact table at the center. It contains the keys to each of four dimensions." }, { "code": null, "e": 3112, "s": 3026, "text": "There is a fact table at the center. It contains the keys to each of four dimensions." }, { "code": null, "e": 3193, "s": 3112, "text": "The fact table also contains the attributes, namely dollars sold and units sold." }, { "code": null, "e": 3274, "s": 3193, "text": "The fact table also contains the attributes, namely dollars sold and units sold." }, { "code": null, "e": 3748, "s": 3274, "text": "Note − Each dimension has only one dimension table and each table holds a set of attributes. For example, the location dimension table contains the attribute set {location_key, street, city, province_or_state,country}. This constraint may cause data redundancy. For example, \"Vancouver\" and \"Victoria\" both the cities are in the Canadian province of British Columbia. The entries for such cities may cause data redundancy along the attributes province_or_state and country." }, { "code": null, "e": 3810, "s": 3748, "text": "Some dimension tables in the Snowflake schema are normalized." }, { "code": null, "e": 3872, "s": 3810, "text": "Some dimension tables in the Snowflake schema are normalized." }, { "code": null, "e": 3933, "s": 3872, "text": "The normalization splits up the data into additional tables." }, { "code": null, "e": 3994, "s": 3933, "text": "The normalization splits up the data into additional tables." }, { "code": null, "e": 4209, "s": 3994, "text": "Unlike Star schema, the dimensions table in a snowflake schema are normalized. For example, the item dimension table in star schema is normalized and split into two dimension tables, namely item and supplier table." }, { "code": null, "e": 4424, "s": 4209, "text": "Unlike Star schema, the dimensions table in a snowflake schema are normalized. For example, the item dimension table in star schema is normalized and split into two dimension tables, namely item and supplier table." }, { "code": null, "e": 4529, "s": 4424, "text": "Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key." }, { "code": null, "e": 4634, "s": 4529, "text": "Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key." }, { "code": null, "e": 4779, "s": 4634, "text": "The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type." }, { "code": null, "e": 4924, "s": 4779, "text": "The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type." }, { "code": null, "e": 5074, "s": 4924, "text": "Note − Due to normalization in the Snowflake schema, the redundancy is reduced and therefore, it becomes easy to maintain and the save storage space." }, { "code": null, "e": 5156, "s": 5074, "text": "A fact constellation has multiple fact tables. It is also known as galaxy schema." }, { "code": null, "e": 5238, "s": 5156, "text": "A fact constellation has multiple fact tables. It is also known as galaxy schema." }, { "code": null, "e": 5310, "s": 5238, "text": "The following diagram shows two fact tables, namely sales and shipping." }, { "code": null, "e": 5382, "s": 5310, "text": "The following diagram shows two fact tables, namely sales and shipping." }, { "code": null, "e": 5439, "s": 5382, "text": "The sales fact table is same as that in the star schema." }, { "code": null, "e": 5496, "s": 5439, "text": "The sales fact table is same as that in the star schema." }, { "code": null, "e": 5613, "s": 5496, "text": "The shipping fact table has the five dimensions, namely item_key, time_key, shipper_key, from_location, to_location." }, { "code": null, "e": 5730, "s": 5613, "text": "The shipping fact table has the five dimensions, namely item_key, time_key, shipper_key, from_location, to_location." }, { "code": null, "e": 5818, "s": 5730, "text": "The shipping fact table also contains two measures, namely dollars sold and units sold." }, { "code": null, "e": 5906, "s": 5818, "text": "The shipping fact table also contains two measures, namely dollars sold and units sold." }, { "code": null, "e": 6082, "s": 5906, "text": "It is also possible to share dimension tables between fact tables. For example, time, item, and location dimension tables are shared between the sales and shipping fact table." }, { "code": null, "e": 6258, "s": 6082, "text": "It is also possible to share dimension tables between fact tables. For example, time, item, and location dimension tables are shared between the sales and shipping fact table." }, { "code": null, "e": 6457, "s": 6258, "text": "Multidimensional schema is defined using Data Mining Query Language (DMQL). The two primitives, cube definition and dimension definition, can be used for defining the data warehouses and data marts." }, { "code": null, "e": 6525, "s": 6457, "text": "define cube < cube_name > [ < dimension-list > }: < measure_list >\n" }, { "code": null, "e": 6601, "s": 6525, "text": "define dimension < dimension_name > as ( < attribute_or_dimension_list > )\n" }, { "code": null, "e": 6708, "s": 6601, "text": "The star schema that we have discussed can be defined using Data Mining Query Language (DMQL) as follows −" }, { "code": null, "e": 7171, "s": 6708, "text": "define cube sales star [time, item, branch, location]: \n \t \ndollars sold = sum(sales in dollars), units sold = count(*) \t \n\ndefine dimension time as (time key, day, day of week, month, quarter, year)\ndefine dimension item as (item key, item name, brand, type, supplier type) \t\ndefine dimension branch as (branch key, branch name, branch type) \t\ndefine dimension location as (location key, street, city, province or state, country)\n" }, { "code": null, "e": 7227, "s": 7171, "text": "Snowflake schema can be defined using DMQL as follows −" }, { "code": null, "e": 7695, "s": 7227, "text": "define cube sales snowflake [time, item, branch, location]:\n\ndollars sold = sum(sales in dollars), units sold = count(*)\n\ndefine dimension time as (time key, day, day of week, month, quarter, year)\ndefine dimension item as (item key, item name, brand, type, supplier (supplier key, supplier type))\ndefine dimension branch as (branch key, branch name, branch type)\ndefine dimension location as (location key, street, city (city key, city, province or state, country))\n" }, { "code": null, "e": 7760, "s": 7695, "text": "Fact constellation schema can be defined using DMQL as follows −" }, { "code": null, "e": 8617, "s": 7760, "text": "define cube sales [time, item, branch, location]:\n\ndollars sold = sum(sales in dollars), units sold = count(*)\n\ndefine dimension time as (time key, day, day of week, month, quarter, year)\ndefine dimension item as (item key, item name, brand, type, supplier type)\ndefine dimension branch as (branch key, branch name, branch type)\ndefine dimension location as (location key, street, city, province or state,country)\ndefine cube shipping [time, item, shipper, from location, to location]:\n\ndollars cost = sum(cost in dollars), units shipped = count(*)\n\ndefine dimension time as time in cube sales\ndefine dimension item as item in cube sales\ndefine dimension shipper as (shipper key, shipper name, location as location in cube sales, shipper type)\ndefine dimension from location as location in cube sales\ndefine dimension to location as location in cube sales\n" }, { "code": null, "e": 8624, "s": 8617, "text": " Print" }, { "code": null, "e": 8635, "s": 8624, "text": " Add Notes" } ]
Publishing Machine Learning API with Python Flask | by Andrej Baranovskij | Towards Data Science
Flask is fun and easy to setup, as it says on Flask website. And that's true. This microframework for Python offers a powerful way of annotating Python function with REST endpoint. I’m using Flask to publish ML model API to be accessible by the 3rd party business applications. This example is based on XGBoost. For better code maintenance, I would recommend using a separate Jupyter notebook where ML model API will be published. Import Flask module along with Flask CORS: from flask import Flask, jsonify, requestfrom flask_cors import CORS, cross_originimport pickleimport pandas as pd Model is trained on Pima Indians Diabetes Database. CSV data can be downloaded from here. To construct Pandas data frame variable as input for model predict function, we need to define an array of dataset columns: # Get headers for payloadheaders = ['times_pregnant', 'glucose', 'blood_pressure', 'skin_fold_thick', 'serum_insuling', 'mass_index', 'diabetes_pedigree', 'age'] Previously trained and saved model is loaded using Pickle: # Use pickle to load in the pre-trained modelwith open(f'diabetes-model.pkl', 'rb') as f: model = pickle.load(f) It is always a good practice to do a test run and check if the model performs well. Construct data frame with an array of column names and an array of data (using new data, the one which is not present in train or test datasets). Calling two functions — model.predict and model.predict_proba. Often I prefer model.predict_proba, it returns probability which describes how likely will be 0/1, this helps to interpret the result based on a certain range (0.25 to 0.75 for example). Pandas data frame is constructed with sample payload and then the model prediction is executed: # Test model with data frameinput_variables = pd.DataFrame([[1, 106, 70, 28, 135, 34.2, 0.142, 22]], columns=headers, dtype=float, index=['input'])# Get the model's predictionprediction = model.predict(input_variables)print("Prediction: ", prediction)prediction_proba = model.predict_proba(input_variables)print("Probabilities: ", prediction_proba) Flask API. Make sure you enable CORS, otherwise API call will not work from another host. Write annotation before the function you want to expose through REST API. Provide an endpoint name and supported REST methods (POST in this example). Payload data is retrieved from the request, Pandas data frame is constructed and model predict_proba function is executed: app = Flask(__name__)CORS(app)@app.route("/katana-ml/api/v1.0/diabetes", methods=['POST'])def predict(): payload = request.json['data'] values = [float(i) for i in payload.split(',')] input_variables = pd.DataFrame([values], columns=headers, dtype=float, index=['input']) # Get the model's prediction prediction_proba = model.predict_proba(input_variables) prediction = (prediction_proba[0])[1] ret = '{"prediction":' + str(float(prediction)) + '}' return ret# running REST interface, port=5000 for direct testif __name__ == "__main__": app.run(debug=False, host='0.0.0.0', port=5000) Response JSON string is constructed and returned as a function result. I’m running Flask in Docker container, that's why using 0.0.0.0 as the host on which it runs. Port 5000 is mapped as external port and this allows calls from the outside. While it works to start Flask interface directly in Jupyter notebook, I would recommend to convert it to Python script and run from command line as a service. Use Jupyter nbconvert command to convert to Python script: jupyter nbconvert — to python diabetes_redsamurai_endpoint_db.ipynb Python script with Flask endpoint can be started as the background process with PM2 process manager. This allows to run endpoint as a service and start other processes on different ports. PM2 start command: pm2 start diabetes_redsamurai_endpoint_db.py pm2 monit helps to display info about running processes: ML model classification REST API call from Postman through endpoint served by Flask: More info: GitHub repo with source code Previous post about XGBoost model training
[ { "code": null, "e": 450, "s": 172, "text": "Flask is fun and easy to setup, as it says on Flask website. And that's true. This microframework for Python offers a powerful way of annotating Python function with REST endpoint. I’m using Flask to publish ML model API to be accessible by the 3rd party business applications." }, { "code": null, "e": 484, "s": 450, "text": "This example is based on XGBoost." }, { "code": null, "e": 646, "s": 484, "text": "For better code maintenance, I would recommend using a separate Jupyter notebook where ML model API will be published. Import Flask module along with Flask CORS:" }, { "code": null, "e": 761, "s": 646, "text": "from flask import Flask, jsonify, requestfrom flask_cors import CORS, cross_originimport pickleimport pandas as pd" }, { "code": null, "e": 975, "s": 761, "text": "Model is trained on Pima Indians Diabetes Database. CSV data can be downloaded from here. To construct Pandas data frame variable as input for model predict function, we need to define an array of dataset columns:" }, { "code": null, "e": 1137, "s": 975, "text": "# Get headers for payloadheaders = ['times_pregnant', 'glucose', 'blood_pressure', 'skin_fold_thick', 'serum_insuling', 'mass_index', 'diabetes_pedigree', 'age']" }, { "code": null, "e": 1196, "s": 1137, "text": "Previously trained and saved model is loaded using Pickle:" }, { "code": null, "e": 1312, "s": 1196, "text": "# Use pickle to load in the pre-trained modelwith open(f'diabetes-model.pkl', 'rb') as f: model = pickle.load(f)" }, { "code": null, "e": 1888, "s": 1312, "text": "It is always a good practice to do a test run and check if the model performs well. Construct data frame with an array of column names and an array of data (using new data, the one which is not present in train or test datasets). Calling two functions — model.predict and model.predict_proba. Often I prefer model.predict_proba, it returns probability which describes how likely will be 0/1, this helps to interpret the result based on a certain range (0.25 to 0.75 for example). Pandas data frame is constructed with sample payload and then the model prediction is executed:" }, { "code": null, "e": 2331, "s": 1888, "text": "# Test model with data frameinput_variables = pd.DataFrame([[1, 106, 70, 28, 135, 34.2, 0.142, 22]], columns=headers, dtype=float, index=['input'])# Get the model's predictionprediction = model.predict(input_variables)print(\"Prediction: \", prediction)prediction_proba = model.predict_proba(input_variables)print(\"Probabilities: \", prediction_proba)" }, { "code": null, "e": 2694, "s": 2331, "text": "Flask API. Make sure you enable CORS, otherwise API call will not work from another host. Write annotation before the function you want to expose through REST API. Provide an endpoint name and supported REST methods (POST in this example). Payload data is retrieved from the request, Pandas data frame is constructed and model predict_proba function is executed:" }, { "code": null, "e": 3412, "s": 2694, "text": "app = Flask(__name__)CORS(app)@app.route(\"/katana-ml/api/v1.0/diabetes\", methods=['POST'])def predict(): payload = request.json['data'] values = [float(i) for i in payload.split(',')] input_variables = pd.DataFrame([values], columns=headers, dtype=float, index=['input']) # Get the model's prediction prediction_proba = model.predict_proba(input_variables) prediction = (prediction_proba[0])[1] ret = '{\"prediction\":' + str(float(prediction)) + '}' return ret# running REST interface, port=5000 for direct testif __name__ == \"__main__\": app.run(debug=False, host='0.0.0.0', port=5000)" }, { "code": null, "e": 3654, "s": 3412, "text": "Response JSON string is constructed and returned as a function result. I’m running Flask in Docker container, that's why using 0.0.0.0 as the host on which it runs. Port 5000 is mapped as external port and this allows calls from the outside." }, { "code": null, "e": 3872, "s": 3654, "text": "While it works to start Flask interface directly in Jupyter notebook, I would recommend to convert it to Python script and run from command line as a service. Use Jupyter nbconvert command to convert to Python script:" }, { "code": null, "e": 3940, "s": 3872, "text": "jupyter nbconvert — to python diabetes_redsamurai_endpoint_db.ipynb" }, { "code": null, "e": 4147, "s": 3940, "text": "Python script with Flask endpoint can be started as the background process with PM2 process manager. This allows to run endpoint as a service and start other processes on different ports. PM2 start command:" }, { "code": null, "e": 4192, "s": 4147, "text": "pm2 start diabetes_redsamurai_endpoint_db.py" }, { "code": null, "e": 4249, "s": 4192, "text": "pm2 monit helps to display info about running processes:" }, { "code": null, "e": 4334, "s": 4249, "text": "ML model classification REST API call from Postman through endpoint served by Flask:" }, { "code": null, "e": 4345, "s": 4334, "text": "More info:" }, { "code": null, "e": 4374, "s": 4345, "text": "GitHub repo with source code" } ]
What is ViewData in ASP .Net MVC C#?
ViewData is a dictionary of objects that are stored and retrieved using strings as keys. It is used to transfer data from Controller to View. Since ViewData is a dictionary, it contains key-value pairs where each key must be a string. ViewData only transfers data from controller to view, not vice-versa. It is valid only during the current request. Storing data in ViewData − ViewData["countries"] = countriesList; Retrieving data from ViewData − string country = ViewData["MyCountry"].ToString(); ViewData does not provide compile time error checking. For example, if we mis-spell the key names we wouldn't get any compile time error. We will get to know about the error only at runtime. using System.Collections.Generic; using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public ViewResult Index(){ ViewData["Countries"] = new List<string>{ "India", "Malaysia", "Dubai", "USA", "UK" }; return View(); } } } @{ ViewBag.Title = "Countries List"; } <h2>Countries List</h2> <ul> @foreach(string country in (List<string>)ViewData["Countries"]){ <li>@country</li> } </ul>
[ { "code": null, "e": 1412, "s": 1062, "text": "ViewData is a dictionary of objects that are stored and retrieved using strings as keys.\nIt is used to transfer data from Controller to View. Since ViewData is a dictionary, it\ncontains key-value pairs where each key must be a string. ViewData only transfers\ndata from controller to view, not vice-versa. It is valid only during the current request." }, { "code": null, "e": 1439, "s": 1412, "text": "Storing data in ViewData −" }, { "code": null, "e": 1478, "s": 1439, "text": "ViewData[\"countries\"] = countriesList;" }, { "code": null, "e": 1510, "s": 1478, "text": "Retrieving data from ViewData −" }, { "code": null, "e": 1561, "s": 1510, "text": "string country = ViewData[\"MyCountry\"].ToString();" }, { "code": null, "e": 1752, "s": 1561, "text": "ViewData does not provide compile time error checking. For example, if we mis-spell\nthe key names we wouldn't get any compile time error. We will get to know about the\nerror only at runtime." }, { "code": null, "e": 2132, "s": 1752, "text": "using System.Collections.Generic;\nusing System.Web.Mvc;\nnamespace DemoMvcApplication.Controllers{\n public class HomeController : Controller{\n public ViewResult Index(){\n ViewData[\"Countries\"] = new List<string>{\n \"India\",\n \"Malaysia\",\n \"Dubai\",\n \"USA\",\n \"UK\"\n };\n return View();\n }\n }\n}" }, { "code": null, "e": 2297, "s": 2132, "text": "@{\n ViewBag.Title = \"Countries List\";\n}\n<h2>Countries List</h2>\n<ul>\n@foreach(string country in (List<string>)ViewData[\"Countries\"]){\n <li>@country</li>\n}\n</ul>" } ]
PHP - Ajax Auto Complete Search
The Auto complete search box provides the suggestions when you enter data into the field. Here we are using xml to call auto complete suggestions. The below example demonstrate, How to use auto complete text box using with php. Index page should be as follows − <html> <head> <style> div { width:240px; color:green; } </style> <script> function showResult(str) { if (str.length == 0) { document.getElementById("livesearch").innerHTML = ""; document.getElementById("livesearch").style.border = "0px"; return; } if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("livesearch").innerHTML = xmlhttp.responseText; document.getElementById("livesearch").style.border = "1px solid #A5ACB2"; } } xmlhttp.open("GET","livesearch.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <h2>Enter Course Name</h2> <input type = "text" size = "30" onkeyup = "showResult(this.value)"> <div id = "livesearch"></div> <a href = "http://www.tutorialspoint.com">More Details </a> </form> </body> </html> It is used to call the data from xml file and it will send the result to web browsers. <?php $xmlDoc = new DOMDocument(); $xmlDoc->load("autocomplete.xml"); $x = $xmlDoc->getElementsByTagName('link'); $q = $_GET["q"]; if (strlen($q)>0) { $hint = ""; for($i = 0; $i>($x->length); $i++) { $y = $x->item($i)->getElementsByTagName('title'); $z = $x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType == 1) { if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint == "") { $hint = "<a href = '" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; }else { $hint = $hint . "<br/><a href = '" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } } } } } if ($hint == "") { $response = "Please enter a valid name"; }else { $response = $hint; } echo $response; ?> It contained auto complete data and accessed by livesearch.php based on tittle field and Url filed <pages> <link> <title>android</title> <url>http://www.tutorialspoint.com/android/index.htm</url> </link> <link> <title>Java</title> <url>http://www.tutorialspoint.com/java/index.htm</url> </link> <link> <title>CSS </title> <url>http://www.tutorialspoint.com/css/index.htm</url> </link> <link> <title>angularjs</title> <url>http://www.tutorialspoint.com/angularjs/index.htm </url> </link> <link> <title>hadoop</title> <url>http://www.tutorialspoint.com/hadoop/index.htm </url> </link> <link> <title>swift</title> <url>http://www.tutorialspoint.com/swift/index.htm </url> </link> <link> <title>ruby</title> <url>http://www.tutorialspoint.com/ruby/index.htm </url> </link> <link> <title>nodejs</title> <url>http://www.tutorialspoint.com/nodejs/index.htm </url> </link> </pages> It will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2985, "s": 2757, "text": "The Auto complete search box provides the suggestions when you enter data into the field. Here we are using xml to call auto complete suggestions. The below example demonstrate, How to use auto complete text box using with php." }, { "code": null, "e": 3019, "s": 2985, "text": "Index page should be as follows −" }, { "code": null, "e": 4422, "s": 3019, "text": "<html>\n <head>\n \n <style>\n div {\n width:240px;\n color:green;\n }\n </style>\n \n <script>\n function showResult(str) {\n\t\t\t\n if (str.length == 0) {\n document.getElementById(\"livesearch\").innerHTML = \"\";\n document.getElementById(\"livesearch\").style.border = \"0px\";\n return;\n }\n \n if (window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n }else {\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n \n xmlhttp.onreadystatechange = function() {\n\t\t\t\t\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n document.getElementById(\"livesearch\").innerHTML = xmlhttp.responseText;\n document.getElementById(\"livesearch\").style.border = \"1px solid #A5ACB2\";\n }\n }\n \n xmlhttp.open(\"GET\",\"livesearch.php?q=\"+str,true);\n xmlhttp.send();\n }\n </script>\n \n </head>\n <body>\n \n <form>\n <h2>Enter Course Name</h2>\n <input type = \"text\" size = \"30\" onkeyup = \"showResult(this.value)\">\n <div id = \"livesearch\"></div>\n <a href = \"http://www.tutorialspoint.com\">More Details </a>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 4509, "s": 4422, "text": "It is used to call the data from xml file and it will send the result to web browsers." }, { "code": null, "e": 5642, "s": 4509, "text": "<?php\n $xmlDoc = new DOMDocument();\n $xmlDoc->load(\"autocomplete.xml\");\n $x = $xmlDoc->getElementsByTagName('link');\n $q = $_GET[\"q\"];\n \n if (strlen($q)>0) {\n $hint = \"\";\n \n for($i = 0; $i>($x->length); $i++) {\n $y = $x->item($i)->getElementsByTagName('title');\n $z = $x->item($i)->getElementsByTagName('url');\n \n if ($y->item(0)->nodeType == 1) {\n if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {\n\t\t\t\t\n if ($hint == \"\") {\n $hint = \"<a href = '\" . $z->item(0)->childNodes->item(0)->nodeValue . \"' target='_blank'>\" . \n $y->item(0)->childNodes->item(0)->nodeValue . \"</a>\";\n }else {\n $hint = $hint . \"<br/><a href = '\" . \n $z->item(0)->childNodes->item(0)->nodeValue . \"' target='_blank'>\" . \n $y->item(0)->childNodes->item(0)->nodeValue . \"</a>\";\n }\n }\n }\n }\n }\n\t\n if ($hint == \"\") {\n $response = \"Please enter a valid name\";\n }else {\n $response = $hint;\n }\n echo $response;\n?>" }, { "code": null, "e": 5741, "s": 5642, "text": "It contained auto complete data and accessed by livesearch.php based on tittle field and Url filed" }, { "code": null, "e": 6669, "s": 5741, "text": "<pages>\n\n <link>\n <title>android</title>\n <url>http://www.tutorialspoint.com/android/index.htm</url>\n </link>\n\n <link>\n <title>Java</title>\n <url>http://www.tutorialspoint.com/java/index.htm</url>\n </link>\n\n <link>\n <title>CSS </title>\n <url>http://www.tutorialspoint.com/css/index.htm</url>\n </link>\n\n <link>\n <title>angularjs</title>\n <url>http://www.tutorialspoint.com/angularjs/index.htm </url>\n </link>\n\n <link>\n <title>hadoop</title>\n <url>http://www.tutorialspoint.com/hadoop/index.htm </url>\n </link>\n\n <link>\n <title>swift</title>\n <url>http://www.tutorialspoint.com/swift/index.htm </url>\n </link>\n\n <link>\n <title>ruby</title>\n <url>http://www.tutorialspoint.com/ruby/index.htm </url>\n </link>\n\n <link>\n <title>nodejs</title>\n <url>http://www.tutorialspoint.com/nodejs/index.htm </url>\n </link>\n\n</pages>" }, { "code": null, "e": 6708, "s": 6669, "text": "It will produce the following result −" }, { "code": null, "e": 6741, "s": 6708, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 6757, "s": 6741, "text": " Malhar Lathkar" }, { "code": null, "e": 6790, "s": 6757, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6801, "s": 6790, "text": " Syed Raza" }, { "code": null, "e": 6836, "s": 6801, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6853, "s": 6836, "text": " Frahaan Hussain" }, { "code": null, "e": 6886, "s": 6853, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6901, "s": 6886, "text": " Nivedita Jain" }, { "code": null, "e": 6936, "s": 6901, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 6948, "s": 6936, "text": " Azaz Patel" }, { "code": null, "e": 6983, "s": 6948, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7011, "s": 6983, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 7018, "s": 7011, "text": " Print" }, { "code": null, "e": 7029, "s": 7018, "text": " Add Notes" } ]
Kernel Functions in Non-linear Classification | by Edwin Tai | Towards Data Science
Once the data points are non-linear separable in their original feature space, the linear classifier may be failed to determine where the decision boundary is. However, mapping the original feature space (x ∈ Rd) into the higher dimensional feature space (φ(x) ∈ Re , e>d) can help to resurrect the linear classifier to do the job correctly. Figure 1. illustrates the concepts of classifying data points through feature mapping. Originally, the data points with the feature vectors x = [x1, x2] in the 2-D space have the concentrically circular distribution (not a strictly mathematical description here). It is impossible to use a linear classifier to distinguish the decision boundary. Nonetheless, by incorporating a certain mapping function φ(x), the feature vectors can be transformed into 3-D feature space. The new data points with 3-D feature vectors φ(x) = [x1, x2,(x12+x22)] can now be using the linear classifier to determine the decision boundary hyperplane. This is the power of feature mapping that can allow us to deal with the more complex data distribution pattern with more expressive ability. However, the drawbacks of using φ(x) directly are that It is sometimes hard to explicitly construct a φ(x) directly.Increase computational power quickly with the increased feature dimensions. It is sometimes hard to explicitly construct a φ(x) directly. Increase computational power quickly with the increased feature dimensions. But the kernel functions can provide an efficient way to solve this. The idea of kernel functions is to take the inner products between two feature vectors, and evaluate inner products is not computationally costly. We can then exploit only the result of the inner products in our algorithms. For example, if we want to have the φ(x) as follows, The kernel function is take the inner products between two feature vectors as follows, As a result, the form of the kernel functions will be easier for us to construct than directly use the mapping functions in the higher feature dimensions. There are several kernel composition rules that can be used to construct more complex kernel functions. The kernel functions can even empower the feature vectors to be infinite dimensional. One of the common kernel functions is the radial basis kernel. The definition is as follows. Because the exponential can be expanded to the infinite power series, the radial basis kernel gives much more expressiveness to the feature mapping. The following is the proof of the radial basis kernel that is a kernel function. Recalling the perceptron algorithm here, the perceptron algorithm updates θ = θ + y( j ) x( j ) once a data point is misclassified. In the other word, the θ can be expressed alternatively as follows. where αj is the number of mistakes the perceptron made on the j-th data point. If it is in the mapping feature space, the θ can be expressed as follows. Utilizing the kernel form of the θ, the pseudocode of the kernel perceptron algorithm can be described as follows. # Kernel Perceptron Algorithm# initialize αj# totally m data pointsfor i = 1 .. m do αi = 0# totally T epoches to iteratefor t = 1 .. T do # totally m data points for i = 1 .. m do # misclassify data points if y(i)∑j(αjy(j)K(x(j),x(i))) ≦ 0 then αi = αi + 1θφ(x(i))= ∑j(αjy(j)K(x(j),x(i))) Figure 2. visualizes the updating of the decision boundary by the radial basis kernel perceptron algorithm. Note that the decision boundary drawn by the radial basis kernel perceptron algorithm can converge in 2 epoches with this kind of data distribution. The γ for the radial basis kernel uses 0.3 here. The sample code written in Jupyter notebook for the perceptron algorithms can be found here. You can play with the data and the hyperparameters yourself to see how the kernel perceptron algorithm performs.
[ { "code": null, "e": 514, "s": 172, "text": "Once the data points are non-linear separable in their original feature space, the linear classifier may be failed to determine where the decision boundary is. However, mapping the original feature space (x ∈ Rd) into the higher dimensional feature space (φ(x) ∈ Re , e>d) can help to resurrect the linear classifier to do the job correctly." }, { "code": null, "e": 860, "s": 514, "text": "Figure 1. illustrates the concepts of classifying data points through feature mapping. Originally, the data points with the feature vectors x = [x1, x2] in the 2-D space have the concentrically circular distribution (not a strictly mathematical description here). It is impossible to use a linear classifier to distinguish the decision boundary." }, { "code": null, "e": 1284, "s": 860, "text": "Nonetheless, by incorporating a certain mapping function φ(x), the feature vectors can be transformed into 3-D feature space. The new data points with 3-D feature vectors φ(x) = [x1, x2,(x12+x22)] can now be using the linear classifier to determine the decision boundary hyperplane. This is the power of feature mapping that can allow us to deal with the more complex data distribution pattern with more expressive ability." }, { "code": null, "e": 1339, "s": 1284, "text": "However, the drawbacks of using φ(x) directly are that" }, { "code": null, "e": 1476, "s": 1339, "text": "It is sometimes hard to explicitly construct a φ(x) directly.Increase computational power quickly with the increased feature dimensions." }, { "code": null, "e": 1538, "s": 1476, "text": "It is sometimes hard to explicitly construct a φ(x) directly." }, { "code": null, "e": 1614, "s": 1538, "text": "Increase computational power quickly with the increased feature dimensions." }, { "code": null, "e": 1683, "s": 1614, "text": "But the kernel functions can provide an efficient way to solve this." }, { "code": null, "e": 1960, "s": 1683, "text": "The idea of kernel functions is to take the inner products between two feature vectors, and evaluate inner products is not computationally costly. We can then exploit only the result of the inner products in our algorithms. For example, if we want to have the φ(x) as follows," }, { "code": null, "e": 2047, "s": 1960, "text": "The kernel function is take the inner products between two feature vectors as follows," }, { "code": null, "e": 2202, "s": 2047, "text": "As a result, the form of the kernel functions will be easier for us to construct than directly use the mapping functions in the higher feature dimensions." }, { "code": null, "e": 2306, "s": 2202, "text": "There are several kernel composition rules that can be used to construct more complex kernel functions." }, { "code": null, "e": 2485, "s": 2306, "text": "The kernel functions can even empower the feature vectors to be infinite dimensional. One of the common kernel functions is the radial basis kernel. The definition is as follows." }, { "code": null, "e": 2715, "s": 2485, "text": "Because the exponential can be expanded to the infinite power series, the radial basis kernel gives much more expressiveness to the feature mapping. The following is the proof of the radial basis kernel that is a kernel function." }, { "code": null, "e": 2915, "s": 2715, "text": "Recalling the perceptron algorithm here, the perceptron algorithm updates θ = θ + y( j ) x( j ) once a data point is misclassified. In the other word, the θ can be expressed alternatively as follows." }, { "code": null, "e": 3068, "s": 2915, "text": "where αj is the number of mistakes the perceptron made on the j-th data point. If it is in the mapping feature space, the θ can be expressed as follows." }, { "code": null, "e": 3183, "s": 3068, "text": "Utilizing the kernel form of the θ, the pseudocode of the kernel perceptron algorithm can be described as follows." }, { "code": null, "e": 3561, "s": 3183, "text": "# Kernel Perceptron Algorithm# initialize αj# totally m data pointsfor i = 1 .. m do αi = 0# totally T epoches to iteratefor t = 1 .. T do # totally m data points for i = 1 .. m do # misclassify data points if y(i)∑j(αjy(j)K(x(j),x(i))) ≦ 0 then αi = αi + 1θφ(x(i))= ∑j(αjy(j)K(x(j),x(i)))" }, { "code": null, "e": 3867, "s": 3561, "text": "Figure 2. visualizes the updating of the decision boundary by the radial basis kernel perceptron algorithm. Note that the decision boundary drawn by the radial basis kernel perceptron algorithm can converge in 2 epoches with this kind of data distribution. The γ for the radial basis kernel uses 0.3 here." } ]
How to vertically align text inside a flexbox using CSS? - GeeksforGeeks
12 Apr, 2019 CSS flexbox: The flex property in CSS is the combination of flex-grow, flex-shrink, and flex-basis property. It is used to set the length of flexible items. The flex property is much responsive and mobile friendly. It is easy to positioning child elements and the main container. The margin doesn’t collapse with the content margins. Order of any element can be easily changed without editing the HTML section. The flexbox was added to the CSS standards a few years ago to manage space distribution and element alignment. Basically it is one-dimensional layout syntax. Vertical align to center: The flexbox property is used to set the content to vertical align. The text content can be aligned vertically by setting the following display properties: align-items justify-content flex-direction align-items and justify-content are the important properties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items property. Example 1: This example set the text content vertically align to center. <!DOCTYPE html><html> <head> <title> Vertically align text content </title> <!-- CSS property to vertical align text content using flex-box --> <style> .GFG { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 400px; background-color: green; align-items: center; } </style></head> <body> <div class="GFG"> <h1>GeeksforGeeks</h1> <h2>Vertically align text using Flexbox</h2> </div></body> </html> Output: Example 2: This example illustrates how to set left align text vertically in a flexbox using CSS. <!DOCTYPE html><html> <head> <title> Vertically align text content </title> <!-- CSS property to vertical align text content using flex-box --> <style> .GFG { display: flex; align-items: left; justify-content: left; flex-direction: column; text-align: left; margin: 13% 0; min-height: 300px; background-color:green; align-items: left; } </style></head> <body> <div class="GFG"> <h1>GeeksforGeeks</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" style="display: inline;"> </div></body> </html> Output: CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25088, "s": 25060, "text": "\n12 Apr, 2019" }, { "code": null, "e": 25657, "s": 25088, "text": "CSS flexbox: The flex property in CSS is the combination of flex-grow, flex-shrink, and flex-basis property. It is used to set the length of flexible items. The flex property is much responsive and mobile friendly. It is easy to positioning child elements and the main container. The margin doesn’t collapse with the content margins. Order of any element can be easily changed without editing the HTML section. The flexbox was added to the CSS standards a few years ago to manage space distribution and element alignment. Basically it is one-dimensional layout syntax." }, { "code": null, "e": 25838, "s": 25657, "text": "Vertical align to center: The flexbox property is used to set the content to vertical align. The text content can be aligned vertically by setting the following display properties:" }, { "code": null, "e": 25850, "s": 25838, "text": "align-items" }, { "code": null, "e": 25866, "s": 25850, "text": "justify-content" }, { "code": null, "e": 25881, "s": 25866, "text": "flex-direction" }, { "code": null, "e": 26111, "s": 25881, "text": "align-items and justify-content are the important properties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items property." }, { "code": null, "e": 26184, "s": 26111, "text": "Example 1: This example set the text content vertically align to center." }, { "code": "<!DOCTYPE html><html> <head> <title> Vertically align text content </title> <!-- CSS property to vertical align text content using flex-box --> <style> .GFG { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 400px; background-color: green; align-items: center; } </style></head> <body> <div class=\"GFG\"> <h1>GeeksforGeeks</h1> <h2>Vertically align text using Flexbox</h2> </div></body> </html>", "e": 26830, "s": 26184, "text": null }, { "code": null, "e": 26838, "s": 26830, "text": "Output:" }, { "code": null, "e": 26936, "s": 26838, "text": "Example 2: This example illustrates how to set left align text vertically in a flexbox using CSS." }, { "code": "<!DOCTYPE html><html> <head> <title> Vertically align text content </title> <!-- CSS property to vertical align text content using flex-box --> <style> .GFG { display: flex; align-items: left; justify-content: left; flex-direction: column; text-align: left; margin: 13% 0; min-height: 300px; background-color:green; align-items: left; } </style></head> <body> <div class=\"GFG\"> <h1>GeeksforGeeks</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\" style=\"display: inline;\"> </div></body> </html> ", "e": 27672, "s": 26936, "text": null }, { "code": null, "e": 27680, "s": 27672, "text": "Output:" }, { "code": null, "e": 27689, "s": 27680, "text": "CSS-Misc" }, { "code": null, "e": 27696, "s": 27689, "text": "Picked" }, { "code": null, "e": 27700, "s": 27696, "text": "CSS" }, { "code": null, "e": 27717, "s": 27700, "text": "Web Technologies" }, { "code": null, "e": 27815, "s": 27717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27824, "s": 27815, "text": "Comments" }, { "code": null, "e": 27837, "s": 27824, "text": "Old Comments" }, { "code": null, "e": 27895, "s": 27837, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27932, "s": 27895, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27969, "s": 27932, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28033, "s": 27969, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28074, "s": 28033, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28116, "s": 28074, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28149, "s": 28116, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28192, "s": 28149, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28237, "s": 28192, "text": "Convert a string to an integer in JavaScript" } ]
What are the differences between tight coupling and loose coupling in Java?
Tight coupling means classes and objects are dependent on one another. In general, tight coupling is usually not good because it reduces the flexibility and re-usability of the code while Loose coupling means reducing the dependencies of a class that uses the different class directly. The tightly coupled object is an object that needs to know about other objects and is usually highly dependent on each other's interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects. In the small applications, we can easily identify the changes and there is less chance to miss anything. But in large applications, these inter-dependencies are not always known by every programmer and there is a chance of overlooking changes. Live Demo class A { public int a = 0; public int getA() { System.out.println("getA() method"); return a; } public void setA(int aa) { if(!(aa > 10)) a = aa; } } public class B { public static void main(String[] args) { A aObject = new A(); aObject.a = 100; // Not suppose to happen as defined by class A, this causes tight coupling. System.out.println("aObject.a value is: " + aObject.a); } } In the above example, the code that is defined by this kind of implementation uses tight coupling and is very bad since class B knows about the detail of class A, if class A changes the variable 'a' to private then class B breaks, also class A's implementation states that variable 'a' should not be more than 10 but as we can see there is no way to enforce such a rule as we can go directly to the variable and change its state to whatever value we decide. aObject.a value is: 100 Loose coupling is a design goal to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is a much more generic concept intended to increase the flexibility of the system, make it more maintainable and makes the entire framework more stable. Live Demo class A { private int a = 0; public int getA() { System.out.println("getA() method"); return a; } public void setA(int aa) { if(!(aa > 10)) a = aa; } } public class B { public static void main(String[] args) { A aObject = new A(); aObject.setA(100); // No way to set 'a' to such value as this method call will // fail due to its enforced rule. System.out.println("aObject value is: " + aObject.getA()); } } In the above example, the code that is defined by this kind of implementation uses loose coupling and is recommended since class B has to go through class A to get its state where rules are enforced. If class A is changed internally, class B will not break as it uses only class A as a way of communication. getA() method aObject value is: 0
[ { "code": null, "e": 1348, "s": 1062, "text": "Tight coupling means classes and objects are dependent on one another. In general, tight coupling is usually not good because it reduces the flexibility and re-usability of the code while Loose coupling means reducing the dependencies of a class that uses the different class directly." }, { "code": null, "e": 1487, "s": 1348, "text": "The tightly coupled object is an object that needs to know about other objects and is usually highly dependent on each other's interfaces." }, { "code": null, "e": 1593, "s": 1487, "text": "Changing one object in a tightly coupled application often requires changes to a number of other objects." }, { "code": null, "e": 1837, "s": 1593, "text": "In the small applications, we can easily identify the changes and there is less chance to miss anything. But in large applications, these inter-dependencies are not always known by every programmer and there is a chance of overlooking changes." }, { "code": null, "e": 1848, "s": 1837, "text": " Live Demo" }, { "code": null, "e": 2297, "s": 1848, "text": "class A {\n public int a = 0;\n public int getA() {\n System.out.println(\"getA() method\");\n return a;\n }\n public void setA(int aa) {\n if(!(aa > 10))\n a = aa;\n }\n}\npublic class B {\n public static void main(String[] args) {\n A aObject = new A();\n aObject.a = 100; // Not suppose to happen as defined by class A, this causes tight coupling.\n System.out.println(\"aObject.a value is: \" + aObject.a);\n }\n}" }, { "code": null, "e": 2755, "s": 2297, "text": "In the above example, the code that is defined by this kind of implementation uses tight coupling and is very bad since class B knows about the detail of class A, if class A changes the variable 'a' to private then class B breaks, also class A's implementation states that variable 'a' should not be more than 10 but as we can see there is no way to enforce such a rule as we can go directly to the variable and change its state to whatever value we decide." }, { "code": null, "e": 2779, "s": 2755, "text": "aObject.a value is: 100" }, { "code": null, "e": 2985, "s": 2779, "text": "Loose coupling is a design goal to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component." }, { "code": null, "e": 3153, "s": 2985, "text": "Loose coupling is a much more generic concept intended to increase the flexibility of the system, make it more maintainable and makes the entire framework more stable." }, { "code": null, "e": 3164, "s": 3153, "text": " Live Demo" }, { "code": null, "e": 3662, "s": 3164, "text": "class A {\n private int a = 0;\n public int getA() {\n System.out.println(\"getA() method\");\n return a;\n }\n public void setA(int aa) {\n if(!(aa > 10))\n a = aa;\n }\n}\npublic class B {\n public static void main(String[] args) {\n A aObject = new A();\n aObject.setA(100); // No way to set 'a' to such value as this method call will\n // fail due to its enforced rule.\n System.out.println(\"aObject value is: \" + aObject.getA());\n }\n}" }, { "code": null, "e": 3970, "s": 3662, "text": "In the above example, the code that is defined by this kind of implementation uses loose coupling and is recommended since class B has to go through class A to get its state where rules are enforced. If class A is changed internally, class B will not break as it uses only class A as a way of communication." }, { "code": null, "e": 4004, "s": 3970, "text": "getA() method\naObject value is: 0" } ]
C++ program to take integer and float as input and return their sum
Suppose we have two numbers a and b, a is integer and b is a float. We shall have to take them from standard input and display the sum. So, if the input is like a = 10 b = 56.23, then the output will be Sum: 66.23 To solve this, we will follow these steps − To display output into the standard output device we can use extraction operator (<<) To display output into the standard output device we can use extraction operator (<<) To take input from standard input we can use insertion operator (>>) To take input from standard input we can use insertion operator (>>) Let us see the following implementation to get better understanding − #include <iostream> using namespace std; int main(){ int a; float b; cout << "Enter numbers:" << endl; cin >> a >> b; cout << "Sum:" << a + b; } 10, 56.23 Enter numbers: Sum:10
[ { "code": null, "e": 1198, "s": 1062, "text": "Suppose we have two numbers a and b, a is integer and b is a float. We shall have to take them from standard input and display the sum." }, { "code": null, "e": 1276, "s": 1198, "text": "So, if the input is like a = 10 b = 56.23, then the output will be Sum: 66.23" }, { "code": null, "e": 1320, "s": 1276, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1406, "s": 1320, "text": "To display output into the standard output device we can use extraction operator (<<)" }, { "code": null, "e": 1492, "s": 1406, "text": "To display output into the standard output device we can use extraction operator (<<)" }, { "code": null, "e": 1561, "s": 1492, "text": "To take input from standard input we can use insertion operator (>>)" }, { "code": null, "e": 1630, "s": 1561, "text": "To take input from standard input we can use insertion operator (>>)" }, { "code": null, "e": 1700, "s": 1630, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1861, "s": 1700, "text": "#include <iostream>\nusing namespace std;\nint main(){\n int a;\n float b;\n cout << \"Enter numbers:\" << endl;\n cin >> a >> b;\n cout << \"Sum:\" << a + b;\n}\n" }, { "code": null, "e": 1871, "s": 1861, "text": "10, 56.23" }, { "code": null, "e": 1893, "s": 1871, "text": "Enter numbers:\nSum:10" } ]
Amazon Interview Experience for SDE Intern | On-Campus 2020 - GeeksforGeeks
14 Oct, 2020 Round 1: Round 1 was an online assessment that consisted of four parts: Code Debugging – 7 questions to be debugged in 20 minutes.Coding Test – 2 coding questions to be solved in 70 minutes.Workstyles assessment – 20minutesReasoning ability – 35 minutes Code Debugging – 7 questions to be debugged in 20 minutes. Coding Test – 2 coding questions to be solved in 70 minutes. Workstyles assessment – 20minutes Reasoning ability – 35 minutes Round 2: Shortlisted students from Round 1 went through round 2 which was a technical interview Round. The interview was held on Amazon Chime. The interviewer was very nice. After 2-3 minutes of introduction, he went straight to Coding questions. I was given a link to the code editor, and he explained to me the problems. The interview lasted approximately 60 minutes. Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities.Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters. Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities. Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters. Example: Input : {"abc", "dgf", "qsvu", "xzy"} Output : "abcdegfhijklmnopqrstvuwxzy" The first round was only about two coding problems to test your knowledge of data structures and algorithms. I was not able to solve the second problem. I couldn’t make it to the 2nd technical interview. Amazon Marketing On-Campus Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Zoho Interview | Set 1 (On-Campus)
[ { "code": null, "e": 25602, "s": 25574, "text": "\n14 Oct, 2020" }, { "code": null, "e": 25674, "s": 25602, "text": "Round 1: Round 1 was an online assessment that consisted of four parts:" }, { "code": null, "e": 25856, "s": 25674, "text": "Code Debugging – 7 questions to be debugged in 20 minutes.Coding Test – 2 coding questions to be solved in 70 minutes.Workstyles assessment – 20minutesReasoning ability – 35 minutes" }, { "code": null, "e": 25915, "s": 25856, "text": "Code Debugging – 7 questions to be debugged in 20 minutes." }, { "code": null, "e": 25976, "s": 25915, "text": "Coding Test – 2 coding questions to be solved in 70 minutes." }, { "code": null, "e": 26010, "s": 25976, "text": "Workstyles assessment – 20minutes" }, { "code": null, "e": 26041, "s": 26010, "text": "Reasoning ability – 35 minutes" }, { "code": null, "e": 26144, "s": 26041, "text": "Round 2: Shortlisted students from Round 1 went through round 2 which was a technical interview Round." }, { "code": null, "e": 26411, "s": 26144, "text": "The interview was held on Amazon Chime. The interviewer was very nice. After 2-3 minutes of introduction, he went straight to Coding questions. I was given a link to the code editor, and he explained to me the problems. The interview lasted approximately 60 minutes." }, { "code": null, "e": 26819, "s": 26411, "text": "Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities.Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters." }, { "code": null, "e": 26980, "s": 26819, "text": "Check if a binary tree is BST or not. The interviewer asked me to first tell the approach. After I solved it, I was asked about the time and space complexities." }, { "code": null, "e": 27228, "s": 26980, "text": "Given an array of strings containing only lowercase alphabets, return a string of 26 English lowercase alphabets in which the alphabets are in the same order as in the array of strings. The strings in the array do not contain repeating characters." }, { "code": null, "e": 27238, "s": 27228, "text": "Example: " }, { "code": null, "e": 27314, "s": 27238, "text": "Input : {\"abc\", \"dgf\", \"qsvu\", \"xzy\"}\nOutput : \"abcdegfhijklmnopqrstvuwxzy\"" }, { "code": null, "e": 27518, "s": 27314, "text": "The first round was only about two coding problems to test your knowledge of data structures and algorithms. I was not able to solve the second problem. I couldn’t make it to the 2nd technical interview." }, { "code": null, "e": 27525, "s": 27518, "text": "Amazon" }, { "code": null, "e": 27535, "s": 27525, "text": "Marketing" }, { "code": null, "e": 27545, "s": 27535, "text": "On-Campus" }, { "code": null, "e": 27567, "s": 27545, "text": "Interview Experiences" }, { "code": null, "e": 27574, "s": 27567, "text": "Amazon" }, { "code": null, "e": 27672, "s": 27574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27722, "s": 27672, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27750, "s": 27722, "text": "Amazon Interview Experience" }, { "code": null, "e": 27809, "s": 27750, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27847, "s": 27809, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 27883, "s": 27847, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 27929, "s": 27883, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27979, "s": 27929, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 28017, "s": 27979, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28082, "s": 28017, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" } ]
How do I catch a Ctrl+C event in C++?
The CTRL + C is used to send an interrupt to the current executing task. In this program, we will see how to catch the CTRL + C event using C++. The CTRL + C is one signal in C or C++. So we can catch by signal catching technique. For this signal, the code is SIGINT (Signal for Interrupt). Here the signal is caught by signal() function. Then one callback address is passed to call function after getting the signal. Please see the program to get the better idea. #include <unistd.h> #include <iostream> #include <cstdlib> #include <signal.h> using namespace std; // Define the function to be called when ctrl-c (SIGINT) is sent to process void signal_callback_handler(int signum) { cout << "Caught signal " << signum << endl; // Terminate program exit(signum); } int main(){ // Register signal and signal handler signal(SIGINT, signal_callback_handler); while(true){ cout << "Program processing..." << endl; sleep(1); } return EXIT_SUCCESS; } $ g++ test.cpp $ ./a.out Program processing... Program processing... Program processing... Program processing... Program processing... Program processing... ^CCaught signal 2 $
[ { "code": null, "e": 1207, "s": 1062, "text": "The CTRL + C is used to send an interrupt to the current executing task. In this program, we will see how to catch the CTRL + C event using C++." }, { "code": null, "e": 1480, "s": 1207, "text": "The CTRL + C is one signal in C or C++. So we can catch by signal catching technique. For this signal, the code is SIGINT (Signal for Interrupt). Here the signal is caught by signal() function. Then one callback address is passed to call function after getting the signal." }, { "code": null, "e": 1527, "s": 1480, "text": "Please see the program to get the better idea." }, { "code": null, "e": 2043, "s": 1527, "text": "#include <unistd.h>\n#include <iostream>\n#include <cstdlib>\n#include <signal.h>\nusing namespace std;\n// Define the function to be called when ctrl-c (SIGINT) is sent to process\nvoid signal_callback_handler(int signum) {\n cout << \"Caught signal \" << signum << endl;\n // Terminate program\n exit(signum);\n}\nint main(){\n // Register signal and signal handler\n signal(SIGINT, signal_callback_handler);\n while(true){\n cout << \"Program processing...\" << endl;\n sleep(1);\n }\n return EXIT_SUCCESS;\n}" }, { "code": null, "e": 2220, "s": 2043, "text": "$ g++ test.cpp\n$ ./a.out\nProgram processing...\nProgram processing...\nProgram processing...\nProgram processing...\nProgram processing...\nProgram processing...\n^CCaught signal 2\n$" } ]
SQL | SEQUENCES - GeeksforGeeks
21 Mar, 2018 Sequence is a set of integers 1, 2, 3, ... that are generated and supported by some database systems to produce unique values on demand. A sequence is a user defined schema bound object that generates a sequence of numeric values. Sequences are frequently used in many databases because many applications require each row in a table to contain a unique value and sequences provides an easy way to generate them. The sequence of numeric values is generated in an ascending or descending order at defined intervals and can be configured to restart when exceeds max_value. Syntax: CREATE SEQUENCE sequence_name START WITH initial_value INCREMENT BY increment_value MINVALUE minimum value MAXVALUE maximum value CYCLE|NOCYCLE ; sequence_name: Name of the sequence. initial_value: starting value from where the sequence starts. Initial_value should be greater than or equal to minimum value and less than equal to maximum value. increment_value: Value by which sequence will increment itself. Increment_value can be positive or negative. minimum_value: Minimum value of the sequence. maximum_value: Maximum value of the sequence. cycle: When sequence reaches its set_limit it starts from beginning. nocycle: An exception will be thrown if sequence exceeds its max_value. Example Following is the sequence query creating sequence in ascending order. Example 1:CREATE SEQUENCE sequence_1 start with 1 increment by 1 minvalue 0 maxvalue 100 cycle; Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding 100. CREATE SEQUENCE sequence_1 start with 1 increment by 1 minvalue 0 maxvalue 100 cycle; Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding 100. Example 2:Following is the sequence query creating sequence in descending order.CREATE SEQUENCE sequence_2 start with 100 increment by -1 minvalue 1 maxvalue 100 cycle; Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to maximum value and will be incremented by -1 having minimum value 1. CREATE SEQUENCE sequence_2 start with 100 increment by -1 minvalue 1 maxvalue 100 cycle; Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to maximum value and will be incremented by -1 having minimum value 1. Example to use sequence : create a table named students with columns as id and name.CREATE TABLE students ( ID number(10), NAME char(20) ); Now insert values into tableINSERT into students VALUES(sequence_1.nextval,'Ramesh'); INSERT into students VALUES(sequence_1.nextval,'Suresh'); where sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.Output: ______________________ | ID | NAME | ------------------------ | 1 | Ramesh | | 2 | Suresh | ---------------------- CREATE TABLE students ( ID number(10), NAME char(20) ); Now insert values into table INSERT into students VALUES(sequence_1.nextval,'Ramesh'); INSERT into students VALUES(sequence_1.nextval,'Suresh'); where sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.Output: ______________________ | ID | NAME | ------------------------ | 1 | Ramesh | | 2 | Suresh | ---------------------- This article is contributed by ARSHPREET SINGH. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. DBMS-SQL SQL-basics SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | Views SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL - ORDER BY
[ { "code": null, "e": 23834, "s": 23806, "text": "\n21 Mar, 2018" }, { "code": null, "e": 23971, "s": 23834, "text": "Sequence is a set of integers 1, 2, 3, ... that are generated and supported by some database systems to produce unique values on demand." }, { "code": null, "e": 24065, "s": 23971, "text": "A sequence is a user defined schema bound object that generates a sequence of numeric values." }, { "code": null, "e": 24246, "s": 24065, "text": "Sequences are frequently used in many databases because many applications require each row in a table to contain a unique value and sequences provides an easy way to generate them." }, { "code": null, "e": 24404, "s": 24246, "text": "The sequence of numeric values is generated in an ascending or descending order at defined intervals and can be configured to restart when exceeds max_value." }, { "code": null, "e": 24412, "s": 24404, "text": "Syntax:" }, { "code": null, "e": 25112, "s": 24412, "text": "CREATE SEQUENCE sequence_name\nSTART WITH initial_value\nINCREMENT BY increment_value\nMINVALUE minimum value\nMAXVALUE maximum value\nCYCLE|NOCYCLE ;\n\nsequence_name: Name of the sequence.\n\ninitial_value: starting value from where the sequence starts. \nInitial_value should be greater than or equal \nto minimum value and less than equal to maximum value.\n\nincrement_value: Value by which sequence will increment itself. \nIncrement_value can be positive or negative.\n\nminimum_value: Minimum value of the sequence.\nmaximum_value: Maximum value of the sequence.\n\ncycle: When sequence reaches its set_limit \nit starts from beginning.\n\nnocycle: An exception will be thrown \nif sequence exceeds its max_value.\n" }, { "code": null, "e": 25120, "s": 25112, "text": "Example" }, { "code": null, "e": 25190, "s": 25120, "text": "Following is the sequence query creating sequence in ascending order." }, { "code": null, "e": 25486, "s": 25190, "text": "Example 1:CREATE SEQUENCE sequence_1\nstart with 1\nincrement by 1\nminvalue 0\nmaxvalue 100\ncycle;\nAbove query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding 100." }, { "code": null, "e": 25573, "s": 25486, "text": "CREATE SEQUENCE sequence_1\nstart with 1\nincrement by 1\nminvalue 0\nmaxvalue 100\ncycle;\n" }, { "code": null, "e": 25773, "s": 25573, "text": "Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding 100." }, { "code": null, "e": 26127, "s": 25773, "text": "Example 2:Following is the sequence query creating sequence in descending order.CREATE SEQUENCE sequence_2\nstart with 100\nincrement by -1\nminvalue 1\nmaxvalue 100\ncycle;\nAbove query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to maximum value and will be incremented by -1 having minimum value 1." }, { "code": null, "e": 26217, "s": 26127, "text": "CREATE SEQUENCE sequence_2\nstart with 100\nincrement by -1\nminvalue 1\nmaxvalue 100\ncycle;\n" }, { "code": null, "e": 26402, "s": 26217, "text": "Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to maximum value and will be incremented by -1 having minimum value 1." }, { "code": null, "e": 26949, "s": 26402, "text": "Example to use sequence : create a table named students with columns as id and name.CREATE TABLE students\n( \nID number(10),\nNAME char(20)\n);\nNow insert values into tableINSERT into students VALUES(sequence_1.nextval,'Ramesh');\nINSERT into students VALUES(sequence_1.nextval,'Suresh');\nwhere sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.Output: ______________________\n| ID | NAME |\n------------------------\n| 1 | Ramesh |\n| 2 | Suresh | \n ----------------------\n" }, { "code": null, "e": 27007, "s": 26949, "text": "CREATE TABLE students\n( \nID number(10),\nNAME char(20)\n);\n" }, { "code": null, "e": 27036, "s": 27007, "text": "Now insert values into table" }, { "code": null, "e": 27153, "s": 27036, "text": "INSERT into students VALUES(sequence_1.nextval,'Ramesh');\nINSERT into students VALUES(sequence_1.nextval,'Suresh');\n" }, { "code": null, "e": 27255, "s": 27153, "text": "where sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.Output:" }, { "code": null, "e": 27416, "s": 27255, "text": " ______________________\n| ID | NAME |\n------------------------\n| 1 | Ramesh |\n| 2 | Suresh | \n ----------------------\n" }, { "code": null, "e": 27719, "s": 27416, "text": "This article is contributed by ARSHPREET SINGH. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27844, "s": 27719, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27853, "s": 27844, "text": "DBMS-SQL" }, { "code": null, "e": 27864, "s": 27853, "text": "SQL-basics" }, { "code": null, "e": 27868, "s": 27864, "text": "SQL" }, { "code": null, "e": 27872, "s": 27868, "text": "SQL" }, { "code": null, "e": 27970, "s": 27872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27982, "s": 27970, "text": "SQL | Views" }, { "code": null, "e": 28006, "s": 27982, "text": "SQL Interview Questions" }, { "code": null, "e": 28072, "s": 28006, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28087, "s": 28072, "text": "SQL | GROUP BY" }, { "code": null, "e": 28126, "s": 28087, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 28171, "s": 28126, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 28203, "s": 28171, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 28235, "s": 28203, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28313, "s": 28235, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" } ]
PHP | Regular Expressions - GeeksforGeeks
10 Feb, 2022 Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings. The exact sequence of characters are unpredictable beforehand, so the regex helps in fetching the required strings based on a pattern definition. Regular Expression is a compact way of describing a string pattern that matches a particular amount of text. As you know, PHP is an open-source language commonly used for website creation, it provides regular expression functions as an important tool. Like PHP, many other programming languages have their own implementation of regular expressions. This is the same with other applications also, which have their own support of regexes having various syntaxes. Many available modern languages and tools apply regexes on very large files and strings. Let us look into some of the advantages and uses of regular expressions in our applications. Advantages and uses of Regular expressions:In many scenarios, developers face problems whenever data are collected in free text fields as most of the programming deals with data entries. Regular expressions are used almost everywhere in today’s application programming. Regular expressions help in validation of text strings which are of programmer’s interest. It offers a powerful tool for analyzing, searching a pattern and modifying the text data. It helps in searching specific string pattern and extracting matching results in a flexible manner. It helps in parsing text files looking for a defined sequence of characters for further analysis or data manipulation. With the help of in-built regexes functions, easy and simple solutions are provided for identifying patterns. It effectively saves a lot of development time, which are in search of specific string pattern. It helps in important user information validations like email address, phone numbers and IP address. It helps in highlighting special keywords in a file based on search result or input. It helps in identifying specific template tags and replacing those data with the actual data as per the requirement. Regexes are very useful for creation of HTML template system recognizing tags. Regexes are mostly used for browser detection, spam filtration, checking password strength and form validations. We cannot cover everything under this topic, but let us look into some of the major regular expression concepts. The following table shows some regular expressions and the corresponding string which matches the regular expression pattern. Note: Complex search patterns can be created by applying some basic regular expression rules. Even many arithmetic operators like +, ^, – are used by regular expressions for creating little complex patterns. Operators in Regular Expression: Let us look into some of the operators in PHP regular expressions. Special Character Classes in Regular Expressions: Let us look into some of the special characters used in regular expressions. Shorthand Character Sets: Let us look into some shorthand character sets available. Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined functions for regular expressions in PHP. PHP provides the programmers to many useful functions to work with regular expressions. The below listed in-built functions are case-sensitive. Note: By default, regular expressions are case sensitive. There is a difference between strings inside single quotes and strings inside double quotes in PHP. The former are treated literally, whereas for the strings inside double-quotes means the content of the variable is printed instead of just printing their names. Example 1: <?php // Declare a regular expression$regex = '/^[a-zA-Z ]*$/'; // Declare a string$nameString = 'Sharukh khan'; // Use preg_match() function to// search string patternif(preg_match($regex, $nameString)) { echo("Name string matching with" . " regular expression");}else { echo("Only letters and white space" . " allowed in name string");} ?> Output: Name string matching with regular expression Example 2: <?php // Declare a regular expression$regex = "/<b>(.*)<\/b>/U"; // Declare a string$inputString = "Name: <b>John</b> Position: <b>Developer</b>"; // Use preg_match_all() function to perform// a global regular expression matchpreg_match_all($regex, $inputString, $output); echo $output[0][0]." <br> ".$output[0][1]."\n"; ?> Output: John Developer Example 3: <?php // Declare a regular expression$regex = "([0-9]+)"; // Declare a string$original = "Completed graduation in 2004";$replaceWith = "2002"; // Use ereg_replace() function to search a// string pattern in an other string$original = ereg_replace($regex, $replaceWith, $original); // Display resultecho $original; ?> Output: Completed graduation in 2002 Example 4: <?php<?php // Declare a string$ip = "134.645.478.670"; // Declare a regular expression$regex = "/\./"; // Use preg_split() function to// convert a given string into// an array$output = preg_split ($regex, $ip); echo "$output[0] <br>";echo "$output[1] <br>";echo "$output[2] <br>";echo "$output[3] <br>"; ?> Output: 134 645 478 670 Metacharacters: There are two kinds of characters that are used in regular expressions these are: Regular characters and Metacharacters. Regular characters are those characters which have a ‘literal’ meaning and Metacharacters are those characters which have ‘special’ meaning in regular expression. Other Examples: Note: Metacharacters are very powerful in regular expressions pattern matching solutions. It handles a lot of complex pattern processing. Every character which is not a metacharacter is definitely a regular character. Every regular character matches the same character by itself. POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic expressions which are called POSIX regular expressions. Some times, complex expression are created by combining various elements or operators in regular expressions. The very basic regex is the one which matches a single character. Lets look into some of the POSIX regular expressions. Quantifiers in Regular Expression: Quantifiers are special characters which tell the quantity, frequency or the number of instances or occurrence of bracketed character or group of characters. They are also called as greedy and lazy expressions. Let us look into some of the concepts and examples of quantifiers. Note: The $ character inside the expression will match the end of the target string. The *, ?, + symbols in a regular expression denotes the frequency of occurrence of a character. If it occurs zero or more time, zero or one time and one or more times. The ^ character inside the expression will match the beginning of the target string. The . metacharacter matches any single character other than the newline. Commonly known regular expression engines: Regexp RegexBuddy Conclusion: A regular expression is a pattern that describes some string text in a particular pattern or it is defined as a pattern-matching algorithm expressed in a single line. Regular expressions are very useful in the programming world for validation checks and recognizing specific templates. PHP provides many in-built functions supporting regular expressions. Metacharacters helps in creating complex patterns. nidhi_biet clintra gabaa406 adnanirshad158 PHP-string 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 execute PHP code using command line ? How to pop an alert message box using PHP ? PHP in_array() Function How to convert array to string in 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": 40503, "s": 40475, "text": "\n10 Feb, 2022" }, { "code": null, "e": 41064, "s": 40503, "text": "Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings. The exact sequence of characters are unpredictable beforehand, so the regex helps in fetching the required strings based on a pattern definition." }, { "code": null, "e": 41707, "s": 41064, "text": "Regular Expression is a compact way of describing a string pattern that matches a particular amount of text. As you know, PHP is an open-source language commonly used for website creation, it provides regular expression functions as an important tool. Like PHP, many other programming languages have their own implementation of regular expressions. This is the same with other applications also, which have their own support of regexes having various syntaxes. Many available modern languages and tools apply regexes on very large files and strings. Let us look into some of the advantages and uses of regular expressions in our applications." }, { "code": null, "e": 41977, "s": 41707, "text": "Advantages and uses of Regular expressions:In many scenarios, developers face problems whenever data are collected in free text fields as most of the programming deals with data entries. Regular expressions are used almost everywhere in today’s application programming." }, { "code": null, "e": 42068, "s": 41977, "text": "Regular expressions help in validation of text strings which are of programmer’s interest." }, { "code": null, "e": 42158, "s": 42068, "text": "It offers a powerful tool for analyzing, searching a pattern and modifying the text data." }, { "code": null, "e": 42258, "s": 42158, "text": "It helps in searching specific string pattern and extracting matching results in a flexible manner." }, { "code": null, "e": 42377, "s": 42258, "text": "It helps in parsing text files looking for a defined sequence of characters for further analysis or data manipulation." }, { "code": null, "e": 42487, "s": 42377, "text": "With the help of in-built regexes functions, easy and simple solutions are provided for identifying patterns." }, { "code": null, "e": 42583, "s": 42487, "text": "It effectively saves a lot of development time, which are in search of specific string pattern." }, { "code": null, "e": 42684, "s": 42583, "text": "It helps in important user information validations like email address, phone numbers and IP address." }, { "code": null, "e": 42769, "s": 42684, "text": "It helps in highlighting special keywords in a file based on search result or input." }, { "code": null, "e": 42886, "s": 42769, "text": "It helps in identifying specific template tags and replacing those data with the actual data as per the requirement." }, { "code": null, "e": 42965, "s": 42886, "text": "Regexes are very useful for creation of HTML template system recognizing tags." }, { "code": null, "e": 43078, "s": 42965, "text": "Regexes are mostly used for browser detection, spam filtration, checking password strength and form validations." }, { "code": null, "e": 43317, "s": 43078, "text": "We cannot cover everything under this topic, but let us look into some of the major regular expression concepts. The following table shows some regular expressions and the corresponding string which matches the regular expression pattern." }, { "code": null, "e": 43525, "s": 43317, "text": "Note: Complex search patterns can be created by applying some basic regular expression rules. Even many arithmetic operators like +, ^, – are used by regular expressions for creating little complex patterns." }, { "code": null, "e": 43625, "s": 43525, "text": "Operators in Regular Expression: Let us look into some of the operators in PHP regular expressions." }, { "code": null, "e": 43752, "s": 43625, "text": "Special Character Classes in Regular Expressions: Let us look into some of the special characters used in regular expressions." }, { "code": null, "e": 43836, "s": 43752, "text": "Shorthand Character Sets: Let us look into some shorthand character sets available." }, { "code": null, "e": 44059, "s": 43836, "text": "Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined functions for regular expressions in PHP. PHP provides the programmers to many useful functions to work with regular expressions." }, { "code": null, "e": 44115, "s": 44059, "text": "The below listed in-built functions are case-sensitive." }, { "code": null, "e": 44121, "s": 44115, "text": "Note:" }, { "code": null, "e": 44173, "s": 44121, "text": "By default, regular expressions are case sensitive." }, { "code": null, "e": 44435, "s": 44173, "text": "There is a difference between strings inside single quotes and strings inside double quotes in PHP. The former are treated literally, whereas for the strings inside double-quotes means the content of the variable is printed instead of just printing their names." }, { "code": null, "e": 44446, "s": 44435, "text": "Example 1:" }, { "code": "<?php // Declare a regular expression$regex = '/^[a-zA-Z ]*$/'; // Declare a string$nameString = 'Sharukh khan'; // Use preg_match() function to// search string patternif(preg_match($regex, $nameString)) { echo(\"Name string matching with\" . \" regular expression\");}else { echo(\"Only letters and white space\" . \" allowed in name string\");} ?>", "e": 44808, "s": 44446, "text": null }, { "code": null, "e": 44816, "s": 44808, "text": "Output:" }, { "code": null, "e": 44861, "s": 44816, "text": "Name string matching with regular expression" }, { "code": null, "e": 44872, "s": 44861, "text": "Example 2:" }, { "code": "<?php // Declare a regular expression$regex = \"/<b>(.*)<\\/b>/U\"; // Declare a string$inputString = \"Name: <b>John</b> Position: <b>Developer</b>\"; // Use preg_match_all() function to perform// a global regular expression matchpreg_match_all($regex, $inputString, $output); echo $output[0][0].\" <br> \".$output[0][1].\"\\n\"; ?>", "e": 45196, "s": 44872, "text": null }, { "code": null, "e": 45204, "s": 45196, "text": "Output:" }, { "code": null, "e": 45220, "s": 45204, "text": "John\nDeveloper\n" }, { "code": null, "e": 45231, "s": 45220, "text": "Example 3:" }, { "code": "<?php // Declare a regular expression$regex = \"([0-9]+)\"; // Declare a string$original = \"Completed graduation in 2004\";$replaceWith = \"2002\"; // Use ereg_replace() function to search a// string pattern in an other string$original = ereg_replace($regex, $replaceWith, $original); // Display resultecho $original; ?>", "e": 45553, "s": 45231, "text": null }, { "code": null, "e": 45561, "s": 45553, "text": "Output:" }, { "code": null, "e": 45590, "s": 45561, "text": "Completed graduation in 2002" }, { "code": null, "e": 45601, "s": 45590, "text": "Example 4:" }, { "code": "<?php<?php // Declare a string$ip = \"134.645.478.670\"; // Declare a regular expression$regex = \"/\\./\"; // Use preg_split() function to// convert a given string into// an array$output = preg_split ($regex, $ip); echo \"$output[0] <br>\";echo \"$output[1] <br>\";echo \"$output[2] <br>\";echo \"$output[3] <br>\"; ?>", "e": 45908, "s": 45601, "text": null }, { "code": null, "e": 45916, "s": 45908, "text": "Output:" }, { "code": null, "e": 45933, "s": 45916, "text": "134\n645\n478\n670\n" }, { "code": null, "e": 46233, "s": 45933, "text": "Metacharacters: There are two kinds of characters that are used in regular expressions these are: Regular characters and Metacharacters. Regular characters are those characters which have a ‘literal’ meaning and Metacharacters are those characters which have ‘special’ meaning in regular expression." }, { "code": null, "e": 46249, "s": 46233, "text": "Other Examples:" }, { "code": null, "e": 46255, "s": 46249, "text": "Note:" }, { "code": null, "e": 46387, "s": 46255, "text": "Metacharacters are very powerful in regular expressions pattern matching solutions. It handles a lot of complex pattern processing." }, { "code": null, "e": 46467, "s": 46387, "text": "Every character which is not a metacharacter is definitely a regular character." }, { "code": null, "e": 46529, "s": 46467, "text": "Every regular character matches the same character by itself." }, { "code": null, "e": 46840, "s": 46529, "text": "POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic expressions which are called POSIX regular expressions. Some times, complex expression are created by combining various elements or operators in regular expressions. The very basic regex is the one which matches a single character." }, { "code": null, "e": 46894, "s": 46840, "text": "Lets look into some of the POSIX regular expressions." }, { "code": null, "e": 47207, "s": 46894, "text": "Quantifiers in Regular Expression: Quantifiers are special characters which tell the quantity, frequency or the number of instances or occurrence of bracketed character or group of characters. They are also called as greedy and lazy expressions. Let us look into some of the concepts and examples of quantifiers." }, { "code": null, "e": 47213, "s": 47207, "text": "Note:" }, { "code": null, "e": 47292, "s": 47213, "text": "The $ character inside the expression will match the end of the target string." }, { "code": null, "e": 47460, "s": 47292, "text": "The *, ?, + symbols in a regular expression denotes the frequency of occurrence of a character. If it occurs zero or more time, zero or one time and one or more times." }, { "code": null, "e": 47545, "s": 47460, "text": "The ^ character inside the expression will match the beginning of the target string." }, { "code": null, "e": 47618, "s": 47545, "text": "The . metacharacter matches any single character other than the newline." }, { "code": null, "e": 47661, "s": 47618, "text": "Commonly known regular expression engines:" }, { "code": null, "e": 47668, "s": 47661, "text": "Regexp" }, { "code": null, "e": 47679, "s": 47668, "text": "RegexBuddy" }, { "code": null, "e": 48097, "s": 47679, "text": "Conclusion: A regular expression is a pattern that describes some string text in a particular pattern or it is defined as a pattern-matching algorithm expressed in a single line. Regular expressions are very useful in the programming world for validation checks and recognizing specific templates. PHP provides many in-built functions supporting regular expressions. Metacharacters helps in creating complex patterns." }, { "code": null, "e": 48108, "s": 48097, "text": "nidhi_biet" }, { "code": null, "e": 48116, "s": 48108, "text": "clintra" }, { "code": null, "e": 48125, "s": 48116, "text": "gabaa406" }, { "code": null, "e": 48140, "s": 48125, "text": "adnanirshad158" }, { "code": null, "e": 48151, "s": 48140, "text": "PHP-string" }, { "code": null, "e": 48155, "s": 48151, "text": "PHP" }, { "code": null, "e": 48172, "s": 48155, "text": "Web Technologies" }, { "code": null, "e": 48176, "s": 48172, "text": "PHP" }, { "code": null, "e": 48274, "s": 48176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48283, "s": 48274, "text": "Comments" }, { "code": null, "e": 48296, "s": 48283, "text": "Old Comments" }, { "code": null, "e": 48346, "s": 48296, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 48391, "s": 48346, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 48435, "s": 48391, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 48459, "s": 48435, "text": "PHP in_array() Function" }, { "code": null, "e": 48499, "s": 48459, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 48555, "s": 48499, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 48588, "s": 48555, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 48650, "s": 48588, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 48693, "s": 48650, "text": "How to fetch data from an API in ReactJS ?" } ]