title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Top 20 Data Science Discord servers to join in 2020 | by Benedict Neo | Towards Data Science
If you’ve never heard of Discord before, then you’re most likely not a gamer. But that’s about to change. Initially, Discord was constructed to be a real-time social platform where gamers unite and communicate with each other. But now, Discord has grown into an essential tool for influencers, YouTubers, memers, and basically anyone to connect with their community. To me, I would say Discord is a mix of Skype and social platforms such as Reddit, Telegram, Twitter but minus all the noise, plus unique features of its own and a cleaner and faster UI. Discord Inc. says it now has more than 250 million registered users, up from 130 million a year ago, and that 850 million messages are exchanged daily. That’s a lot of chatting. While the virtual hangout now has many corners, where people talk about everything (from books to tv shows on Netflix), it would seem that Artificial Intelligence, Machine Learning, and Data Science have also made their way into Discord servers, where data science enthusiast and experts gather to share all kinds of things, from solving multivariable calculus and making neural networks from scratch to rambling about how to get a job as a data scientists and how data scientists will be replaced by Machine learning in the coming decades. If you’ve never used Discord before, and you have no idea how to start, don’t worry. It’s super easy to use. After you sign up for Discord here, you can join different servers, akin to slack channels using a custom invite link, which you’ll see below each server in this article later on. Each of these servers represents a community, and you can intuitively toggle between them. Inside a server, you’ll see a list of hashtags (channels) beside the server icons, the chats in the middle and the server members at the far right. You can also opt for private conversations with your friends without using servers. To have a more in-depth guide to use Discord, check out this video. You might ask why should one start using this mysterious purple chatting platform if you’re comfortable with Twitter and Reddit? Well, here are the reasons. Discord is an open-end platform for all kinds of questions and inquiries you have to satiate your curious mind. Many influencers and YouTubers such as Ninja, Try Guys, and Philip DeFranco all love using Discord because they love the community-centered platform and the privacy-centric experience it provides. A few benefits of Discords include: 1. Highly customizable — private and public channels, roles, colors, etc2. Private3. Chat-oriented Discord is the place where to talk to people about the things you care about, and you can hang out with anyone in any way you want, whether it’s engaging in debates or sharing interests in memes and jokes. Now that you’re introduced to what Discord is, here is a list of servers on Discord where you can ask any questions you have on AI, ML, Data Science and so on. Data Science is not a stroll in the park, you have to tackle difficult statistics and probability concepts while learning how to code at the same time, not to mention the communication skills you have to master. Discord is a great place for you to find a community that is striving towards the same goal, and it can motivate you to push yourself past your limit. So, start using discord today, and join these amazing Data Science Servers! I write articles on Data Science and AI. If you want to be notified when I post, subscribe to my medium newsletter now! If you’re not a medium member, consider subscribing today for only just $5. You’ll be supporting me directly and you’ll get access to tons of great writing on medium! General• Science and Technology• Everything HubHacking skills• Programming• The Programming Hangout• The Programming Server• Planet: Code• CS 50• The Coding Den• Python• CP Community• #100DaysOfCodeData Science• Towards Data Science• Data Science• CS DojoProjects/tutorials • Tech with Tim• SentdexML and AI • /r/LearnMachineLearning• Fundamentals of ML• Artificial Intelligence Community• TensorFlow• Learn AI Together Data Science is a multidisciplinary field that requires knowledge from various fields, from epidemiology to finance. Thus, joining these servers will equip you with different kinds of information for your future endeavors. A community dedicated to scientific exploration and technological innovation! A place for sharing scientific discussions, research, and meeting new and similar individuals who are interested in academia of science. discord.gg The name says it all. This server has literally everything, from animals, sports, and movies to tech and programming. discord.gg Data Science involves a lot of coding, and one way to improve your coding skills is by asking questions (and getting answers from StackOverflow). All these servers encompass avid coders and hackers which can answer any questions you throw at them. Ask away! An active community around various programming languages, operating systems, as well as hardware, security, and low-level programming. discordapp.com A community geared towards programming. TPH has a place for all kinds of programmers, from complete beginners to experts with 20 years of experience. discord.gg A programming server with mathematics, ML and AI, data science, and cyber-security channels. A place for a beginner to ask data science related questions. discord.gg One of the most popular Introductions to Computer Science classes, now on Discord. Keep up with their latest courses and be connected to the smarts here! discord.gg A place to freely ask other Coders/Programmers for help, or any question about anything related to coding. A mashup between Stack overflow and subreddits like r/coding /r/ programming etc. discord.gg A huge community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others. discord.gg A server for specific programming language questions, such as c, CPP, java, python, SQL, etc. discord.gg A community of competitive programmers where coders ask questions from code forces. There is a channel for beginner questions and math. discord.gg The infamous #100 days of code, where dedicated programmers commit to coding every day for 100 days, and posting it on twitter. Connect with other devoted programmers in this server! discord.gg A community-driven, maintained, and moderated project and is not an official extension of the TDS group. A great server to ask data science questions as well as obtaining resources throughout your learning process. discordapp.com A community of data science professionals and enthusiasts. Explore all the different aspects of this field, from visualization and communication to data engineering and model deployment. Whether you’re a pundit, student or a casual enthusiast, all are welcomed! discordapp.com CS Dojo is a well-known YouTuber who talks about programming related stuff. Join his large community where discussions about programming, game development, web dev, AI and ML, Data Science, etc. are made. discord.gg These are servers of YouTubers who create amazing videos on tutorials for Python, machine learning, neural networks and so on. The YouTubers Tech with Tim and Sentdex are featured. Connect with Tech with Tim enthusiasts where u can ask questions, project suggestions, python, pygame, and machine learning and AI. discord.gg Sentdex’s community is largely made up of Python programmers, but others are welcomed as well. The #help channel is extremely useful. discord.gg These servers are for those who need to ask questions about Machine Learning and AI. Stay motivated to this group of people wanting to achieve the same thing as you and share knowledge with each other. A great community where all are friendly ML enthusiasts who are willing to help everyone, even the complete beginners. There are also study rooms for the infamous Andrew Ng Machine Learning course and fast.ai deep learning course. discord.gg A place to ask everything about ML, from the basic linear regression to Neural Networks. discord.gg A community of AI enthusiasts, with main channels — Machine Learning, Language processing, Vision & speech, and others. discord.gg Tensorflow is an end-to-end open-source machine learning platform. If you want to get started on Tensorflow, join this server first. discordapp.com “Learn AI together” is a great discord server with almost 4,000 AI enthusiasts sharing papers, projects, kaggle competitions, courses and much more. It’s a great addition to anyone who’s interested in Ai and to be apart of a community learning AI. discord.gg Discord servers are amazing, not only do you get to have a community of people sharing the same passion and goals, but you get to ask all kinds of questions and get them answered in a flash. It’s important to be a part of communities like this as Data Science is really difficult to learn all by yourself. It’s the insights and experiences of others that are crucial as compared to the textbook stuff. It’s the theory part of Data Science that people struggle with the most, especially in mathematics and programming. With a community of friendly and helpful people, your journey towards becoming a Data Scientists will be smoother. So, try out Discord if you don’t already have it. And start asking questions, and answer the questions of others as well, because asking questions proves that you are actually learning, and not pretending to know something. “Never let fear stop you from asking something you don’t understand or know. To pretend or to act as if you know is not a wise thing to do.” Catherine Pulsifer Thanks for reading this article, I hope it inspired you to start using Discord. Leave comments down below for any other servers you would like to share! towardsdatascience.com towardsdatascience.com medium.com towardsdatascience.com towardsdatascience.com If you want to be updated with my latest articles follow me on Medium. Follow me at:
[ { "code": null, "e": 538, "s": 171, "text": "If you’ve never heard of Discord before, then you’re most likely not a gamer. But that’s about to change. Initially, Discord was constructed to be a real-time social platform where gamers unite and communicate with each other. But now, Discord has grown into an essential tool for influencers, YouTubers, memers, and basically anyone to connect with their community." }, { "code": null, "e": 724, "s": 538, "text": "To me, I would say Discord is a mix of Skype and social platforms such as Reddit, Telegram, Twitter but minus all the noise, plus unique features of its own and a cleaner and faster UI." }, { "code": null, "e": 902, "s": 724, "text": "Discord Inc. says it now has more than 250 million registered users, up from 130 million a year ago, and that 850 million messages are exchanged daily. That’s a lot of chatting." }, { "code": null, "e": 1443, "s": 902, "text": "While the virtual hangout now has many corners, where people talk about everything (from books to tv shows on Netflix), it would seem that Artificial Intelligence, Machine Learning, and Data Science have also made their way into Discord servers, where data science enthusiast and experts gather to share all kinds of things, from solving multivariable calculus and making neural networks from scratch to rambling about how to get a job as a data scientists and how data scientists will be replaced by Machine learning in the coming decades." }, { "code": null, "e": 1552, "s": 1443, "text": "If you’ve never used Discord before, and you have no idea how to start, don’t worry. It’s super easy to use." }, { "code": null, "e": 1823, "s": 1552, "text": "After you sign up for Discord here, you can join different servers, akin to slack channels using a custom invite link, which you’ll see below each server in this article later on. Each of these servers represents a community, and you can intuitively toggle between them." }, { "code": null, "e": 2055, "s": 1823, "text": "Inside a server, you’ll see a list of hashtags (channels) beside the server icons, the chats in the middle and the server members at the far right. You can also opt for private conversations with your friends without using servers." }, { "code": null, "e": 2123, "s": 2055, "text": "To have a more in-depth guide to use Discord, check out this video." }, { "code": null, "e": 2280, "s": 2123, "text": "You might ask why should one start using this mysterious purple chatting platform if you’re comfortable with Twitter and Reddit? Well, here are the reasons." }, { "code": null, "e": 2589, "s": 2280, "text": "Discord is an open-end platform for all kinds of questions and inquiries you have to satiate your curious mind. Many influencers and YouTubers such as Ninja, Try Guys, and Philip DeFranco all love using Discord because they love the community-centered platform and the privacy-centric experience it provides." }, { "code": null, "e": 2724, "s": 2589, "text": "A few benefits of Discords include: 1. Highly customizable — private and public channels, roles, colors, etc2. Private3. Chat-oriented" }, { "code": null, "e": 2930, "s": 2724, "text": "Discord is the place where to talk to people about the things you care about, and you can hang out with anyone in any way you want, whether it’s engaging in debates or sharing interests in memes and jokes." }, { "code": null, "e": 3302, "s": 2930, "text": "Now that you’re introduced to what Discord is, here is a list of servers on Discord where you can ask any questions you have on AI, ML, Data Science and so on. Data Science is not a stroll in the park, you have to tackle difficult statistics and probability concepts while learning how to code at the same time, not to mention the communication skills you have to master." }, { "code": null, "e": 3453, "s": 3302, "text": "Discord is a great place for you to find a community that is striving towards the same goal, and it can motivate you to push yourself past your limit." }, { "code": null, "e": 3529, "s": 3453, "text": "So, start using discord today, and join these amazing Data Science Servers!" }, { "code": null, "e": 3649, "s": 3529, "text": "I write articles on Data Science and AI. If you want to be notified when I post, subscribe to my medium newsletter now!" }, { "code": null, "e": 3816, "s": 3649, "text": "If you’re not a medium member, consider subscribing today for only just $5. You’ll be supporting me directly and you’ll get access to tons of great writing on medium!" }, { "code": null, "e": 4236, "s": 3816, "text": "General• Science and Technology• Everything HubHacking skills• Programming• The Programming Hangout• The Programming Server• Planet: Code• CS 50• The Coding Den• Python• CP Community• #100DaysOfCodeData Science• Towards Data Science• Data Science• CS DojoProjects/tutorials • Tech with Tim• SentdexML and AI • /r/LearnMachineLearning• Fundamentals of ML• Artificial Intelligence Community• TensorFlow• Learn AI Together" }, { "code": null, "e": 4459, "s": 4236, "text": "Data Science is a multidisciplinary field that requires knowledge from various fields, from epidemiology to finance. Thus, joining these servers will equip you with different kinds of information for your future endeavors." }, { "code": null, "e": 4674, "s": 4459, "text": "A community dedicated to scientific exploration and technological innovation! A place for sharing scientific discussions, research, and meeting new and similar individuals who are interested in academia of science." }, { "code": null, "e": 4685, "s": 4674, "text": "discord.gg" }, { "code": null, "e": 4803, "s": 4685, "text": "The name says it all. This server has literally everything, from animals, sports, and movies to tech and programming." }, { "code": null, "e": 4814, "s": 4803, "text": "discord.gg" }, { "code": null, "e": 5072, "s": 4814, "text": "Data Science involves a lot of coding, and one way to improve your coding skills is by asking questions (and getting answers from StackOverflow). All these servers encompass avid coders and hackers which can answer any questions you throw at them. Ask away!" }, { "code": null, "e": 5207, "s": 5072, "text": "An active community around various programming languages, operating systems, as well as hardware, security, and low-level programming." }, { "code": null, "e": 5222, "s": 5207, "text": "discordapp.com" }, { "code": null, "e": 5372, "s": 5222, "text": "A community geared towards programming. TPH has a place for all kinds of programmers, from complete beginners to experts with 20 years of experience." }, { "code": null, "e": 5383, "s": 5372, "text": "discord.gg" }, { "code": null, "e": 5538, "s": 5383, "text": "A programming server with mathematics, ML and AI, data science, and cyber-security channels. A place for a beginner to ask data science related questions." }, { "code": null, "e": 5549, "s": 5538, "text": "discord.gg" }, { "code": null, "e": 5703, "s": 5549, "text": "One of the most popular Introductions to Computer Science classes, now on Discord. Keep up with their latest courses and be connected to the smarts here!" }, { "code": null, "e": 5714, "s": 5703, "text": "discord.gg" }, { "code": null, "e": 5903, "s": 5714, "text": "A place to freely ask other Coders/Programmers for help, or any question about anything related to coding. A mashup between Stack overflow and subreddits like r/coding /r/ programming etc." }, { "code": null, "e": 5914, "s": 5903, "text": "discord.gg" }, { "code": null, "e": 6090, "s": 5914, "text": "A huge community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others." }, { "code": null, "e": 6101, "s": 6090, "text": "discord.gg" }, { "code": null, "e": 6195, "s": 6101, "text": "A server for specific programming language questions, such as c, CPP, java, python, SQL, etc." }, { "code": null, "e": 6206, "s": 6195, "text": "discord.gg" }, { "code": null, "e": 6342, "s": 6206, "text": "A community of competitive programmers where coders ask questions from code forces. There is a channel for beginner questions and math." }, { "code": null, "e": 6353, "s": 6342, "text": "discord.gg" }, { "code": null, "e": 6536, "s": 6353, "text": "The infamous #100 days of code, where dedicated programmers commit to coding every day for 100 days, and posting it on twitter. Connect with other devoted programmers in this server!" }, { "code": null, "e": 6547, "s": 6536, "text": "discord.gg" }, { "code": null, "e": 6762, "s": 6547, "text": "A community-driven, maintained, and moderated project and is not an official extension of the TDS group. A great server to ask data science questions as well as obtaining resources throughout your learning process." }, { "code": null, "e": 6777, "s": 6762, "text": "discordapp.com" }, { "code": null, "e": 7039, "s": 6777, "text": "A community of data science professionals and enthusiasts. Explore all the different aspects of this field, from visualization and communication to data engineering and model deployment. Whether you’re a pundit, student or a casual enthusiast, all are welcomed!" }, { "code": null, "e": 7054, "s": 7039, "text": "discordapp.com" }, { "code": null, "e": 7259, "s": 7054, "text": "CS Dojo is a well-known YouTuber who talks about programming related stuff. Join his large community where discussions about programming, game development, web dev, AI and ML, Data Science, etc. are made." }, { "code": null, "e": 7270, "s": 7259, "text": "discord.gg" }, { "code": null, "e": 7451, "s": 7270, "text": "These are servers of YouTubers who create amazing videos on tutorials for Python, machine learning, neural networks and so on. The YouTubers Tech with Tim and Sentdex are featured." }, { "code": null, "e": 7583, "s": 7451, "text": "Connect with Tech with Tim enthusiasts where u can ask questions, project suggestions, python, pygame, and machine learning and AI." }, { "code": null, "e": 7594, "s": 7583, "text": "discord.gg" }, { "code": null, "e": 7728, "s": 7594, "text": "Sentdex’s community is largely made up of Python programmers, but others are welcomed as well. The #help channel is extremely useful." }, { "code": null, "e": 7739, "s": 7728, "text": "discord.gg" }, { "code": null, "e": 7941, "s": 7739, "text": "These servers are for those who need to ask questions about Machine Learning and AI. Stay motivated to this group of people wanting to achieve the same thing as you and share knowledge with each other." }, { "code": null, "e": 8172, "s": 7941, "text": "A great community where all are friendly ML enthusiasts who are willing to help everyone, even the complete beginners. There are also study rooms for the infamous Andrew Ng Machine Learning course and fast.ai deep learning course." }, { "code": null, "e": 8183, "s": 8172, "text": "discord.gg" }, { "code": null, "e": 8272, "s": 8183, "text": "A place to ask everything about ML, from the basic linear regression to Neural Networks." }, { "code": null, "e": 8283, "s": 8272, "text": "discord.gg" }, { "code": null, "e": 8403, "s": 8283, "text": "A community of AI enthusiasts, with main channels — Machine Learning, Language processing, Vision & speech, and others." }, { "code": null, "e": 8414, "s": 8403, "text": "discord.gg" }, { "code": null, "e": 8547, "s": 8414, "text": "Tensorflow is an end-to-end open-source machine learning platform. If you want to get started on Tensorflow, join this server first." }, { "code": null, "e": 8562, "s": 8547, "text": "discordapp.com" }, { "code": null, "e": 8810, "s": 8562, "text": "“Learn AI together” is a great discord server with almost 4,000 AI enthusiasts sharing papers, projects, kaggle competitions, courses and much more. It’s a great addition to anyone who’s interested in Ai and to be apart of a community learning AI." }, { "code": null, "e": 8821, "s": 8810, "text": "discord.gg" }, { "code": null, "e": 9223, "s": 8821, "text": "Discord servers are amazing, not only do you get to have a community of people sharing the same passion and goals, but you get to ask all kinds of questions and get them answered in a flash. It’s important to be a part of communities like this as Data Science is really difficult to learn all by yourself. It’s the insights and experiences of others that are crucial as compared to the textbook stuff." }, { "code": null, "e": 9454, "s": 9223, "text": "It’s the theory part of Data Science that people struggle with the most, especially in mathematics and programming. With a community of friendly and helpful people, your journey towards becoming a Data Scientists will be smoother." }, { "code": null, "e": 9678, "s": 9454, "text": "So, try out Discord if you don’t already have it. And start asking questions, and answer the questions of others as well, because asking questions proves that you are actually learning, and not pretending to know something." }, { "code": null, "e": 9819, "s": 9678, "text": "“Never let fear stop you from asking something you don’t understand or know. To pretend or to act as if you know is not a wise thing to do.”" }, { "code": null, "e": 9838, "s": 9819, "text": "Catherine Pulsifer" }, { "code": null, "e": 9918, "s": 9838, "text": "Thanks for reading this article, I hope it inspired you to start using Discord." }, { "code": null, "e": 9991, "s": 9918, "text": "Leave comments down below for any other servers you would like to share!" }, { "code": null, "e": 10014, "s": 9991, "text": "towardsdatascience.com" }, { "code": null, "e": 10037, "s": 10014, "text": "towardsdatascience.com" }, { "code": null, "e": 10048, "s": 10037, "text": "medium.com" }, { "code": null, "e": 10071, "s": 10048, "text": "towardsdatascience.com" }, { "code": null, "e": 10094, "s": 10071, "text": "towardsdatascience.com" }, { "code": null, "e": 10165, "s": 10094, "text": "If you want to be updated with my latest articles follow me on Medium." } ]
Machine Learning Models For Improved Startup Valuation. | by flo.tausend | Towards Data Science
Determining the valuation of an early-stage Startup is in most cases very challenging due limited historical data, little to no existing revenues, market uncertainty and many more. Traditional valuation techniques, such as Discounted Cash Flow (DCF) or Multiples (CCA), therefore often lead to inappropriate results. On the other hand, alternative valuation methods remain subject to an individual’s subjective assessment and a black box for others. Therefore, the underlying study leverages machine learning algorithms to predict a fair, data-driven and comprehensible startup valuations. Three different data sources are merged and applied to three regression models. The regression models’ performance is compared on defined measurements and the final outcome is a continuous numeric value — the predicted startup valuation. In order to build a machine learning model and get significant results, it is essential to have a solid data base. In this case the final analytical data set is a combination of public and private, anonymised data sources. The study was enabled by partnering with investory.io to get access to anonymised key performance indicators, as well as cap tab le data from early-stage companies. In combination with Crunchbase it is possible to map this data to funding stages, funding rounds, locations and the team size. Last but not least we used social media data, as a previous study (“Social is the new financial”, Jin et al 2017) found a relationship between likelihood of closing an investment round and Twitter activities. At this point a big shoutout to Storyclash for access to their amazing social media analytics platform. Most of the effort had to be spent merging the different data sources together and cleaning them. While the investory.io data came already in a clean numeric format, Crunchbase data for example was not pulled through their API and therefor came in a very unclean format. In the very beginning an overview of the different tables and information was generated with a simple database client DBEAVER. After that relevant information was extracted, transformed and loaded mainly with the help of Python programming. As this generated countless lines of code, we will not go into every detail, but pick some examples as data normalisation below. But just to give you a brief idea: There were companies from more than 50 countries included, with various different currencies and local peculiarities. It is often said that data preparation, cleaning and transformation consumes 80% of a data scientist’s time. This statement also proves itself true in this case. Normalisation & Scaling On important step to prepare the dataset for our machine learning algorithms was normalisation. The idea is to bring the numeric values in a common scale. This is necessary as we have headcount and revenue as two features. While revenue may take a numeric value with 6 digits, it is very unlikely that the headcount has values above 100. The features have a very different range and revenue would influence our model more only due to its higher values. #Data Normalizationfrom sklearn.preprocessing import MinMaxScaler#Select numerical columns which needs to be normalizedtrain_norm = x_traintest_norm = x_test# Normalize Training Data scaler = MinMaxScaler(feature_range=(0, 1))x_train_norm = scaler.fit_transform(train_norm)#Converting numpy array to dataframetraining_norm_col = pd.DataFrame(x_train_norm, index=train_norm.index, columns=train_norm.columns) x_train.update(training_norm_col)print (x_train.head())# Normalize Testing Data by using mean and SD of training setx_test_norm = scaler.transform(test_norm)testing_norm_col = pd.DataFrame(x_test_norm, index=test_norm.index, columns=test_norm.columns) x_test.update(testing_norm_col)print (x_train.head()) The MinMax Scaler is very sensitive to outliers. If your data has some severe outliers, please take care of that beforehand. The range of the normalized data is usually between zero and one as seen in the code above. Within the project there were three regression models applied to the dataset. They were chosen according to their characteristics and usual purpose of application. Each regression model was evaluated with the help of three indicators: Mean Absolute Error, Root Mean Squared Error and R-Squared. Linear RegressionA linear regression describes the process of finding a straight line that is as close as possible to the given data points. The model then tries to minimize the squared errors. As it is assumed that the company valuation increases with better performance gradually, the linear regression is applied to the given dataset. Furthermore, as there are multiple numerous features given in the dataset for this project, it is not a simple but a multiple linear regression. As this project is set up with Python, the module statsmodels is used to perform regression and evaluate the predictive results. While there are several classes available, the ordinary least squares method was chosen as it is mostly used for linear relationships in the training data. # Linear Regressionimport pandas as pdfrom sklearn import linear_modelimport statsmodels.api as sm# with sklearnregr = linear_model.LinearRegression()regr.fit(x_train, y_train)print('Intercept: \n', regr.intercept_)print('Coefficients: \n', regr.coef_)# with statsmodelsx_train = sm.add_constant(x_train) # adding a constant model_OLS = sm.OLS(y_train, x_train).fit()#predictions = model.predict(x_test) print_model = model_OLS.summary()print(print_model) The constant (const) in the first line indicates the estimated valuation if all other variables are zero. This constant is calculated at 986.000 €. Furthermore, the Revenue coefficient is with a p-value of 0.003 statistically significant for the model. After removing one coefficient after the other, always the one with the most non-significant value, there were to coefficients clearly driving the model: Revenue and headcount with a p-value of 0.000 and 0.004. Poly RegressionThe polynomial regression is performed by two steps. First of all, the data has to be transformed into a polynomial. A degree of one would create a simple linear regression. To create a polynomial regression the degree must be higher than one and chosen carefully, because if the value is chosen too high, the model may be overfitted. The final code for the polynomial regression looks the following: # Poly Regressionimport operatorimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_errorfrom sklearn.preprocessing import PolynomialFeatures# with sklearnpolynomial_features= PolynomialFeatures(degree=2)x_poly = polynomial_features.fit_transform(x_train)model = LinearRegression()model.fit(x_poly, y_train)y_poly_pred = model.predict(x_poly)MAE = mean_absolute_error(y_train,y_poly_pred)rmse = np.sqrt(mean_squared_error(y_train,y_poly_pred))r2 = r2_score(y_train,y_poly_pred)print(MAE)print(rmse)print(r2) Neural Network Regression Neural networks are well known for outperforming traditional learning algorithms, especially when it comes to image recognition or classification problems. Applying neural networks to regression problems is not found that often in existing literature. This probably results from the fact that a neural network for regression may be considered as over engineered for a regression, which is in many cases simpler and does not require that much computational power. But on the other hand, it is also argued that deep neural networks mimic the human brain and therefore perform better at complex tasks. In conclusion to the fact that the prevailing dataset is very complex and has many features, the idea is to apply a neural network for performance improvements competing with the previously applied traditional models. ## Neural Networkmodel = Sequential()model.add(Dense(256, input_dim=10, kernel_initializer='normal', activation='relu'))model.add(Dense(512, activation='relu'))model.add(Dense(512, activation='relu'))model.add(Dense(1, activation='relu'))model.summary()model.compile(loss='mse', optimizer='adam', metrics=['mse','mae']) In this specific case the model has one input layer, two hidden layers with 512 nodes and one output layer. The activation function of choice is the rectified linear unit function (ReLU). The function is widely used due and usually a good first choice due to its good performance with low computational power and its ability to not activate all Neurons at the same time. The last layer is the output layer with only one node which is supposed to do the final output. In this case the private company valuation. In this case the best results were achieved with the mean squared error as loss measurement and the optimiser adam. In contrast to the stochastic gradient descent optimisation, the adam optimiser manages the learning rate for each parameter (weight) in the network and individually adjusts them. The final neural network model looks the following: Evaluating Model PerformanceR2, MAE and RMSE are used determine the overall performance of each model and compare them. , interpreting the coefficients helps to find the drivers of a model. Before interpreting the results, it can be seen that the polynomial regression was outperforming the Neural Network Regression and the Linear Regression. Furthermore, the Revenue coefficient is with a p-value of 0.003 statistically significant for the model. After removing one coefficient after the other, always the one with the most non-significant value, there were two coefficients clearly driving the model: Revenue and headcount with a p-value of 0.000 and 0.004 The best performing machine learning model was the polynomial regression model. It had an explained variance of 28% percent which is acceptable with regards to mimicking human behaviour. Furthermore the mean error was 830k Euros and the KPI features “Revenue” and “Headcount” have statistically significant influence on the model. The underlying applied machine learning model takes only structured performance data into consideration. Important factors that usually drive a startup valuation enormously, such as management team experience, technological advantage, operating market growth and many more, are not yet considered. This also explains the moderate r-squared value. It needs to be stated that there is no standard guideline defined for the level of acceptance when it comes to r-squared - Especially when the model mimics human behaviour. The research shows that with a little amount of structured private and public company data, a simple regression model is able to produce useful valuations. To further develop the machine learning model and improve its performance, it is highly recommended to take more features into consideration as a next step. Unstructured data from the areas mentioned above in combination with additional growth indicators are very likely to boost model performance significantly. *************************************************************** Special thanks to Guillermo Falco from investory.io and Prof. Dr. Barbara Sprick from SRH Heidelberg supporting this study. *************************************************************** Articles you may enjoy reading as well: Learn How To Predict Customer Churn Generate Your Sample Dataset — A Must Have Skill For Data Scientists. Setup Your Data Environment With Docker Eliminating Churn is Growth Hacking 2.0 Misleading with Data & Statistics
[ { "code": null, "e": 622, "s": 172, "text": "Determining the valuation of an early-stage Startup is in most cases very challenging due limited historical data, little to no existing revenues, market uncertainty and many more. Traditional valuation techniques, such as Discounted Cash Flow (DCF) or Multiples (CCA), therefore often lead to inappropriate results. On the other hand, alternative valuation methods remain subject to an individual’s subjective assessment and a black box for others." }, { "code": null, "e": 1000, "s": 622, "text": "Therefore, the underlying study leverages machine learning algorithms to predict a fair, data-driven and comprehensible startup valuations. Three different data sources are merged and applied to three regression models. The regression models’ performance is compared on defined measurements and the final outcome is a continuous numeric value — the predicted startup valuation." }, { "code": null, "e": 1828, "s": 1000, "text": "In order to build a machine learning model and get significant results, it is essential to have a solid data base. In this case the final analytical data set is a combination of public and private, anonymised data sources. The study was enabled by partnering with investory.io to get access to anonymised key performance indicators, as well as cap tab le data from early-stage companies. In combination with Crunchbase it is possible to map this data to funding stages, funding rounds, locations and the team size. Last but not least we used social media data, as a previous study (“Social is the new financial”, Jin et al 2017) found a relationship between likelihood of closing an investment round and Twitter activities. At this point a big shoutout to Storyclash for access to their amazing social media analytics platform." }, { "code": null, "e": 2099, "s": 1828, "text": "Most of the effort had to be spent merging the different data sources together and cleaning them. While the investory.io data came already in a clean numeric format, Crunchbase data for example was not pulled through their API and therefor came in a very unclean format." }, { "code": null, "e": 2340, "s": 2099, "text": "In the very beginning an overview of the different tables and information was generated with a simple database client DBEAVER. After that relevant information was extracted, transformed and loaded mainly with the help of Python programming." }, { "code": null, "e": 2784, "s": 2340, "text": "As this generated countless lines of code, we will not go into every detail, but pick some examples as data normalisation below. But just to give you a brief idea: There were companies from more than 50 countries included, with various different currencies and local peculiarities. It is often said that data preparation, cleaning and transformation consumes 80% of a data scientist’s time. This statement also proves itself true in this case." }, { "code": null, "e": 2808, "s": 2784, "text": "Normalisation & Scaling" }, { "code": null, "e": 3261, "s": 2808, "text": "On important step to prepare the dataset for our machine learning algorithms was normalisation. The idea is to bring the numeric values in a common scale. This is necessary as we have headcount and revenue as two features. While revenue may take a numeric value with 6 digits, it is very unlikely that the headcount has values above 100. The features have a very different range and revenue would influence our model more only due to its higher values." }, { "code": null, "e": 3975, "s": 3261, "text": "#Data Normalizationfrom sklearn.preprocessing import MinMaxScaler#Select numerical columns which needs to be normalizedtrain_norm = x_traintest_norm = x_test# Normalize Training Data scaler = MinMaxScaler(feature_range=(0, 1))x_train_norm = scaler.fit_transform(train_norm)#Converting numpy array to dataframetraining_norm_col = pd.DataFrame(x_train_norm, index=train_norm.index, columns=train_norm.columns) x_train.update(training_norm_col)print (x_train.head())# Normalize Testing Data by using mean and SD of training setx_test_norm = scaler.transform(test_norm)testing_norm_col = pd.DataFrame(x_test_norm, index=test_norm.index, columns=test_norm.columns) x_test.update(testing_norm_col)print (x_train.head())" }, { "code": null, "e": 4192, "s": 3975, "text": "The MinMax Scaler is very sensitive to outliers. If your data has some severe outliers, please take care of that beforehand. The range of the normalized data is usually between zero and one as seen in the code above." }, { "code": null, "e": 4487, "s": 4192, "text": "Within the project there were three regression models applied to the dataset. They were chosen according to their characteristics and usual purpose of application. Each regression model was evaluated with the help of three indicators: Mean Absolute Error, Root Mean Squared Error and R-Squared." }, { "code": null, "e": 5255, "s": 4487, "text": "Linear RegressionA linear regression describes the process of finding a straight line that is as close as possible to the given data points. The model then tries to minimize the squared errors. As it is assumed that the company valuation increases with better performance gradually, the linear regression is applied to the given dataset. Furthermore, as there are multiple numerous features given in the dataset for this project, it is not a simple but a multiple linear regression. As this project is set up with Python, the module statsmodels is used to perform regression and evaluate the predictive results. While there are several classes available, the ordinary least squares method was chosen as it is mostly used for linear relationships in the training data." }, { "code": null, "e": 5712, "s": 5255, "text": "# Linear Regressionimport pandas as pdfrom sklearn import linear_modelimport statsmodels.api as sm# with sklearnregr = linear_model.LinearRegression()regr.fit(x_train, y_train)print('Intercept: \\n', regr.intercept_)print('Coefficients: \\n', regr.coef_)# with statsmodelsx_train = sm.add_constant(x_train) # adding a constant model_OLS = sm.OLS(y_train, x_train).fit()#predictions = model.predict(x_test) print_model = model_OLS.summary()print(print_model)" }, { "code": null, "e": 6176, "s": 5712, "text": "The constant (const) in the first line indicates the estimated valuation if all other variables are zero. This constant is calculated at 986.000 €. Furthermore, the Revenue coefficient is with a p-value of 0.003 statistically significant for the model. After removing one coefficient after the other, always the one with the most non-significant value, there were to coefficients clearly driving the model: Revenue and headcount with a p-value of 0.000 and 0.004." }, { "code": null, "e": 6526, "s": 6176, "text": "Poly RegressionThe polynomial regression is performed by two steps. First of all, the data has to be transformed into a polynomial. A degree of one would create a simple linear regression. To create a polynomial regression the degree must be higher than one and chosen carefully, because if the value is chosen too high, the model may be overfitted." }, { "code": null, "e": 6592, "s": 6526, "text": "The final code for the polynomial regression looks the following:" }, { "code": null, "e": 7219, "s": 6592, "text": "# Poly Regressionimport operatorimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_errorfrom sklearn.preprocessing import PolynomialFeatures# with sklearnpolynomial_features= PolynomialFeatures(degree=2)x_poly = polynomial_features.fit_transform(x_train)model = LinearRegression()model.fit(x_poly, y_train)y_poly_pred = model.predict(x_poly)MAE = mean_absolute_error(y_train,y_poly_pred)rmse = np.sqrt(mean_squared_error(y_train,y_poly_pred))r2 = r2_score(y_train,y_poly_pred)print(MAE)print(rmse)print(r2)" }, { "code": null, "e": 7245, "s": 7219, "text": "Neural Network Regression" }, { "code": null, "e": 8062, "s": 7245, "text": "Neural networks are well known for outperforming traditional learning algorithms, especially when it comes to image recognition or classification problems. Applying neural networks to regression problems is not found that often in existing literature. This probably results from the fact that a neural network for regression may be considered as over engineered for a regression, which is in many cases simpler and does not require that much computational power. But on the other hand, it is also argued that deep neural networks mimic the human brain and therefore perform better at complex tasks. In conclusion to the fact that the prevailing dataset is very complex and has many features, the idea is to apply a neural network for performance improvements competing with the previously applied traditional models." }, { "code": null, "e": 8382, "s": 8062, "text": "## Neural Networkmodel = Sequential()model.add(Dense(256, input_dim=10, kernel_initializer='normal', activation='relu'))model.add(Dense(512, activation='relu'))model.add(Dense(512, activation='relu'))model.add(Dense(1, activation='relu'))model.summary()model.compile(loss='mse', optimizer='adam', metrics=['mse','mae'])" }, { "code": null, "e": 9241, "s": 8382, "text": "In this specific case the model has one input layer, two hidden layers with 512 nodes and one output layer. The activation function of choice is the rectified linear unit function (ReLU). The function is widely used due and usually a good first choice due to its good performance with low computational power and its ability to not activate all Neurons at the same time. The last layer is the output layer with only one node which is supposed to do the final output. In this case the private company valuation. In this case the best results were achieved with the mean squared error as loss measurement and the optimiser adam. In contrast to the stochastic gradient descent optimisation, the adam optimiser manages the learning rate for each parameter (weight) in the network and individually adjusts them. The final neural network model looks the following:" }, { "code": null, "e": 9585, "s": 9241, "text": "Evaluating Model PerformanceR2, MAE and RMSE are used determine the overall performance of each model and compare them. , interpreting the coefficients helps to find the drivers of a model. Before interpreting the results, it can be seen that the polynomial regression was outperforming the Neural Network Regression and the Linear Regression." }, { "code": null, "e": 9901, "s": 9585, "text": "Furthermore, the Revenue coefficient is with a p-value of 0.003 statistically significant for the model. After removing one coefficient after the other, always the one with the most non-significant value, there were two coefficients clearly driving the model: Revenue and headcount with a p-value of 0.000 and 0.004" }, { "code": null, "e": 10232, "s": 9901, "text": "The best performing machine learning model was the polynomial regression model. It had an explained variance of 28% percent which is acceptable with regards to mimicking human behaviour. Furthermore the mean error was 830k Euros and the KPI features “Revenue” and “Headcount” have statistically significant influence on the model." }, { "code": null, "e": 10752, "s": 10232, "text": "The underlying applied machine learning model takes only structured performance data into consideration. Important factors that usually drive a startup valuation enormously, such as management team experience, technological advantage, operating market growth and many more, are not yet considered. This also explains the moderate r-squared value. It needs to be stated that there is no standard guideline defined for the level of acceptance when it comes to r-squared - Especially when the model mimics human behaviour." }, { "code": null, "e": 11221, "s": 10752, "text": "The research shows that with a little amount of structured private and public company data, a simple regression model is able to produce useful valuations. To further develop the machine learning model and improve its performance, it is highly recommended to take more features into consideration as a next step. Unstructured data from the areas mentioned above in combination with additional growth indicators are very likely to boost model performance significantly." }, { "code": null, "e": 11285, "s": 11221, "text": "***************************************************************" }, { "code": null, "e": 11409, "s": 11285, "text": "Special thanks to Guillermo Falco from investory.io and Prof. Dr. Barbara Sprick from SRH Heidelberg supporting this study." }, { "code": null, "e": 11473, "s": 11409, "text": "***************************************************************" }, { "code": null, "e": 11513, "s": 11473, "text": "Articles you may enjoy reading as well:" }, { "code": null, "e": 11549, "s": 11513, "text": "Learn How To Predict Customer Churn" }, { "code": null, "e": 11619, "s": 11549, "text": "Generate Your Sample Dataset — A Must Have Skill For Data Scientists." }, { "code": null, "e": 11659, "s": 11619, "text": "Setup Your Data Environment With Docker" }, { "code": null, "e": 11699, "s": 11659, "text": "Eliminating Churn is Growth Hacking 2.0" } ]
A Comprehensive Guide to Convolutional Neural Networks — the ELI5 way | by Sumit Saha | Towards Data Science
Artificial Intelligence has been witnessing a monumental growth in bridging the gap between the capabilities of humans and machines. Researchers and enthusiasts alike, work on numerous aspects of the field to make amazing things happen. One of many such areas is the domain of Computer Vision. The agenda for this field is to enable machines to view the world as humans do, perceive it in a similar manner and even use the knowledge for a multitude of tasks such as Image & Video recognition, Image Analysis & Classification, Media Recreation, Recommendation Systems, Natural Language Processing, etc. The advancements in Computer Vision with Deep Learning has been constructed and perfected with time, primarily over one particular algorithm — a Convolutional Neural Network. A Convolutional Neural Network (ConvNet/CNN) is a Deep Learning algorithm which can take in an input image, assign importance (learnable weights and biases) to various aspects/objects in the image and be able to differentiate one from the other. The pre-processing required in a ConvNet is much lower as compared to other classification algorithms. While in primitive methods filters are hand-engineered, with enough training, ConvNets have the ability to learn these filters/characteristics. The architecture of a ConvNet is analogous to that of the connectivity pattern of Neurons in the Human Brain and was inspired by the organization of the Visual Cortex. Individual neurons respond to stimuli only in a restricted region of the visual field known as the Receptive Field. A collection of such fields overlap to cover the entire visual area. An image is nothing but a matrix of pixel values, right? So why not just flatten the image (e.g. 3x3 image matrix into a 9x1 vector) and feed it to a Multi-Level Perceptron for classification purposes? Uh.. not really. In cases of extremely basic binary images, the method might show an average precision score while performing prediction of classes but would have little to no accuracy when it comes to complex images having pixel dependencies throughout. A ConvNet is able to successfully capture the Spatial and Temporal dependencies in an image through the application of relevant filters. The architecture performs a better fitting to the image dataset due to the reduction in the number of parameters involved and reusability of weights. In other words, the network can be trained to understand the sophistication of the image better. In the figure, we have an RGB image which has been separated by its three color planes — Red, Green, and Blue. There are a number of such color spaces in which images exist — Grayscale, RGB, HSV, CMYK, etc. You can imagine how computationally intensive things would get once the images reach dimensions, say 8K (7680×4320). The role of the ConvNet is to reduce the images into a form which is easier to process, without losing features which are critical for getting a good prediction. This is important when we are to design an architecture which is not only good at learning features but also is scalable to massive datasets. Image Dimensions = 5 (Height) x 5 (Breadth) x 1 (Number of channels, eg. RGB) In the above demonstration, the green section resembles our 5x5x1 input image, I. The element involved in carrying out the convolution operation in the first part of a Convolutional Layer is called the Kernel/Filter, K, represented in the color yellow. We have selected K as a 3x3x1 matrix. Kernel/Filter, K = 1 0 10 1 01 0 1 The Kernel shifts 9 times because of Stride Length = 1 (Non-Strided), every time performing a matrix multiplication operation between K and the portion P of the image over which the kernel is hovering. The filter moves to the right with a certain Stride Value till it parses the complete width. Moving on, it hops down to the beginning (left) of the image with the same Stride Value and repeats the process until the entire image is traversed. In the case of images with multiple channels (e.g. RGB), the Kernel has the same depth as that of the input image. Matrix Multiplication is performed between Kn and In stack ([K1, I1]; [K2, I2]; [K3, I3]) and all the results are summed with the bias to give us a squashed one-depth channel Convoluted Feature Output. The objective of the Convolution Operation is to extract the high-level features such as edges, from the input image. ConvNets need not be limited to only one Convolutional Layer. Conventionally, the first ConvLayer is responsible for capturing the Low-Level features such as edges, color, gradient orientation, etc. With added layers, the architecture adapts to the High-Level features as well, giving us a network which has the wholesome understanding of images in the dataset, similar to how we would. There are two types of results to the operation — one in which the convolved feature is reduced in dimensionality as compared to the input, and the other in which the dimensionality is either increased or remains the same. This is done by applying Valid Padding in case of the former, or Same Padding in the case of the latter. When we augment the 5x5x1 image into a 6x6x1 image and then apply the 3x3x1 kernel over it, we find that the convolved matrix turns out to be of dimensions 5x5x1. Hence the name — Same Padding. On the other hand, if we perform the same operation without padding, we are presented with a matrix which has dimensions of the Kernel (3x3x1) itself — Valid Padding. The following repository houses many such GIFs which would help you get a better understanding of how Padding and Stride Length work together to achieve results relevant to our needs. github.com Similar to the Convolutional Layer, the Pooling layer is responsible for reducing the spatial size of the Convolved Feature. This is to decrease the computational power required to process the data through dimensionality reduction. Furthermore, it is useful for extracting dominant features which are rotational and positional invariant, thus maintaining the process of effectively training of the model. There are two types of Pooling: Max Pooling and Average Pooling. Max Pooling returns the maximum value from the portion of the image covered by the Kernel. On the other hand, Average Pooling returns the average of all the values from the portion of the image covered by the Kernel. Max Pooling also performs as a Noise Suppressant. It discards the noisy activations altogether and also performs de-noising along with dimensionality reduction. On the other hand, Average Pooling simply performs dimensionality reduction as a noise suppressing mechanism. Hence, we can say that Max Pooling performs a lot better than Average Pooling. The Convolutional Layer and the Pooling Layer, together form the i-th layer of a Convolutional Neural Network. Depending on the complexities in the images, the number of such layers may be increased for capturing low-levels details even further, but at the cost of more computational power. After going through the above process, we have successfully enabled the model to understand the features. Moving on, we are going to flatten the final output and feed it to a regular Neural Network for classification purposes. Adding a Fully-Connected layer is a (usually) cheap way of learning non-linear combinations of the high-level features as represented by the output of the convolutional layer. The Fully-Connected layer is learning a possibly non-linear function in that space. Now that we have converted our input image into a suitable form for our Multi-Level Perceptron, we shall flatten the image into a column vector. The flattened output is fed to a feed-forward neural network and backpropagation applied to every iteration of training. Over a series of epochs, the model is able to distinguish between dominating and certain low-level features in images and classify them using the Softmax Classification technique. There are various architectures of CNNs available which have been key in building algorithms which power and shall power AI as a whole in the foreseeable future. Some of them have been listed below: LeNetAlexNetVGGNetGoogLeNetResNetZFNet LeNet AlexNet VGGNet GoogLeNet ResNet ZFNet GitHub Notebook — Recognising Hand Written Digits using MNIST Dataset with TensorFlow
[ { "code": null, "e": 466, "s": 172, "text": "Artificial Intelligence has been witnessing a monumental growth in bridging the gap between the capabilities of humans and machines. Researchers and enthusiasts alike, work on numerous aspects of the field to make amazing things happen. One of many such areas is the domain of Computer Vision." }, { "code": null, "e": 949, "s": 466, "text": "The agenda for this field is to enable machines to view the world as humans do, perceive it in a similar manner and even use the knowledge for a multitude of tasks such as Image & Video recognition, Image Analysis & Classification, Media Recreation, Recommendation Systems, Natural Language Processing, etc. The advancements in Computer Vision with Deep Learning has been constructed and perfected with time, primarily over one particular algorithm — a Convolutional Neural Network." }, { "code": null, "e": 1442, "s": 949, "text": "A Convolutional Neural Network (ConvNet/CNN) is a Deep Learning algorithm which can take in an input image, assign importance (learnable weights and biases) to various aspects/objects in the image and be able to differentiate one from the other. The pre-processing required in a ConvNet is much lower as compared to other classification algorithms. While in primitive methods filters are hand-engineered, with enough training, ConvNets have the ability to learn these filters/characteristics." }, { "code": null, "e": 1795, "s": 1442, "text": "The architecture of a ConvNet is analogous to that of the connectivity pattern of Neurons in the Human Brain and was inspired by the organization of the Visual Cortex. Individual neurons respond to stimuli only in a restricted region of the visual field known as the Receptive Field. A collection of such fields overlap to cover the entire visual area." }, { "code": null, "e": 2014, "s": 1795, "text": "An image is nothing but a matrix of pixel values, right? So why not just flatten the image (e.g. 3x3 image matrix into a 9x1 vector) and feed it to a Multi-Level Perceptron for classification purposes? Uh.. not really." }, { "code": null, "e": 2252, "s": 2014, "text": "In cases of extremely basic binary images, the method might show an average precision score while performing prediction of classes but would have little to no accuracy when it comes to complex images having pixel dependencies throughout." }, { "code": null, "e": 2636, "s": 2252, "text": "A ConvNet is able to successfully capture the Spatial and Temporal dependencies in an image through the application of relevant filters. The architecture performs a better fitting to the image dataset due to the reduction in the number of parameters involved and reusability of weights. In other words, the network can be trained to understand the sophistication of the image better." }, { "code": null, "e": 2843, "s": 2636, "text": "In the figure, we have an RGB image which has been separated by its three color planes — Red, Green, and Blue. There are a number of such color spaces in which images exist — Grayscale, RGB, HSV, CMYK, etc." }, { "code": null, "e": 3264, "s": 2843, "text": "You can imagine how computationally intensive things would get once the images reach dimensions, say 8K (7680×4320). The role of the ConvNet is to reduce the images into a form which is easier to process, without losing features which are critical for getting a good prediction. This is important when we are to design an architecture which is not only good at learning features but also is scalable to massive datasets." }, { "code": null, "e": 3342, "s": 3264, "text": "Image Dimensions = 5 (Height) x 5 (Breadth) x 1 (Number of channels, eg. RGB)" }, { "code": null, "e": 3633, "s": 3342, "text": "In the above demonstration, the green section resembles our 5x5x1 input image, I. The element involved in carrying out the convolution operation in the first part of a Convolutional Layer is called the Kernel/Filter, K, represented in the color yellow. We have selected K as a 3x3x1 matrix." }, { "code": null, "e": 3674, "s": 3633, "text": "Kernel/Filter, K = 1 0 10 1 01 0 1" }, { "code": null, "e": 3876, "s": 3674, "text": "The Kernel shifts 9 times because of Stride Length = 1 (Non-Strided), every time performing a matrix multiplication operation between K and the portion P of the image over which the kernel is hovering." }, { "code": null, "e": 4118, "s": 3876, "text": "The filter moves to the right with a certain Stride Value till it parses the complete width. Moving on, it hops down to the beginning (left) of the image with the same Stride Value and repeats the process until the entire image is traversed." }, { "code": null, "e": 4435, "s": 4118, "text": "In the case of images with multiple channels (e.g. RGB), the Kernel has the same depth as that of the input image. Matrix Multiplication is performed between Kn and In stack ([K1, I1]; [K2, I2]; [K3, I3]) and all the results are summed with the bias to give us a squashed one-depth channel Convoluted Feature Output." }, { "code": null, "e": 4940, "s": 4435, "text": "The objective of the Convolution Operation is to extract the high-level features such as edges, from the input image. ConvNets need not be limited to only one Convolutional Layer. Conventionally, the first ConvLayer is responsible for capturing the Low-Level features such as edges, color, gradient orientation, etc. With added layers, the architecture adapts to the High-Level features as well, giving us a network which has the wholesome understanding of images in the dataset, similar to how we would." }, { "code": null, "e": 5268, "s": 4940, "text": "There are two types of results to the operation — one in which the convolved feature is reduced in dimensionality as compared to the input, and the other in which the dimensionality is either increased or remains the same. This is done by applying Valid Padding in case of the former, or Same Padding in the case of the latter." }, { "code": null, "e": 5462, "s": 5268, "text": "When we augment the 5x5x1 image into a 6x6x1 image and then apply the 3x3x1 kernel over it, we find that the convolved matrix turns out to be of dimensions 5x5x1. Hence the name — Same Padding." }, { "code": null, "e": 5629, "s": 5462, "text": "On the other hand, if we perform the same operation without padding, we are presented with a matrix which has dimensions of the Kernel (3x3x1) itself — Valid Padding." }, { "code": null, "e": 5813, "s": 5629, "text": "The following repository houses many such GIFs which would help you get a better understanding of how Padding and Stride Length work together to achieve results relevant to our needs." }, { "code": null, "e": 5824, "s": 5813, "text": "github.com" }, { "code": null, "e": 6229, "s": 5824, "text": "Similar to the Convolutional Layer, the Pooling layer is responsible for reducing the spatial size of the Convolved Feature. This is to decrease the computational power required to process the data through dimensionality reduction. Furthermore, it is useful for extracting dominant features which are rotational and positional invariant, thus maintaining the process of effectively training of the model." }, { "code": null, "e": 6511, "s": 6229, "text": "There are two types of Pooling: Max Pooling and Average Pooling. Max Pooling returns the maximum value from the portion of the image covered by the Kernel. On the other hand, Average Pooling returns the average of all the values from the portion of the image covered by the Kernel." }, { "code": null, "e": 6861, "s": 6511, "text": "Max Pooling also performs as a Noise Suppressant. It discards the noisy activations altogether and also performs de-noising along with dimensionality reduction. On the other hand, Average Pooling simply performs dimensionality reduction as a noise suppressing mechanism. Hence, we can say that Max Pooling performs a lot better than Average Pooling." }, { "code": null, "e": 7152, "s": 6861, "text": "The Convolutional Layer and the Pooling Layer, together form the i-th layer of a Convolutional Neural Network. Depending on the complexities in the images, the number of such layers may be increased for capturing low-levels details even further, but at the cost of more computational power." }, { "code": null, "e": 7379, "s": 7152, "text": "After going through the above process, we have successfully enabled the model to understand the features. Moving on, we are going to flatten the final output and feed it to a regular Neural Network for classification purposes." }, { "code": null, "e": 7639, "s": 7379, "text": "Adding a Fully-Connected layer is a (usually) cheap way of learning non-linear combinations of the high-level features as represented by the output of the convolutional layer. The Fully-Connected layer is learning a possibly non-linear function in that space." }, { "code": null, "e": 8085, "s": 7639, "text": "Now that we have converted our input image into a suitable form for our Multi-Level Perceptron, we shall flatten the image into a column vector. The flattened output is fed to a feed-forward neural network and backpropagation applied to every iteration of training. Over a series of epochs, the model is able to distinguish between dominating and certain low-level features in images and classify them using the Softmax Classification technique." }, { "code": null, "e": 8284, "s": 8085, "text": "There are various architectures of CNNs available which have been key in building algorithms which power and shall power AI as a whole in the foreseeable future. Some of them have been listed below:" }, { "code": null, "e": 8323, "s": 8284, "text": "LeNetAlexNetVGGNetGoogLeNetResNetZFNet" }, { "code": null, "e": 8329, "s": 8323, "text": "LeNet" }, { "code": null, "e": 8337, "s": 8329, "text": "AlexNet" }, { "code": null, "e": 8344, "s": 8337, "text": "VGGNet" }, { "code": null, "e": 8354, "s": 8344, "text": "GoogLeNet" }, { "code": null, "e": 8361, "s": 8354, "text": "ResNet" }, { "code": null, "e": 8367, "s": 8361, "text": "ZFNet" } ]
Matplotlib.pyplot.semilogx() in Python - GeeksforGeeks
29 May, 2021 Data Visualization Is an important part of analyzing the data as plotting graphs helps in providing better insight and understanding of the problem. Matplotlib.pyplot is one of the most commonly used libraries to do the same. It helps in creating attractive data and is super easy to use. This function is used to visualize data in a manner that the x-axis is converted to log format. This function is particularly useful when one of the parameters is extremely large and thus stored in a compact manner initially. It supports all the keyword arguments of the plot() and matplotlib.axes.Axes.set_xscale(). The additional parameters are basex, subsx and nonposx. Syntax: Matplotlib.pyplot.semilogx(x, y, ) Parameters: Some important parameters are: x: Values on X-axis. y: Values on Y-axis. color: (optional) Color of the line or the symbol. linewidth: (optional) Width of the line. label: (optional) Specifies the label of the graph basex: (optional) The base of the x logarithm. The scalar should be larger than 1. subsx: (optional) The location of the minor xticks; None defaults to autosubs, which depend on the number of decades in the plot. nonposx: (optional) Non-positive values in x can be masked as invalid, or clipped to a very small positive number. marker: (optional) Displays the points as the mentioned symbol. markersize: (optional) Changes the size of all the markers. Return: A log-scaled plot on the x-axis. Example 1: simple plot. Python3 #import required libraryimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [1, 2, 3, 4, 5, 6]y = [100, 200, 300, 400, 500, 600] # plotting the given graphplt.semilogx(x, y, marker = ".", markersize = 15, color = "green")# plot with gridplt.grid(True) # show the plotplt.show() Output: A simple plot Example 2: Using negative and zero values in X and Y axis. Since the X-axis is involved in the logarithmic function, it is clear that the negative or the positive values would either be clipped or masked, as specified by the nonposx parameter. By default, the negative or zero values are clipped. Python3 # importing required librariesimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [-1, -2, 0]y = [5, -2, 0] # plotting the given graphplt.semilogx(x,y) # show the plotplt.show() Output: No value is plotted as all are negative x values Example 3: If symbols are used then the negative or zero values are simply removed and only the positive values are plotted. Python3 #import required libraryimport matplotlib.pyplot as plt # defining the values at X and Y axisx = [-10, 30, 0, 20, -50, 25, 29, -3 , 23, 25, 29, 31]y = [-3, 30, -10, 0, -40, 3, 8, 0, -24, 40, 43, 25] # plotting the graphplt.semilogx(x,y,'g^', color = "red") # plot with gridplt.grid(True) # set y axis labelplt.ylabel('---y---') # set x axis labelplt.xlabel('---x---') # show the plotplt.show() Output: Only positive values are plotted Example 4: If the lines are used, the values are clipped. Python3 #import required libraryimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [1, 2, -3, -4, 5, 6]y = [100, 200, 300, 400, 500, 600] # plotting the graphplt.semilogx(x, y, marker = ".", markersize = 15) # plot with gridplt.grid(True) # show the plotplt.show() Output: The values corresponding to -3 and -4 are clipped Example 5: The following subplots will make the differences more clear. Python3 #import required libraryimport matplotlib.pyplot as plt # specifying the subplotfig, axes = plt.subplots(nrows = 4, ncols = 4, figsize = (10,10)) # Or equivalently, # "plt.tight_layout()"fig.tight_layout() # subplot 1plt.subplot(2, 2, 1)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, color = "blue", linewidth = 4)# set the titleplt.title("USING LINE") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 2plt.subplot(2, 2, 2)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, 'g^', markersize = 20, color = "black")# set the titleplt.title("USING SYMBOL") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 3plt.subplot(2, 2, 3)x2 = [0.1, 10, -30]y2 = [40, -10 ,45] # plotting the given graphplt.semilogx(x2, y2, nonposx = "clip", color = "red", linewidth = 4)# set the titleplt.title("CLIPPED") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 4plt.subplot(2, 2, 4)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, nonposx = "mask", color = "green", linewidth = 4) # set the titleplt.title("MASKED") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # show the plotplt.show() Output: Differences between all the plot. Example 6: Using nonposx parameter. Masking removes the invalid values while clipping sets them to a very low possible value. The difference between clipping and masking will be more clear in the following plot. Python3 # import required libraryimport matplotlib.pyplot as plt fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,9))# Or equivalently, "plt.tight_layout()"fig.tight_layout() # subplot 1x1 = [-1, 2, 0, -3, 5, 9, 10, -3, -8, 15, 12, 0.1,0.9] y1 = [5, -2, 0, 10, 20, 30, 25, 28, 16, 25, 28, 3, 5] plt.subplot(1,2,1) # plotting the graphplt.semilogx(x1, y1, marker = ".", markersize = 20, nonposx = "clip", color = "green" ) # set the y-axis labelplt.ylabel('---y---') # set the x-axis labelplt.xlabel('---x---') # set the titleplt.title('CLIP') # plot with gridplt.grid(True) # subplot 2x2 = [-1, 2, 0, -3, 5, 9, 10, -3, -8, 15, 12, 0.1, 0.9] y2 = [5, -2, 0, 10, 20, 30, 25, 28, 16, 25, 28, 3, 5] plt.subplot(1,2,2)plt.semilogx(x2, y2, nonposx = "mask", color ="green", linewidth = 4, marker = ".", markersize = 20) # set the titleplt.title('MASK') # set the y-axis labelplt.ylabel('---y---') # set the x-axis labelplt.xlabel('---x---') # plot with gridplt.grid(True) # show the plotplt.show() Output: Difference between mask and clip Example 7: Changing the base. The base can be set as per the convenience and it should be greater than 1 to satisfy the logarithmic properties. Python3 # importing the required librariesimport numpy as npimport matplotlib.pyplot as plt # function that will# output the valuesdef function(t): return np.exp(-t)*np.sin(2*np.pi.t)/2 + np.tan(t) # define the x-axis valuest1 = np.arange(-0.01, 1.0, 0.08)t2 = np.arange(0.0, 5.0, 0.02) # subplot 1plt.figure(figsize = (10,10))plt.subplot(211) # plot the graphplt.semilogx(t1, f(t1), 'bo', t2, f(t2), 'k', color = "blue", basex = 3)# set the titleplt.title("BASE: 3") # subplot 2plt.subplot(212) # plot the graphplt.semilogx(t2, np.cos(2*np.pi*t2), 'r--', color = "brown", linewidth = 2, basex = 4) # set the titleplt.title("BASE: 4") # show the plotplt.show() Output: Changing the base Example 8: Using subsx parameter. Specifies the minor xticks on the X-axis. By default, it depends on the number of decades in the plot. Python3 # import required libraryimport matplotlib.pyplot as plt fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (10,7)) # Or equivalently, "plt.tight_layout()"fig.tight_layout() # subplot 1plt.subplot(2, 2, 1)x = [1, 11]y = [4, 6] # plot the graphplt.semilogx(x, y, marker = ".", markersize = 20, color = "green") # set the titleplt.title("Without subsx - line ") # plot with gridplt.grid(True) # subplot 2plt.subplot(2, 2, 2)x = [1, 11]y = [4, 6] # plot the graphplt.semilogx(x, y, subsx = [2, 3, 9, 10], marker = ".", markersize = 20, color = "green") # set the titleplt.title("With subsx - line ")plt.grid(True) # subplot 3plt.subplot(2, 2, 3)x = [1, 11]y = [4, 6]plt.semilogx(x, y, 'g^', marker = ".", markersize = 20, color = "blue")plt.title("Without subsx - symbol ")plt.grid(True) # subplot 4plt.subplot(2, 2, 4)x = [1, 11]y = [4, 6]plt.semilogx(x, y, 'g^', subsx=[2, 3, 9, 10], marker = ".", markersize = 20, color = "blue")plt.title("With subsx - symbol ")plt.grid(True) plt.show() Output: SUBSX parameter Summary: The X-axis is plotted in the logarithmic manner and base can be specified by defining the basex property. The base should be greater than 1 If lines are plotted then the negative or zero values are clipped by default. The mask property removes the negative/zero values while clip property sets them to a very low positive value. If the symbols are used then the negative/zero are masked by default. semilogx follows all the arguments of plot() and matplotlib.axes.Axes.set_xscale(). subsx parameter defines the minor xticks. arorakashish0911 Code_Mech Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23769, "s": 23741, "text": "\n29 May, 2021" }, { "code": null, "e": 24059, "s": 23769, "text": "Data Visualization Is an important part of analyzing the data as plotting graphs helps in providing better insight and understanding of the problem. Matplotlib.pyplot is one of the most commonly used libraries to do the same. It helps in creating attractive data and is super easy to use. " }, { "code": null, "e": 24433, "s": 24059, "text": " This function is used to visualize data in a manner that the x-axis is converted to log format. This function is particularly useful when one of the parameters is extremely large and thus stored in a compact manner initially. It supports all the keyword arguments of the plot() and matplotlib.axes.Axes.set_xscale(). The additional parameters are basex, subsx and nonposx." }, { "code": null, "e": 24477, "s": 24433, "text": "Syntax: Matplotlib.pyplot.semilogx(x, y, ) " }, { "code": null, "e": 24520, "s": 24477, "text": "Parameters: Some important parameters are:" }, { "code": null, "e": 24541, "s": 24520, "text": "x: Values on X-axis." }, { "code": null, "e": 24562, "s": 24541, "text": "y: Values on Y-axis." }, { "code": null, "e": 24613, "s": 24562, "text": "color: (optional) Color of the line or the symbol." }, { "code": null, "e": 24654, "s": 24613, "text": "linewidth: (optional) Width of the line." }, { "code": null, "e": 24705, "s": 24654, "text": "label: (optional) Specifies the label of the graph" }, { "code": null, "e": 24788, "s": 24705, "text": "basex: (optional) The base of the x logarithm. The scalar should be larger than 1." }, { "code": null, "e": 24918, "s": 24788, "text": "subsx: (optional) The location of the minor xticks; None defaults to autosubs, which depend on the number of decades in the plot." }, { "code": null, "e": 25033, "s": 24918, "text": "nonposx: (optional) Non-positive values in x can be masked as invalid, or clipped to a very small positive number." }, { "code": null, "e": 25097, "s": 25033, "text": "marker: (optional) Displays the points as the mentioned symbol." }, { "code": null, "e": 25157, "s": 25097, "text": "markersize: (optional) Changes the size of all the markers." }, { "code": null, "e": 25198, "s": 25157, "text": "Return: A log-scaled plot on the x-axis." }, { "code": null, "e": 25222, "s": 25198, "text": "Example 1: simple plot." }, { "code": null, "e": 25230, "s": 25222, "text": "Python3" }, { "code": "#import required libraryimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [1, 2, 3, 4, 5, 6]y = [100, 200, 300, 400, 500, 600] # plotting the given graphplt.semilogx(x, y, marker = \".\", markersize = 15, color = \"green\")# plot with gridplt.grid(True) # show the plotplt.show()", "e": 25562, "s": 25230, "text": null }, { "code": null, "e": 25573, "s": 25565, "text": "Output:" }, { "code": null, "e": 25589, "s": 25575, "text": "A simple plot" }, { "code": null, "e": 25650, "s": 25591, "text": "Example 2: Using negative and zero values in X and Y axis." }, { "code": null, "e": 25890, "s": 25652, "text": "Since the X-axis is involved in the logarithmic function, it is clear that the negative or the positive values would either be clipped or masked, as specified by the nonposx parameter. By default, the negative or zero values are clipped." }, { "code": null, "e": 25900, "s": 25892, "text": "Python3" }, { "code": "# importing required librariesimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [-1, -2, 0]y = [5, -2, 0] # plotting the given graphplt.semilogx(x,y) # show the plotplt.show()", "e": 26101, "s": 25900, "text": null }, { "code": null, "e": 26112, "s": 26104, "text": "Output:" }, { "code": null, "e": 26164, "s": 26114, "text": "No value is plotted as all are negative x values " }, { "code": null, "e": 26291, "s": 26166, "text": "Example 3: If symbols are used then the negative or zero values are simply removed and only the positive values are plotted." }, { "code": null, "e": 26301, "s": 26293, "text": "Python3" }, { "code": "#import required libraryimport matplotlib.pyplot as plt # defining the values at X and Y axisx = [-10, 30, 0, 20, -50, 25, 29, -3 , 23, 25, 29, 31]y = [-3, 30, -10, 0, -40, 3, 8, 0, -24, 40, 43, 25] # plotting the graphplt.semilogx(x,y,'g^', color = \"red\") # plot with gridplt.grid(True) # set y axis labelplt.ylabel('---y---') # set x axis labelplt.xlabel('---x---') # show the plotplt.show()", "e": 26711, "s": 26301, "text": null }, { "code": null, "e": 26722, "s": 26714, "text": "Output:" }, { "code": null, "e": 26757, "s": 26724, "text": "Only positive values are plotted" }, { "code": null, "e": 26817, "s": 26759, "text": "Example 4: If the lines are used, the values are clipped." }, { "code": null, "e": 26827, "s": 26819, "text": "Python3" }, { "code": "#import required libraryimport matplotlib.pyplot as plt # defining the values# at X and Y axisx = [1, 2, -3, -4, 5, 6]y = [100, 200, 300, 400, 500, 600] # plotting the graphplt.semilogx(x, y, marker = \".\", markersize = 15) # plot with gridplt.grid(True) # show the plotplt.show()", "e": 27127, "s": 26827, "text": null }, { "code": null, "e": 27139, "s": 27130, "text": "Output: " }, { "code": null, "e": 27191, "s": 27141, "text": "The values corresponding to -3 and -4 are clipped" }, { "code": null, "e": 27265, "s": 27193, "text": "Example 5: The following subplots will make the differences more clear." }, { "code": null, "e": 27275, "s": 27267, "text": "Python3" }, { "code": "#import required libraryimport matplotlib.pyplot as plt # specifying the subplotfig, axes = plt.subplots(nrows = 4, ncols = 4, figsize = (10,10)) # Or equivalently, # \"plt.tight_layout()\"fig.tight_layout() # subplot 1plt.subplot(2, 2, 1)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, color = \"blue\", linewidth = 4)# set the titleplt.title(\"USING LINE\") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 2plt.subplot(2, 2, 2)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, 'g^', markersize = 20, color = \"black\")# set the titleplt.title(\"USING SYMBOL\") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 3plt.subplot(2, 2, 3)x2 = [0.1, 10, -30]y2 = [40, -10 ,45] # plotting the given graphplt.semilogx(x2, y2, nonposx = \"clip\", color = \"red\", linewidth = 4)# set the titleplt.title(\"CLIPPED\") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # subplot 4plt.subplot(2, 2, 4)x2 = [0.1, 10, -30]y2 = [40, -10, 45] # plotting the given graphplt.semilogx(x2, y2, nonposx = \"mask\", color = \"green\", linewidth = 4) # set the titleplt.title(\"MASKED\") # set y axis labelplt.ylabel('-----------y-----------') # set x axis labelplt.xlabel('-----------x-----------') # plot with gridplt.grid(True) # show the plotplt.show()", "e": 29041, "s": 27275, "text": null }, { "code": null, "e": 29052, "s": 29044, "text": "Output:" }, { "code": null, "e": 29088, "s": 29054, "text": "Differences between all the plot." }, { "code": null, "e": 29126, "s": 29090, "text": "Example 6: Using nonposx parameter." }, { "code": null, "e": 29218, "s": 29128, "text": "Masking removes the invalid values while clipping sets them to a very low possible value." }, { "code": null, "e": 29306, "s": 29220, "text": "The difference between clipping and masking will be more clear in the following plot." }, { "code": null, "e": 29316, "s": 29308, "text": "Python3" }, { "code": "# import required libraryimport matplotlib.pyplot as plt fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,9))# Or equivalently, \"plt.tight_layout()\"fig.tight_layout() # subplot 1x1 = [-1, 2, 0, -3, 5, 9, 10, -3, -8, 15, 12, 0.1,0.9] y1 = [5, -2, 0, 10, 20, 30, 25, 28, 16, 25, 28, 3, 5] plt.subplot(1,2,1) # plotting the graphplt.semilogx(x1, y1, marker = \".\", markersize = 20, nonposx = \"clip\", color = \"green\" ) # set the y-axis labelplt.ylabel('---y---') # set the x-axis labelplt.xlabel('---x---') # set the titleplt.title('CLIP') # plot with gridplt.grid(True) # subplot 2x2 = [-1, 2, 0, -3, 5, 9, 10, -3, -8, 15, 12, 0.1, 0.9] y2 = [5, -2, 0, 10, 20, 30, 25, 28, 16, 25, 28, 3, 5] plt.subplot(1,2,2)plt.semilogx(x2, y2, nonposx = \"mask\", color =\"green\", linewidth = 4, marker = \".\", markersize = 20) # set the titleplt.title('MASK') # set the y-axis labelplt.ylabel('---y---') # set the x-axis labelplt.xlabel('---x---') # plot with gridplt.grid(True) # show the plotplt.show()", "e": 30531, "s": 29316, "text": null }, { "code": null, "e": 30542, "s": 30534, "text": "Output:" }, { "code": null, "e": 30577, "s": 30544, "text": "Difference between mask and clip" }, { "code": null, "e": 30609, "s": 30579, "text": "Example 7: Changing the base." }, { "code": null, "e": 30725, "s": 30611, "text": "The base can be set as per the convenience and it should be greater than 1 to satisfy the logarithmic properties." }, { "code": null, "e": 30735, "s": 30727, "text": "Python3" }, { "code": "# importing the required librariesimport numpy as npimport matplotlib.pyplot as plt # function that will# output the valuesdef function(t): return np.exp(-t)*np.sin(2*np.pi.t)/2 + np.tan(t) # define the x-axis valuest1 = np.arange(-0.01, 1.0, 0.08)t2 = np.arange(0.0, 5.0, 0.02) # subplot 1plt.figure(figsize = (10,10))plt.subplot(211) # plot the graphplt.semilogx(t1, f(t1), 'bo', t2, f(t2), 'k', color = \"blue\", basex = 3)# set the titleplt.title(\"BASE: 3\") # subplot 2plt.subplot(212) # plot the graphplt.semilogx(t2, np.cos(2*np.pi*t2), 'r--', color = \"brown\", linewidth = 2, basex = 4) # set the titleplt.title(\"BASE: 4\") # show the plotplt.show()", "e": 31452, "s": 30735, "text": null }, { "code": null, "e": 31463, "s": 31455, "text": "Output:" }, { "code": null, "e": 31483, "s": 31465, "text": "Changing the base" }, { "code": null, "e": 31519, "s": 31485, "text": "Example 8: Using subsx parameter." }, { "code": null, "e": 31624, "s": 31521, "text": "Specifies the minor xticks on the X-axis. By default, it depends on the number of decades in the plot." }, { "code": null, "e": 31634, "s": 31626, "text": "Python3" }, { "code": "# import required libraryimport matplotlib.pyplot as plt fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (10,7)) # Or equivalently, \"plt.tight_layout()\"fig.tight_layout() # subplot 1plt.subplot(2, 2, 1)x = [1, 11]y = [4, 6] # plot the graphplt.semilogx(x, y, marker = \".\", markersize = 20, color = \"green\") # set the titleplt.title(\"Without subsx - line \") # plot with gridplt.grid(True) # subplot 2plt.subplot(2, 2, 2)x = [1, 11]y = [4, 6] # plot the graphplt.semilogx(x, y, subsx = [2, 3, 9, 10], marker = \".\", markersize = 20, color = \"green\") # set the titleplt.title(\"With subsx - line \")plt.grid(True) # subplot 3plt.subplot(2, 2, 3)x = [1, 11]y = [4, 6]plt.semilogx(x, y, 'g^', marker = \".\", markersize = 20, color = \"blue\")plt.title(\"Without subsx - symbol \")plt.grid(True) # subplot 4plt.subplot(2, 2, 4)x = [1, 11]y = [4, 6]plt.semilogx(x, y, 'g^', subsx=[2, 3, 9, 10], marker = \".\", markersize = 20, color = \"blue\")plt.title(\"With subsx - symbol \")plt.grid(True) plt.show()", "e": 32776, "s": 31634, "text": null }, { "code": null, "e": 32787, "s": 32779, "text": "Output:" }, { "code": null, "e": 32805, "s": 32789, "text": "SUBSX parameter" }, { "code": null, "e": 32816, "s": 32807, "text": "Summary:" }, { "code": null, "e": 32958, "s": 32818, "text": "The X-axis is plotted in the logarithmic manner and base can be specified by defining the basex property. The base should be greater than 1" }, { "code": null, "e": 33036, "s": 32958, "text": "If lines are plotted then the negative or zero values are clipped by default." }, { "code": null, "e": 33147, "s": 33036, "text": "The mask property removes the negative/zero values while clip property sets them to a very low positive value." }, { "code": null, "e": 33217, "s": 33147, "text": "If the symbols are used then the negative/zero are masked by default." }, { "code": null, "e": 33301, "s": 33217, "text": "semilogx follows all the arguments of plot() and matplotlib.axes.Axes.set_xscale()." }, { "code": null, "e": 33343, "s": 33301, "text": "subsx parameter defines the minor xticks." }, { "code": null, "e": 33362, "s": 33345, "text": "arorakashish0911" }, { "code": null, "e": 33372, "s": 33362, "text": "Code_Mech" }, { "code": null, "e": 33396, "s": 33372, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 33414, "s": 33396, "text": "Python-matplotlib" }, { "code": null, "e": 33421, "s": 33414, "text": "Python" }, { "code": null, "e": 33519, "s": 33421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33528, "s": 33519, "text": "Comments" }, { "code": null, "e": 33541, "s": 33528, "text": "Old Comments" }, { "code": null, "e": 33559, "s": 33541, "text": "Python Dictionary" }, { "code": null, "e": 33594, "s": 33559, "text": "Read a file line by line in Python" }, { "code": null, "e": 33616, "s": 33594, "text": "Enumerate() in Python" }, { "code": null, "e": 33648, "s": 33616, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33678, "s": 33648, "text": "Iterate over a list in Python" }, { "code": null, "e": 33720, "s": 33678, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33763, "s": 33720, "text": "Python program to convert a list to string" }, { "code": null, "e": 33789, "s": 33763, "text": "Python String | replace()" }, { "code": null, "e": 33833, "s": 33789, "text": "Reading and Writing to text files in Python" } ]
Symmetric Tree in Python
Suppose we have one binary tree. We have to check whether the tree is a symmetric tree or not. A tree will be said to be symmetric if it is the same when we take the mirror image of it. From these two trees, the first one is symmetric, but the second one is not. To solve this, we will follow these steps. We will call following steps recursively. The function will be solve(root, root) if the node1 and node2 are empty, then return true if either node1 or node2 is empty, then return false return true when node1.val = node2.val and solve(node1.left, node2.right) and solve(node1.right, node2.left) Let us see the following implementation to get better understanding − Live Demo class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): if data is not None: temp.left = TreeNode(data) else: temp.left = TreeNode(0) break else: que.append(temp.left) if (not temp.right): if data is not None: temp.right = TreeNode(data) else: temp.right = TreeNode(0) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ return self.solve(root,root) def solve(self,node1,node2): if not node1 and not node2: return True if not node1 or not node2: return False # print(node1.val, node2.val) return node1.data == node2.data and self.solve(node1.left,node2.right) and self.solve(node1.right,node2.left) tree1 = make_tree([1,2,2,3,4,4,3]) tree2 = make_tree([1,2,2,3,4,None,3]) ob1 = Solution() print(ob1.isSymmetric(tree1)) print(ob1.isSymmetric(tree2)) tree1 = make_tree([1,2,2,3,4,4,3]) tree2 = make_tree([1,2,2,3,4,None,3]) True False
[ { "code": null, "e": 1325, "s": 1062, "text": "Suppose we have one binary tree. We have to check whether the tree is a symmetric tree or not. A tree will be said to be symmetric if it is the same when we take the mirror image of it. From these two trees, the first one is symmetric, but the second one is not." }, { "code": null, "e": 1368, "s": 1325, "text": "To solve this, we will follow these steps." }, { "code": null, "e": 1449, "s": 1368, "text": "We will call following steps recursively. The function will be solve(root, root)" }, { "code": null, "e": 1500, "s": 1449, "text": "if the node1 and node2 are empty, then return true" }, { "code": null, "e": 1553, "s": 1500, "text": "if either node1 or node2 is empty, then return false" }, { "code": null, "e": 1662, "s": 1553, "text": "return true when node1.val = node2.val and solve(node1.left, node2.right) and solve(node1.right, node2.left)" }, { "code": null, "e": 1732, "s": 1662, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1743, "s": 1732, "text": " Live Demo" }, { "code": null, "e": 3144, "s": 1743, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n if data is not None:\n temp.left = TreeNode(data)\n else:\n temp.left = TreeNode(0)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n if data is not None:\n temp.right = TreeNode(data)\n else:\n temp.right = TreeNode(0)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n return self.solve(root,root)\n def solve(self,node1,node2):\n if not node1 and not node2:\n return True\n if not node1 or not node2:\n return False\n # print(node1.val, node2.val)\n return node1.data == node2.data and\nself.solve(node1.left,node2.right) and\nself.solve(node1.right,node2.left)\ntree1 = make_tree([1,2,2,3,4,4,3])\ntree2 = make_tree([1,2,2,3,4,None,3])\nob1 = Solution()\nprint(ob1.isSymmetric(tree1))\nprint(ob1.isSymmetric(tree2))" }, { "code": null, "e": 3217, "s": 3144, "text": "tree1 = make_tree([1,2,2,3,4,4,3])\ntree2 = make_tree([1,2,2,3,4,None,3])" }, { "code": null, "e": 3228, "s": 3217, "text": "True\nFalse" } ]
Connecting to an ec2 instance in a private subnet on AWS | by Harry Daniels | Towards Data Science
If you’d like to skip ahead, all the code discussed in this post is available on my GitHub here. Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you’ve defined. A subnet is a range of IP addresses within the VPC. Subnets can be either public with a gateway to the internet or private. Instances launched in a public subnet can send outbound traffic to the internet while instances launched in the private subnet can only do so via a network address translation (NAT) gateway in a public subnet. Naturally private subnets are more secure, as the management ports aren’t exposed to the internet. Typically in a modular web application, the front end web server will reside within the public subnet while the backend database is in the private subnet. There are many reasons why connecting to instances in a private subnet is necessary: The backend database for an application resides within a private subnet and an engineer needs access to perform ad-hoc analysis. The private subnet is whitelisted against another third-party service and it’s a requirement to interact with that service. Instances within the same VPC can connect to one another via their private IP addresses, as such it is possible to connect to an instance in a private subnet from an instance in a public subnet; otherwise known as a bastion host. Amazon instances use SSH keys for authentication. As such connecting to the private instance will require a private key on the bastion host; in the same way connecting to the public instance requires a private key on your host machine, however this is extremely bad practise. Never expose your private keys to a bastion host! An alternative solution is to use SSH agent forwarding, which allows a user to connect from the bastion to another instance without storing the private key on the bastion. An SSH agent is a program that keeps track of user’s identity keys and their pass phrases and can be configured with the following commands: # Generate SSH keysssh-keygen -k mykeypair# Add the keys to your keychainssh-add -K mykeypair Once the keys have been generated and added to the keychain, it is possible to connect to the bastion instance with SSH using the -A option. This enables forwarding and lets the local agent respond to the public-key challenge when connecting to instances from your bastion. # Connect to the bastion host:ssh -A <bastion-ip-address> the next step is deploying the required infrastructure using Terraform. The infrastructure below has been deployed using Terraform; an open-source infrastructure as code software (and the best thing since sliced bread!). VPC: An Amazon VPC (virtual private cloud) is an isolated section of the AWS cloud where you can provision your infrastructure. In all likelihood your organisation will already have a VPC, if this is the case you can skip this step. Subnets: Subnets are essentially subsets of available addresses in your VPC and add an extra layer of control and security to resources in your environment. As above your organisation will probably already have subnets set up, but if not, please see below. The key differentiator between a private and public subnet is the map_public_ip_on_launch flag, if this is True, instances launched in this subnet will have a public IP address and be accessible via the internet gateway. Secondary CIDR: If all of your organisation’s IP addresses in its VPC are occupied by private subnets, a way around this is to create a secondary CIDR block and launch a public subnet in it. Internet Gateway: For a subnet to be accessible to the internet an AWS internet gateway is required. An internet gateway allows internet traffic to and from your VPC. Route table: A Route table specifies which external IP address are contactable from a subnet or internet gateway. Nat Gateway: A Nat Gateway enables instances in private subnets to connect to the internet. The Nat gateway must be deployed in the public subnet with an Elastic IP. Once the resource is created, a route table associated with the the private subnet needs to point internet-bound traffic to the NAT gateway. Security Groups: A security group acts as a virtual firewall for your instance to control incoming and outgoing traffic. The security group below enables all traffic over port 22 (SSH). Both instances in the private and public subnet require this security group. Ec2 Instances and Keys: After all the necessary infrastructure has been defined, we can set up our Ec2 instances. The instances require an AWS key-pair to authenticate access which is created below using the aws_key_pair resource and existing ssh key created earlier. Now that the infrastructure is complete the next step is to deploy. This can be achieved with the following Terraform commands in the terraform directory: terraform initterraform apply If the deployment has been successful, you’ll be able to see two new EC-2 instances in your AWS console. The SSH config file The SSH config file is a great resource for storing all your configuration for the remote machines you connect to. It is located in your home directory here: .ssh/config. The config file isn’t automatically created, so if it doesn’t exist you will have to create it. Host bastion-instance HostName <Bastion Public IP> User ubuntuHost private-instance HostName <Private IP> User ubuntu ProxyCommand ssh -q -W %h:%p bastion-instance The ProxyCommand in the private-instance tells SSH to make a connection to the bastion-instance and then establish a TCP forwarding to the private-instance. Finally, you can connect to the private instance over SSH using the command below: ssh private-instance And Voila, you’re in! I hope you enjoyed this post; if you have any questions or suggestions, or even ideas for future posts, let me know in the comments section and I’ll do my best to get back to you. Please checkout my other posts:
[ { "code": null, "e": 269, "s": 172, "text": "If you’d like to skip ahead, all the code discussed in this post is available on my GitHub here." }, { "code": null, "e": 979, "s": 269, "text": "Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you’ve defined. A subnet is a range of IP addresses within the VPC. Subnets can be either public with a gateway to the internet or private. Instances launched in a public subnet can send outbound traffic to the internet while instances launched in the private subnet can only do so via a network address translation (NAT) gateway in a public subnet. Naturally private subnets are more secure, as the management ports aren’t exposed to the internet. Typically in a modular web application, the front end web server will reside within the public subnet while the backend database is in the private subnet." }, { "code": null, "e": 1064, "s": 979, "text": "There are many reasons why connecting to instances in a private subnet is necessary:" }, { "code": null, "e": 1193, "s": 1064, "text": "The backend database for an application resides within a private subnet and an engineer needs access to perform ad-hoc analysis." }, { "code": null, "e": 1317, "s": 1193, "text": "The private subnet is whitelisted against another third-party service and it’s a requirement to interact with that service." }, { "code": null, "e": 1547, "s": 1317, "text": "Instances within the same VPC can connect to one another via their private IP addresses, as such it is possible to connect to an instance in a private subnet from an instance in a public subnet; otherwise known as a bastion host." }, { "code": null, "e": 1873, "s": 1547, "text": "Amazon instances use SSH keys for authentication. As such connecting to the private instance will require a private key on the bastion host; in the same way connecting to the public instance requires a private key on your host machine, however this is extremely bad practise. Never expose your private keys to a bastion host!" }, { "code": null, "e": 2186, "s": 1873, "text": "An alternative solution is to use SSH agent forwarding, which allows a user to connect from the bastion to another instance without storing the private key on the bastion. An SSH agent is a program that keeps track of user’s identity keys and their pass phrases and can be configured with the following commands:" }, { "code": null, "e": 2280, "s": 2186, "text": "# Generate SSH keysssh-keygen -k mykeypair# Add the keys to your keychainssh-add -K mykeypair" }, { "code": null, "e": 2554, "s": 2280, "text": "Once the keys have been generated and added to the keychain, it is possible to connect to the bastion instance with SSH using the -A option. This enables forwarding and lets the local agent respond to the public-key challenge when connecting to instances from your bastion." }, { "code": null, "e": 2612, "s": 2554, "text": "# Connect to the bastion host:ssh -A <bastion-ip-address>" }, { "code": null, "e": 2684, "s": 2612, "text": "the next step is deploying the required infrastructure using Terraform." }, { "code": null, "e": 2833, "s": 2684, "text": "The infrastructure below has been deployed using Terraform; an open-source infrastructure as code software (and the best thing since sliced bread!)." }, { "code": null, "e": 3066, "s": 2833, "text": "VPC: An Amazon VPC (virtual private cloud) is an isolated section of the AWS cloud where you can provision your infrastructure. In all likelihood your organisation will already have a VPC, if this is the case you can skip this step." }, { "code": null, "e": 3323, "s": 3066, "text": "Subnets: Subnets are essentially subsets of available addresses in your VPC and add an extra layer of control and security to resources in your environment. As above your organisation will probably already have subnets set up, but if not, please see below." }, { "code": null, "e": 3544, "s": 3323, "text": "The key differentiator between a private and public subnet is the map_public_ip_on_launch flag, if this is True, instances launched in this subnet will have a public IP address and be accessible via the internet gateway." }, { "code": null, "e": 3735, "s": 3544, "text": "Secondary CIDR: If all of your organisation’s IP addresses in its VPC are occupied by private subnets, a way around this is to create a secondary CIDR block and launch a public subnet in it." }, { "code": null, "e": 3902, "s": 3735, "text": "Internet Gateway: For a subnet to be accessible to the internet an AWS internet gateway is required. An internet gateway allows internet traffic to and from your VPC." }, { "code": null, "e": 4016, "s": 3902, "text": "Route table: A Route table specifies which external IP address are contactable from a subnet or internet gateway." }, { "code": null, "e": 4323, "s": 4016, "text": "Nat Gateway: A Nat Gateway enables instances in private subnets to connect to the internet. The Nat gateway must be deployed in the public subnet with an Elastic IP. Once the resource is created, a route table associated with the the private subnet needs to point internet-bound traffic to the NAT gateway." }, { "code": null, "e": 4586, "s": 4323, "text": "Security Groups: A security group acts as a virtual firewall for your instance to control incoming and outgoing traffic. The security group below enables all traffic over port 22 (SSH). Both instances in the private and public subnet require this security group." }, { "code": null, "e": 4854, "s": 4586, "text": "Ec2 Instances and Keys: After all the necessary infrastructure has been defined, we can set up our Ec2 instances. The instances require an AWS key-pair to authenticate access which is created below using the aws_key_pair resource and existing ssh key created earlier." }, { "code": null, "e": 5009, "s": 4854, "text": "Now that the infrastructure is complete the next step is to deploy. This can be achieved with the following Terraform commands in the terraform directory:" }, { "code": null, "e": 5039, "s": 5009, "text": "terraform initterraform apply" }, { "code": null, "e": 5144, "s": 5039, "text": "If the deployment has been successful, you’ll be able to see two new EC-2 instances in your AWS console." }, { "code": null, "e": 5164, "s": 5144, "text": "The SSH config file" }, { "code": null, "e": 5431, "s": 5164, "text": "The SSH config file is a great resource for storing all your configuration for the remote machines you connect to. It is located in your home directory here: .ssh/config. The config file isn’t automatically created, so if it doesn’t exist you will have to create it." }, { "code": null, "e": 5605, "s": 5431, "text": "Host bastion-instance HostName <Bastion Public IP> User ubuntuHost private-instance HostName <Private IP> User ubuntu ProxyCommand ssh -q -W %h:%p bastion-instance" }, { "code": null, "e": 5762, "s": 5605, "text": "The ProxyCommand in the private-instance tells SSH to make a connection to the bastion-instance and then establish a TCP forwarding to the private-instance." }, { "code": null, "e": 5845, "s": 5762, "text": "Finally, you can connect to the private instance over SSH using the command below:" }, { "code": null, "e": 5866, "s": 5845, "text": "ssh private-instance" }, { "code": null, "e": 5888, "s": 5866, "text": "And Voila, you’re in!" }, { "code": null, "e": 6068, "s": 5888, "text": "I hope you enjoyed this post; if you have any questions or suggestions, or even ideas for future posts, let me know in the comments section and I’ll do my best to get back to you." } ]
Count of rotations required to generate a sorted array - GeeksforGeeks
10 Jun, 2021 Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3} Output: 2 Explanation: Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2} Output: 1 Explanation: Sorted array {1, 2, 2, 2, 2} after 1 anti-clockwise rotations. Naive Approach:To solve the problem mentioned above the first observation is if we have n elements in the array then after sorting, the largest element is at (n – 1)th position. After k number of anti-clockwise rotations, the largest element will be at index (k – 1) (kth element from start). Another thing to note here is that, after rotation, the next element of the largest element will always be the smallest element, (unless the largest element is at last index, possible if there was no rotation). Hence, Number of rotations (k) = index of smallest element (k) in the array Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the// count of rotations#include <bits/stdc++.h>using namespace std; // Function to return the count// of rotationsint countRotation(int arr[], int n){ for(int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codeint main(){ int arr1[] = { 4, 5, 1, 2, 3 }; int n = sizeof(arr1) / sizeof(int); cout << countRotation(arr1, n);} // This code is contributed by jrishabh99 // Java Program to find the// count of rotationspublic class GFG { // Function to return the count of // rotations public static int countRotation(int[] arr, int n) { for (int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0; } // Driver Code public static void main(String[] args) { int[] arr1 = { 4, 5, 1, 2, 3 }; System.out.println( countRotation( arr1, arr1.length)); }} # Python3 program to find the# count of rotations # Function to return the count# of rotationsdef countRotation(arr, n): for i in range (1, n): # Find the smallest element if (arr[i] < arr[i - 1]): # Return its index return i # If array is not # rotated at all return 0 # Driver Codeif __name__ == "__main__": arr1 = [ 4, 5, 1, 2, 3 ] n = len(arr1) print(countRotation(arr1, n)) # This code is contributed by chitranayal // C# program to find the count of rotationsusing System;class GFG{ // Function to return the count of// rotationspublic static int countRotation(int[] arr, int n){ for(int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codepublic static void Main(String[] args){ int[] arr1 = { 4, 5, 1, 2, 3 }; Console.WriteLine(countRotation(arr1, arr1.Length));}} // This code is contributed by gauravrajput1 <script> // JavaScript program to find the// count of rotations // Function to return the count of// rotationsfunction countRotation(arr, n){ for(let i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codelet arr1 = [ 4, 5, 1, 2, 3 ]; document.write(countRotation( arr1, arr1.length)); // This code is contributed by sanjoy_62 </script> 2 Time Complexity: O(N) Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, we will use Binary Search. We can notice that, after being sorted and rotated, the given array is divided into two halves with non-decreasing elements, which is the only pre-requisite for binary search. Perform a recursive binary search in the array to find the index of the smallest element. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to return the// count of rotationsint countRotation(int arr[], int low, int high){ // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // The next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver code int main(){ int arr1[] = { 4, 5, 1, 2, 3 }; int N = sizeof(arr1) / sizeof(arr1[0]); cout << countRotation(arr1, 0, N - 1); return 0;} // This code is contributed by divyeshrabadiya07 // Java Program to implement// the above approach public class GFG { // Function to return the // count of rotations public static int countRotation(int[] arr, int low, int high) { // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // the next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; } } // Driver Program public static void main(String[] args) { int[] arr1 = { 4, 5, 1, 2, 3 }; System.out.println( countRotation( arr1, 0, arr1.length - 1)); }} # Python3 program to implement the# above approach # Function to return the# count of rotationsdef countRotation(arr, low, high): # If array is not rotated if (low > high): return 0 mid = low + (high - low) // 2 # Check if current element is # greater than the next # element if (mid < high and arr[mid] > arr[mid + 1]): # The next element is # the smallest return mid + 1 # Check if current element is # smaller than it's previous # element if (mid > low and arr[mid] < arr[mid - 1]): # Current element is # the smallest return mid # Check if current element is # greater than lower bound if (arr[mid] > arr[low]): # The sequence is increasing # so far # Search for smallest # element on the right # subarray return countRotation(arr, mid + 1, high) if (arr[mid] < arr[high]): # Smallest element lies on the # left subarray return countRotation(arr, low, mid - 1) else: # Search for the smallest # element on both subarrays rightIndex = countRotation(arr, mid + 1, high) leftIndex = countRotation(arr, low, mid - 1) if (rightIndex == 0): return leftIndex return rightIndex # Driver codeif __name__ == '__main__': arr1 = [ 4, 5, 1, 2, 3 ] N = len(arr1) print(countRotation(arr1, 0, N - 1)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System; class GFG{ // Function to return the// count of rotationspublic static int countRotation(int[] arr, int low, int high){ // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // The next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver codepublic static void Main(String[] args){ int[] arr1 = { 4, 5, 1, 2, 3 }; Console.WriteLine(countRotation(arr1, 0, arr1.Length - 1));}} // This code is contributed by 29AjayKumar <script>// Javascript Program to implement// the above approach // Function to return the // count of rotationsfunction countRotation(arr,low,high){ // If array is not rotated if (low > high) { return 0; } let mid = low + Math.floor((high - low) / 2); // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // the next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays let rightIndex = countRotation(arr, mid + 1, high); let leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver Programlet arr1=[4, 5, 1, 2, 3 ];document.write( countRotation( arr1, 0, arr1.length - 1)); // This code is contributed by avanitrachhadiya2155</script> 2 Time Complexity: O(N) The complexity will be O(logN) for an array without duplicates. But if the array contains duplicates, then it will recursively call the search for both halves. So the worst-case complexity will be O(N). Auxiliary Space:O(N) At worst case, the recursion call stack will have N/2 recursion calls at a time. GauravRajput1 jrishabh99 divyeshrabadiya07 ukasp 29AjayKumar mohit kumar 29 sanjoy_62 avanitrachhadiya2155 Binary Search rotation Arrays Recursion Searching Arrays Searching Recursion Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 25522, "s": 25494, "text": "\n10 Jun, 2021" }, { "code": null, "e": 25649, "s": 25522, "text": "Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples:" }, { "code": null, "e": 25766, "s": 25649, "text": "Input: arr[] = {4, 5, 1, 2, 3} Output: 2 Explanation: Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations." }, { "code": null, "e": 25883, "s": 25766, "text": "Input: arr[] = {2, 1, 2, 2, 2} Output: 1 Explanation: Sorted array {1, 2, 2, 2, 2} after 1 anti-clockwise rotations." }, { "code": null, "e": 26394, "s": 25883, "text": "Naive Approach:To solve the problem mentioned above the first observation is if we have n elements in the array then after sorting, the largest element is at (n – 1)th position. After k number of anti-clockwise rotations, the largest element will be at index (k – 1) (kth element from start). Another thing to note here is that, after rotation, the next element of the largest element will always be the smallest element, (unless the largest element is at last index, possible if there was no rotation). Hence," }, { "code": null, "e": 26463, "s": 26394, "text": "Number of rotations (k) = index of smallest element (k) in the array" }, { "code": null, "e": 26514, "s": 26463, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26518, "s": 26514, "text": "C++" }, { "code": null, "e": 26523, "s": 26518, "text": "Java" }, { "code": null, "e": 26531, "s": 26523, "text": "Python3" }, { "code": null, "e": 26534, "s": 26531, "text": "C#" }, { "code": null, "e": 26545, "s": 26534, "text": "Javascript" }, { "code": "// C++ program to find the// count of rotations#include <bits/stdc++.h>using namespace std; // Function to return the count// of rotationsint countRotation(int arr[], int n){ for(int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codeint main(){ int arr1[] = { 4, 5, 1, 2, 3 }; int n = sizeof(arr1) / sizeof(int); cout << countRotation(arr1, n);} // This code is contributed by jrishabh99", "e": 27146, "s": 26545, "text": null }, { "code": "// Java Program to find the// count of rotationspublic class GFG { // Function to return the count of // rotations public static int countRotation(int[] arr, int n) { for (int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0; } // Driver Code public static void main(String[] args) { int[] arr1 = { 4, 5, 1, 2, 3 }; System.out.println( countRotation( arr1, arr1.length)); }}", "e": 27847, "s": 27146, "text": null }, { "code": "# Python3 program to find the# count of rotations # Function to return the count# of rotationsdef countRotation(arr, n): for i in range (1, n): # Find the smallest element if (arr[i] < arr[i - 1]): # Return its index return i # If array is not # rotated at all return 0 # Driver Codeif __name__ == \"__main__\": arr1 = [ 4, 5, 1, 2, 3 ] n = len(arr1) print(countRotation(arr1, n)) # This code is contributed by chitranayal", "e": 28367, "s": 27847, "text": null }, { "code": "// C# program to find the count of rotationsusing System;class GFG{ // Function to return the count of// rotationspublic static int countRotation(int[] arr, int n){ for(int i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codepublic static void Main(String[] args){ int[] arr1 = { 4, 5, 1, 2, 3 }; Console.WriteLine(countRotation(arr1, arr1.Length));}} // This code is contributed by gauravrajput1", "e": 29029, "s": 28367, "text": null }, { "code": "<script> // JavaScript program to find the// count of rotations // Function to return the count of// rotationsfunction countRotation(arr, n){ for(let i = 1; i < n; i++) { // Find the smallest element if (arr[i] < arr[i - 1]) { // Return its index return i; } } // If array is not // rotated at all return 0;} // Driver Codelet arr1 = [ 4, 5, 1, 2, 3 ]; document.write(countRotation( arr1, arr1.length)); // This code is contributed by sanjoy_62 </script>", "e": 29586, "s": 29029, "text": null }, { "code": null, "e": 29588, "s": 29586, "text": "2" }, { "code": null, "e": 29634, "s": 29590, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 29979, "s": 29634, "text": "Efficient Approach: To optimize the above approach, we will use Binary Search. We can notice that, after being sorted and rotated, the given array is divided into two halves with non-decreasing elements, which is the only pre-requisite for binary search. Perform a recursive binary search in the array to find the index of the smallest element." }, { "code": null, "e": 30030, "s": 29979, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30034, "s": 30030, "text": "C++" }, { "code": null, "e": 30039, "s": 30034, "text": "Java" }, { "code": null, "e": 30047, "s": 30039, "text": "Python3" }, { "code": null, "e": 30050, "s": 30047, "text": "C#" }, { "code": null, "e": 30061, "s": 30050, "text": "Javascript" }, { "code": "// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to return the// count of rotationsint countRotation(int arr[], int low, int high){ // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // The next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver code int main(){ int arr1[] = { 4, 5, 1, 2, 3 }; int N = sizeof(arr1) / sizeof(arr1[0]); cout << countRotation(arr1, 0, N - 1); return 0;} // This code is contributed by divyeshrabadiya07", "e": 31993, "s": 30061, "text": null }, { "code": "// Java Program to implement// the above approach public class GFG { // Function to return the // count of rotations public static int countRotation(int[] arr, int low, int high) { // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // the next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; } } // Driver Program public static void main(String[] args) { int[] arr1 = { 4, 5, 1, 2, 3 }; System.out.println( countRotation( arr1, 0, arr1.length - 1)); }}", "e": 34247, "s": 31993, "text": null }, { "code": "# Python3 program to implement the# above approach # Function to return the# count of rotationsdef countRotation(arr, low, high): # If array is not rotated if (low > high): return 0 mid = low + (high - low) // 2 # Check if current element is # greater than the next # element if (mid < high and arr[mid] > arr[mid + 1]): # The next element is # the smallest return mid + 1 # Check if current element is # smaller than it's previous # element if (mid > low and arr[mid] < arr[mid - 1]): # Current element is # the smallest return mid # Check if current element is # greater than lower bound if (arr[mid] > arr[low]): # The sequence is increasing # so far # Search for smallest # element on the right # subarray return countRotation(arr, mid + 1, high) if (arr[mid] < arr[high]): # Smallest element lies on the # left subarray return countRotation(arr, low, mid - 1) else: # Search for the smallest # element on both subarrays rightIndex = countRotation(arr, mid + 1, high) leftIndex = countRotation(arr, low, mid - 1) if (rightIndex == 0): return leftIndex return rightIndex # Driver codeif __name__ == '__main__': arr1 = [ 4, 5, 1, 2, 3 ] N = len(arr1) print(countRotation(arr1, 0, N - 1)) # This code is contributed by mohit kumar 29", "e": 35833, "s": 34247, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to return the// count of rotationspublic static int countRotation(int[] arr, int low, int high){ // If array is not rotated if (low > high) { return 0; } int mid = low + (high - low) / 2; // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // The next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays int rightIndex = countRotation(arr, mid + 1, high); int leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver codepublic static void Main(String[] args){ int[] arr1 = { 4, 5, 1, 2, 3 }; Console.WriteLine(countRotation(arr1, 0, arr1.Length - 1));}} // This code is contributed by 29AjayKumar", "e": 37839, "s": 35833, "text": null }, { "code": "<script>// Javascript Program to implement// the above approach // Function to return the // count of rotationsfunction countRotation(arr,low,high){ // If array is not rotated if (low > high) { return 0; } let mid = low + Math.floor((high - low) / 2); // Check if current element is // greater than the next // element if (mid < high && arr[mid] > arr[mid + 1]) { // the next element is // the smallest return mid + 1; } // Check if current element is // smaller than it's previous // element if (mid > low && arr[mid] < arr[mid - 1]) { // Current element is // the smallest return mid; } // Check if current element is // greater than lower bound if (arr[mid] > arr[low]) { // The sequence is increasing // so far // Search for smallest // element on the right // subarray return countRotation(arr, mid + 1, high); } if (arr[mid] < arr[high]) { // Smallest element lies on the // left subarray return countRotation(arr, low, mid - 1); } else { // Search for the smallest // element on both subarrays let rightIndex = countRotation(arr, mid + 1, high); let leftIndex = countRotation(arr, low, mid - 1); if (rightIndex == 0) { return leftIndex; } return rightIndex; }} // Driver Programlet arr1=[4, 5, 1, 2, 3 ];document.write( countRotation( arr1, 0, arr1.length - 1)); // This code is contributed by avanitrachhadiya2155</script>", "e": 40009, "s": 37839, "text": null }, { "code": null, "e": 40011, "s": 40009, "text": "2" }, { "code": null, "e": 40238, "s": 40013, "text": "Time Complexity: O(N) The complexity will be O(logN) for an array without duplicates. But if the array contains duplicates, then it will recursively call the search for both halves. So the worst-case complexity will be O(N)." }, { "code": null, "e": 40341, "s": 40238, "text": "Auxiliary Space:O(N) At worst case, the recursion call stack will have N/2 recursion calls at a time. " }, { "code": null, "e": 40355, "s": 40341, "text": "GauravRajput1" }, { "code": null, "e": 40366, "s": 40355, "text": "jrishabh99" }, { "code": null, "e": 40384, "s": 40366, "text": "divyeshrabadiya07" }, { "code": null, "e": 40390, "s": 40384, "text": "ukasp" }, { "code": null, "e": 40402, "s": 40390, "text": "29AjayKumar" }, { "code": null, "e": 40417, "s": 40402, "text": "mohit kumar 29" }, { "code": null, "e": 40427, "s": 40417, "text": "sanjoy_62" }, { "code": null, "e": 40448, "s": 40427, "text": "avanitrachhadiya2155" }, { "code": null, "e": 40462, "s": 40448, "text": "Binary Search" }, { "code": null, "e": 40471, "s": 40462, "text": "rotation" }, { "code": null, "e": 40478, "s": 40471, "text": "Arrays" }, { "code": null, "e": 40488, "s": 40478, "text": "Recursion" }, { "code": null, "e": 40498, "s": 40488, "text": "Searching" }, { "code": null, "e": 40505, "s": 40498, "text": "Arrays" }, { "code": null, "e": 40515, "s": 40505, "text": "Searching" }, { "code": null, "e": 40525, "s": 40515, "text": "Recursion" }, { "code": null, "e": 40539, "s": 40525, "text": "Binary Search" }, { "code": null, "e": 40637, "s": 40539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40705, "s": 40637, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40753, "s": 40705, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 40797, "s": 40753, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40829, "s": 40797, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40852, "s": 40829, "text": "Introduction to Arrays" }, { "code": null, "e": 40912, "s": 40852, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40997, "s": 40912, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 41007, "s": 40997, "text": "Recursion" }, { "code": null, "e": 41034, "s": 41007, "text": "Program for Tower of Hanoi" } ]
How can I select every alternative row and display in descending order in SQL?
To fetch every alternative row, use MOD() under WHERE. Then use ORDER BY DESC to display the result in descending order − select *from yourTableName where mod(yourColumnName,2)=1 order by yourColumnName DESC; Let us first create a table − mysql> create table DemoTable ( UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(40), ClientAge int ); Query OK, 0 rows affected (1.02 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(ClientName,ClientAge) values('Chris',34); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Tom',45); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Sam',36); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Carol',42); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('David',38); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Chris | 34 | | 2 | Tom | 45 | | 3 | Sam | 36 | | 4 | Carol | 42 | | 5 | David | 38 | +----------+------------+-----------+ 5 rows in set (0.00 sec) Let us now select every alternative row and display in descending order − mysql> select *from DemoTable where mod(UniqueId,2)=1 order by UniqueId DESC; This will produce the following output − +----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 5 | David | 38 | | 3 | Sam | 36 | | 1 | Chris | 34 | +----------+------------+-----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": "To fetch every alternative row, use MOD() under WHERE. Then use ORDER BY DESC to display the result in descending order −" }, { "code": null, "e": 1271, "s": 1184, "text": "select *from yourTableName where mod(yourColumnName,2)=1 order by yourColumnName DESC;" }, { "code": null, "e": 1301, "s": 1271, "text": "Let us first create a table −" }, { "code": null, "e": 1470, "s": 1301, "text": "mysql> create table DemoTable\n(\n UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientName varchar(40),\n ClientAge int\n);\nQuery OK, 0 rows affected (1.02 sec)" }, { "code": null, "e": 1526, "s": 1470, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2057, "s": 1526, "text": "mysql> insert into DemoTable(ClientName,ClientAge) values('Chris',34);\nQuery OK, 1 row affected (0.47 sec)\nmysql> insert into DemoTable(ClientName,ClientAge) values('Tom',45);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable(ClientName,ClientAge) values('Sam',36);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable(ClientName,ClientAge) values('Carol',42);\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable(ClientName,ClientAge) values('David',38);\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2117, "s": 2057, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2148, "s": 2117, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2189, "s": 2148, "text": "This will produce the following output −" }, { "code": null, "e": 2556, "s": 2189, "text": "+----------+------------+-----------+\n| UniqueId | ClientName | ClientAge |\n+----------+------------+-----------+\n| 1 | Chris | 34 |\n| 2 | Tom | 45 |\n| 3 | Sam | 36 |\n| 4 | Carol | 42 |\n| 5 | David | 38 |\n+----------+------------+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2630, "s": 2556, "text": "Let us now select every alternative row and display in descending order −" }, { "code": null, "e": 2708, "s": 2630, "text": "mysql> select *from DemoTable where mod(UniqueId,2)=1 order by UniqueId DESC;" }, { "code": null, "e": 2749, "s": 2708, "text": "This will produce the following output −" }, { "code": null, "e": 3040, "s": 2749, "text": "+----------+------------+-----------+\n| UniqueId | ClientName | ClientAge |\n+----------+------------+-----------+\n| 5 | David | 38 |\n| 3 | Sam | 36 |\n| 1 | Chris | 34 |\n+----------+------------+-----------+\n3 rows in set (0.00 sec)" } ]
How to set the height/width of a Label widget in Tkinter?
The Label widgets are used for displaying text and images in the application. The size of the label widget depends on a number of factors such as width, height, and Font-size of the Label text. The height and width define how the label widget should appear in the window. To set the height and width of the label widget, we should declare the Label widget with a variable. Instantiating the label widget with a variable allows the users to add/edit the properties of the Label widget. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Add a Label widget label=Label(win, text="How to set the height/width " "of a Label widget in Tkinter?", font=('Times 14'), width=60, height=15) label.pack() win.mainloop() Running the above code will display a window that contains a label widget within width and height.
[ { "code": null, "e": 1256, "s": 1062, "text": "The Label widgets are used for displaying text and images in the application. The size of the label widget depends on a number of factors such as width, height, and Font-size of the Label text." }, { "code": null, "e": 1547, "s": 1256, "text": "The height and width define how the label widget should appear in the window. To set the height and width of the label widget, we should declare the Label widget with a variable. Instantiating the label widget with a variable allows the users to add/edit the properties of the Label widget." }, { "code": null, "e": 1890, "s": 1547, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Add a Label widget\nlabel=Label(win, text=\"How to set the height/width \" \"of a Label widget in Tkinter?\", font=('Times 14'), width=60, height=15)\nlabel.pack()\n\nwin.mainloop()" }, { "code": null, "e": 1989, "s": 1890, "text": "Running the above code will display a window that contains a label widget within width and height." } ]
Ruby on Rails - Database Setup
Before starting with this chapter, make sure your database server is up and running. Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment. According to convention, their names should be − library_development library_production library_test You should initialize all three of them and create a user and password for them with full read and write privileges. We are using the root user ID for our application. In MySQL, we are using the root user ID for our application. The MySQL console session in which you do this looks something like − mysql> create database library_development; Query OK, 1 row affected (0.01 sec) mysql> grant all privileges on library_development.* to 'root'@'localhost' identified by 'password'; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) You can do the same thing for two more databases library_production and library_test. At this point, you need to let Rails know about the user name and password for the databases. You do this in the file database.yml, available in the library\config subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the username and password lines to reflect the permissions on the databases you've created. When you finish, it should look something like − development: adapter: mysql database: library_development username: root password: [password] host: localhost test: adapter: mysql database: library_test username: root password: [password] host: localhost production: adapter: mysql database: library_production username: root password: [password] host: localhost By default, PostgreSQL does not provide any users. We have to create new users. Use the following command to create a user with the name rubyuser. tp> sudo -u postgres createuser rubyuser -s If you want to create a password for the new user, then use the following command. tp> sudo -u postgres psql postgres=# \password rubyuser Use the following command for creating a database library_development. postgres=# CREATE DATABASE library_development OWNER rubyuser; CREATE DATABASE Use the following command for creating a database library_production. postgres=# CREATE DATABASE library_production OWNER rubyuser; CREATE DATABASE Use the following command for creating a database library_test. postgres=# CREATE DATABASE library_test OWNER rubyuser; CREATE DATABASE Press Ctrl+D to terminate PosgreSQL. At this point, you need to let Rails know the username and password for the databases. You do this in the file database.yml, available in the library\config subdirectory of Rails Application you created. This file has live configuration sections for PostgreSQL databases. In each of the sections, you need to change the username and password lines to reflect the permissions on the databases you've created. When you finish, it should look as follows − default: &default adapter: postgresql encoding: unicode development: adapter: postgresql encoding: unicode database: library_development username: rubyuser password: <Password for rubyuser> test: adapter: postgresql encoding: unicode database: library_test username: rubyuser password: <Password for rubyuser> production: adapter: postgresql encoding: unicode database: library_production username: rubyuser password: <Password for rubyuser> The next two chapters explain how to model your database tables and how to manage those using Rails Migrations. Print Add Notes Bookmark this page
[ { "code": null, "e": 2360, "s": 2103, "text": "Before starting with this chapter, make sure your database server is up and running. Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment. According to convention, their names should be −" }, { "code": null, "e": 2380, "s": 2360, "text": "library_development" }, { "code": null, "e": 2399, "s": 2380, "text": "library_production" }, { "code": null, "e": 2412, "s": 2399, "text": "library_test" }, { "code": null, "e": 2580, "s": 2412, "text": "You should initialize all three of them and create a user and password for them with full read and write privileges. We are using the root user ID for our application." }, { "code": null, "e": 2711, "s": 2580, "text": "In MySQL, we are using the root user ID for our application. The MySQL console session in which you do this looks something like −" }, { "code": null, "e": 2994, "s": 2711, "text": "mysql> create database library_development;\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> grant all privileges on library_development.*\nto 'root'@'localhost' identified by 'password';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> FLUSH PRIVILEGES;\nQuery OK, 0 rows affected (0.00 sec)\n" }, { "code": null, "e": 3080, "s": 2994, "text": "You can do the same thing for two more databases library_production and library_test." }, { "code": null, "e": 3498, "s": 3080, "text": "At this point, you need to let Rails know about the user name and password for the databases. You do this in the file database.yml, available in the library\\config subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the username and password lines to reflect the permissions on the databases you've created." }, { "code": null, "e": 3547, "s": 3498, "text": "When you finish, it should look something like −" }, { "code": null, "e": 3913, "s": 3547, "text": "development:\n adapter: mysql\n database: library_development\n username: root\n password: [password]\n host: localhost\n\t\ntest:\n adapter: mysql\n database: library_test\n username: root\n password: [password]\n host: localhost\n \nproduction:\n adapter: mysql\n database: library_production\n username: root\n password: [password]\n host: localhost\n" }, { "code": null, "e": 4060, "s": 3913, "text": "By default, PostgreSQL does not provide any users. We have to create new users. Use the following command to create a user with the name rubyuser." }, { "code": null, "e": 4105, "s": 4060, "text": "tp> sudo -u postgres createuser rubyuser -s\n" }, { "code": null, "e": 4188, "s": 4105, "text": "If you want to create a password for the new user, then use the following command." }, { "code": null, "e": 4246, "s": 4188, "text": "tp> sudo -u postgres psql\n\npostgres=# \\password rubyuser\n" }, { "code": null, "e": 4317, "s": 4246, "text": "Use the following command for creating a database library_development." }, { "code": null, "e": 4399, "s": 4317, "text": "postgres=# CREATE DATABASE library_development OWNER rubyuser; \n\nCREATE DATABASE\n" }, { "code": null, "e": 4469, "s": 4399, "text": "Use the following command for creating a database library_production." }, { "code": null, "e": 4550, "s": 4469, "text": "postgres=# CREATE DATABASE library_production OWNER rubyuser; \n\nCREATE DATABASE\n" }, { "code": null, "e": 4614, "s": 4550, "text": "Use the following command for creating a database library_test." }, { "code": null, "e": 4689, "s": 4614, "text": "postgres=# CREATE DATABASE library_test OWNER rubyuser; \n\nCREATE DATABASE\n" }, { "code": null, "e": 4726, "s": 4689, "text": "Press Ctrl+D to terminate PosgreSQL." }, { "code": null, "e": 5134, "s": 4726, "text": "At this point, you need to let Rails know the username and password for the databases. You do this in the file database.yml, available in the library\\config subdirectory of Rails Application you created. This file has live configuration sections for PostgreSQL databases. In each of the sections, you need to change the username and password lines to reflect the permissions on the databases you've created." }, { "code": null, "e": 5179, "s": 5134, "text": "When you finish, it should look as follows −" }, { "code": null, "e": 5679, "s": 5179, "text": "default: &default\n adapter: postgresql\n encoding: unicode\n \ndevelopment:\n adapter: postgresql\n encoding: unicode\n database: library_development\n username: rubyuser\n password: <Password for rubyuser>\n\ntest:\n adapter: postgresql\n encoding: unicode\n database: library_test\n username: rubyuser\n password: <Password for rubyuser>\n \nproduction:\n adapter: postgresql\n encoding: unicode\n database: library_production\n username: rubyuser\n password: <Password for rubyuser>\n" }, { "code": null, "e": 5791, "s": 5679, "text": "The next two chapters explain how to model your database tables and how to manage those using Rails Migrations." }, { "code": null, "e": 5798, "s": 5791, "text": " Print" }, { "code": null, "e": 5809, "s": 5798, "text": " Add Notes" } ]
C# - if...else Statement
An if statement can be followed by an optional else statement, which executes when the boolean expression is false. The syntax of an if...else statement in C# is − if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } If the boolean expression evaluates to true, then the if block of code is executed, otherwise else block of code is executed. using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 100; /* check the boolean condition */ if (a < 20) { /* if condition is true then print the following */ Console.WriteLine("a is less than 20"); } else { /* if condition is false then print the following */ Console.WriteLine("a is not less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − a is not less than 20; value of a is : 100 An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. The syntax of an if...else if...else statement in C# is − if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ } using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 100; /* check the boolean condition */ if (a == 10) { /* if condition is true then print the following */ Console.WriteLine("Value of a is 10"); } else if (a == 20) { /* if else if condition is true */ Console.WriteLine("Value of a is 20"); } else if (a == 30) { /* if else if condition is true */ Console.WriteLine("Value of a is 30"); } else { /* if none of the conditions is true */ Console.WriteLine("None of the values is matching"); } Console.WriteLine("Exact value of a is: {0}", a); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − None of the values is matching Exact value of a is: 100 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2386, "s": 2270, "text": "An if statement can be followed by an optional else statement, which executes when the boolean expression is false." }, { "code": null, "e": 2434, "s": 2386, "text": "The syntax of an if...else statement in C# is −" }, { "code": null, "e": 2610, "s": 2434, "text": "if(boolean_expression) {\n /* statement(s) will execute if the boolean expression is true */\n} else {\n /* statement(s) will execute if the boolean expression is false */\n}\n" }, { "code": null, "e": 2736, "s": 2610, "text": "If the boolean expression evaluates to true, then the if block of code is executed, otherwise else block of code is executed." }, { "code": null, "e": 3340, "s": 2736, "text": "using System;\n\nnamespace DecisionMaking {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if (a < 20) {\n /* if condition is true then print the following */\n Console.WriteLine(\"a is less than 20\");\n } else {\n /* if condition is false then print the following */\n Console.WriteLine(\"a is not less than 20\");\n }\n Console.WriteLine(\"value of a is : {0}\", a);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3421, "s": 3340, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3465, "s": 3421, "text": "a is not less than 20;\nvalue of a is : 100\n" }, { "code": null, "e": 3623, "s": 3465, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 3701, "s": 3623, "text": "When using if, else if, else statements there are few points to keep in mind." }, { "code": null, "e": 3773, "s": 3701, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3845, "s": 3773, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3919, "s": 3845, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3993, "s": 3919, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 4077, "s": 3993, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4161, "s": 4077, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4219, "s": 4161, "text": "The syntax of an if...else if...else statement in C# is −" }, { "code": null, "e": 4561, "s": 4219, "text": "if(boolean_expression 1) {\n /* Executes when the boolean expression 1 is true */\n} \nelse if( boolean_expression 2) {\n /* Executes when the boolean expression 2 is true */\n} \nelse if( boolean_expression 3) {\n /* Executes when the boolean expression 3 is true */\n} else {\n /* executes when the none of the above condition is true */\n}\n" }, { "code": null, "e": 5445, "s": 4561, "text": "using System;\n\nnamespace DecisionMaking {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if (a == 10) {\n /* if condition is true then print the following */\n Console.WriteLine(\"Value of a is 10\");\n } \n else if (a == 20) {\n /* if else if condition is true */\n Console.WriteLine(\"Value of a is 20\");\n } \n else if (a == 30) {\n /* if else if condition is true */\n Console.WriteLine(\"Value of a is 30\");\n } else {\n /* if none of the conditions is true */\n Console.WriteLine(\"None of the values is matching\");\n }\n Console.WriteLine(\"Exact value of a is: {0}\", a);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 5526, "s": 5445, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5583, "s": 5526, "text": "None of the values is matching\nExact value of a is: 100\n" }, { "code": null, "e": 5620, "s": 5583, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 5633, "s": 5620, "text": " Raja Biswas" }, { "code": null, "e": 5667, "s": 5633, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 5685, "s": 5667, "text": " Trevoir Williams" }, { "code": null, "e": 5718, "s": 5685, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5732, "s": 5718, "text": " Peter Jepson" }, { "code": null, "e": 5769, "s": 5732, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 5784, "s": 5769, "text": " Ebenezer Ogbu" }, { "code": null, "e": 5819, "s": 5784, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 5834, "s": 5819, "text": " Arnold Higuit" }, { "code": null, "e": 5869, "s": 5834, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5881, "s": 5869, "text": " Eric Frick" }, { "code": null, "e": 5888, "s": 5881, "text": " Print" }, { "code": null, "e": 5899, "s": 5888, "text": " Add Notes" } ]
Dart Programming - for Loop
The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. Following is the syntax of the for loop. for (initial_count_value; termination-condition; step) { //statements } void main() { var num = 5; var factorial = 1; for( var i = num ; i >= 1; i-- ) { factorial *= i ; } print(factorial); } The program code will produce the following output − 120 The for loop has three parts: the initializer (i=num), the condition ( i>=1) and the final expression (i--). The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration. Multiple assignments and final expressions can be combined in a for loop, by using the comma operator (,). For example, the following for loop prints the first eight Fibonacci numbers − void main() { for(var temp, i = 0, j = 1; j<30; temp = i, i = j, j = i + temp) { print('${j}'); } } It should produce the following output − 1 1 2 3 5 8 13 21 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2721, "s": 2525, "text": "The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array." }, { "code": null, "e": 2762, "s": 2721, "text": "Following is the syntax of the for loop." }, { "code": null, "e": 2844, "s": 2762, "text": "for (initial_count_value; termination-condition; step) { \n //statements \n} \n" }, { "code": null, "e": 2996, "s": 2844, "text": "void main() { \n var num = 5; \n var factorial = 1; \n \n for( var i = num ; i >= 1; i-- ) { \n factorial *= i ; \n } \n print(factorial); \n}" }, { "code": null, "e": 3049, "s": 2996, "text": "The program code will produce the following output −" }, { "code": null, "e": 3054, "s": 3049, "text": "120\n" }, { "code": null, "e": 3163, "s": 3054, "text": "The for loop has three parts: the initializer (i=num), the condition ( i>=1) and the final expression (i--)." }, { "code": null, "e": 3358, "s": 3163, "text": "The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration." }, { "code": null, "e": 3544, "s": 3358, "text": "Multiple assignments and final expressions can be combined in a for loop, by using the comma operator (,). For example, the following for loop prints the first eight Fibonacci numbers −" }, { "code": null, "e": 3661, "s": 3544, "text": "void main() { \n for(var temp, i = 0, j = 1; j<30; temp = i, i = j, j = i + temp) { \n print('${j}'); \n } \n} " }, { "code": null, "e": 3702, "s": 3661, "text": "It should produce the following output −" }, { "code": null, "e": 3727, "s": 3702, "text": "1 \n1 \n2 \n3 \n5\n8 \n13 \n21\n" }, { "code": null, "e": 3762, "s": 3727, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3782, "s": 3762, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3815, "s": 3782, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3835, "s": 3815, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3868, "s": 3835, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3885, "s": 3868, "text": " Frahaan Hussain" }, { "code": null, "e": 3920, "s": 3885, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3937, "s": 3920, "text": " Frahaan Hussain" }, { "code": null, "e": 3972, "s": 3937, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3992, "s": 3972, "text": " Pranjal Srivastava" }, { "code": null, "e": 4025, "s": 3992, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 4045, "s": 4025, "text": " Pranjal Srivastava" }, { "code": null, "e": 4052, "s": 4045, "text": " Print" }, { "code": null, "e": 4063, "s": 4052, "text": " Add Notes" } ]
How to work with Camera in an Android App using Kotlin?
This example demonstrates how to work with Camera in an Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Take a Photo" /> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@+id/button" android:layout_alignParentTop="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.widget.Button import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { private val cameraRequest = 1888 lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), cameraRequest) imageView = findViewById(R.id.imageView) val photoButton: Button = findViewById(R.id.button) photoButton.setOnClickListener { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(cameraIntent, cameraRequest) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == cameraRequest) { val photo: Bitmap = data?.extras?.get("data") as Bitmap imageView.setImageBitmap(photo) } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the 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": 1144, "s": 1062, "text": "This example demonstrates how to work with Camera in an Android App using Kotlin." }, { "code": null, "e": 1273, "s": 1144, "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": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2067, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"Take a Photo\" />\n<ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_above=\"@+id/button\"\n android:layout_alignParentTop=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2122, "s": 2067, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3611, "s": 2122, "text": "import android.Manifest\nimport android.content.Intent\nimport android.content.pm.PackageManager\nimport android.graphics.Bitmap\nimport android.os.Bundle\nimport android.provider.MediaStore\nimport android.widget.Button\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.app.ActivityCompat\nimport androidx.core.content.ContextCompat\nclass MainActivity : AppCompatActivity() {\n private val cameraRequest = 1888\n lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CAMERA)\n == PackageManager.PERMISSION_DENIED)\n ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), cameraRequest)\n imageView = findViewById(R.id.imageView)\n val photoButton: Button = findViewById(R.id.button)\n photoButton.setOnClickListener {\n val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)\n startActivityForResult(cameraIntent, cameraRequest)\n }\n }\n override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n if (requestCode == cameraRequest) {\n val photo: Bitmap = data?.extras?.get(\"data\") as Bitmap\n imageView.setImageBitmap(photo)\n }\n }\n}" }, { "code": null, "e": 3666, "s": 3611, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4337, "s": 3666, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4685, "s": 4337, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Iterative Initial Centroid Search via Sampling for k-Means Clustering | by Matthew Mayo | Towards Data Science
In this post, we will look at using an iterative approach to searching for a better set of initial centroids for k-means clustering, and will do so by performing this process on a sample of our full dataset. What do we mean by “better?” Since k-means clustering aims to converge on an optimal set of cluster centers (centroids) and cluster membership based on distance from these centroids via successive iterations, it is intuitive that the more optimal the positioning of these initial centroids, the fewer iterations of the k-means clustering algorithms will be required for convergence. Therefore, thinking about ways to find a better set of initial centroid positions is a valid approach to optimizing the k-means clustering process. What we will do differently, specifically, is to draw a sample of data from our full dataset, and run short runs of of the k-means clustering algorithm on it (not to convergence), short runs which will include, out of necessity, the centroid initialization process. We will repeat these short runs with a number of randomly initialized centroids, and will track the improvement to the measurement metric — within-cluster sum-of-squares — for determining goodness of cluster membership (or, at least, one of the valid metrics for measuring this). The final centroids associated with the random centroid initialization iteration process which provide the lowest inertia is the set of centroids which we will carry forward to our full dataset clustering process. The hope is that this up-front work will lead to a better set of initial centroids for our full clustering process, and, hence, a lesser number of k-means clustering iterations and, ultimately, less time required to fully cluster a dataset. This would obviously not be the only method of optimizing centroid initialization. In the past we have discussed the naive sharding centroid initialization method, a deterministic method for optimal centroid initialization. Other forms of modifications to the k-means clustering algorithm take different approaches to this problem as well (see k-means++ for comparison). This post will approach our task as follows: prepare the data prepare our sample perform centroid initialization search iterations to determine our “best” collection of initial centroids use results to perform clustering on full dataset A future post will perform and report comparisons of results between various approaches to centroid initialization, for a more comprehensive understanding of the practicalities of implementation. For now, however, let’s introduce and explore this particular approach to centroid initialization. For this overview, we will use the 3D road network dataset. Since this particular dataset has no missing values, and no class labels, our data preparation will primarily constitute normalization, along with dropping a column which identifies a geographical location from where the additional 3 columns worth of measurements come from, which is not useful for our task. See the dataset description for additional details. import numpy as npimport pandas as pdfrom sklearn import preprocessing# Read datasetdata = pd.read_csv('3D_spatial_network.csv', header=None)# Drop first column (not required)data.drop(labels=0, axis=1, inplace=True)# Normalize data (min/max scaling)data_arr = data.valuessc = preprocessing.MinMaxScaler()data_sc = sc.fit_transform(data_arr)data = pd.DataFrame(data_sc) Let’s check out a sampling of our data: data.sample(10) Next, we will pull our sample that will be used to find our “best” initial centroids. Let’s be clear about exactly what we are doing: first, we are pulling a single set of samples from our dataset; then, we will perform successive rounds k-means clustering on this sample data, each iteration of which will: randomly initialize k centroids and perform n iterations of the k-means clustering algorithm the initial inertia (within-cluster sum-of-squares) of each centroid will be noted, as will its final inertia, and the initial centroids which provide the greatest increase in inertia over n iterations will be chosen as our initial centroids for the full dataset clustering Finally, we will then perform full k-means clustering on the full dataset, using the initial clusters found in the previous step. 2 important points: Why not use greatest decrease in inertia? (The hope being that the initial momentum in this area will continue.) Doing so would also be a valid choice to explore (and changing a single line of code would allow for this). An arbitrary initial experimentation choice, and one which could use more investigation. However, the repetitive execution and comparison on a number of samples initially showed that the lowest inertia and greatest decrease in inertia coincide a great majority of the time, and so the decision may, in fact, be arbitrary, but also inconsequential in practice.Of particular clarification, we are not sampling multiple times from our dataset (e.g. once from our dataset for each iteration of centroid initialization). We are sampling once for all iterations of a single centroid initialization search. One sample, from which we will randomly derive initial centroids many times. Contrast this with the idea of repetitive sampling, once for each centroid initialization iteration. Why not use greatest decrease in inertia? (The hope being that the initial momentum in this area will continue.) Doing so would also be a valid choice to explore (and changing a single line of code would allow for this). An arbitrary initial experimentation choice, and one which could use more investigation. However, the repetitive execution and comparison on a number of samples initially showed that the lowest inertia and greatest decrease in inertia coincide a great majority of the time, and so the decision may, in fact, be arbitrary, but also inconsequential in practice. Of particular clarification, we are not sampling multiple times from our dataset (e.g. once from our dataset for each iteration of centroid initialization). We are sampling once for all iterations of a single centroid initialization search. One sample, from which we will randomly derive initial centroids many times. Contrast this with the idea of repetitive sampling, once for each centroid initialization iteration. Below, we set: sample size as a ratio of our full dataset random state for reproducibility number of clusters (k) for our dataset number of iterations (n) for our k-means algorithm number of attempts at finding our best chance initial centroids while clustering on our sample dataset We then set our sample data # Some variablesSAMPLE_SIZE = 0.1RANDOM_STATE = 42NUM_CLUSTERS = 10 # kNUM_ITER = 3 # nNUM_ATTEMPTS = 5 # mdata_sample = data.sample(frac=SAMPLE_SIZE, random_state=RANDOM_STATE, replace=False)data_sample.shape Now that when we have our data sample (data_sample) we are ready to perform iterations of centroid initialization for comparison and selection. Since Scikit-learn’s k-means clustering implementation does not allow for easily obtaining centroids between clustering iterations, we have to hack the workflow a bit. While the verbose option does output some useful information in this regard directly to screen, and redirecting this output and then post-parsing it would be one approach to getting what we need, what we will do is write our own outer iteration loop to control for our n variable ourselves. This means that we need to count iterations and capture what we need between these iterations, after each clustering step has run. We will then wrap that clustering iteration loop in a centroid initialization loop, which will initialize k centroids from our sample data m times. This is the hyperparameter specific to our particular instantiation of the k-means centroid initialization process, beyond “regular” k-means. Given our above parameters, we will be clustering our dataset into 10 clusters (NUM_CLUSTERS, or k), we will run our centroid search for 3 iterations (NUM_ITER, or n), and we will attempt this with 5 random initial centroids (NUM_ATTEMPTS, or m), after which we will determine our “best” set of centroids to initialize with for full clustering (in our case, the metric is the lowest within-cluster sum-of-squares, or inertia). Prior to any clustering, however, let’s see what a sample of what a single initialization of our k-means looks like, prior to any clustering iterations. from sklearn.cluster import KMeanskm = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=1, n_init=1)#, verbose=1)km.fit(data_sample)print('Pre-clustering metrics')print('----------------------')print('Inertia:', km.inertia_)print('Centroids:', km.cluster_centers_)Pre-clustering metrics----------------------Inertia: 898.5527121490726Centroids: [[0.42360342 0.20208702 0.26294088] [0.56835267 0.34756347 0.14179924] [0.66005691 0.73147524 0.38203476] [0.23935675 0.08942105 0.11727529] [0.58630271 0.23417288 0.45793108] [0.1982982 0.11219503 0.23924021] [0.79313864 0.52773534 0.1334036 ] [0.54442269 0.60599501 0.17600424] [0.14588389 0.29821987 0.18053109] [0.73877864 0.8379479 0.12567452]] In the code below, note that we have to manually track our centroids at the start of each iteration and at the end of each iteration, given that we are managing these successive iterations ourselves. We then feed these end centroids into our next loop iteration as the initial centroids, and run for one iteration. A bit tedious, and aggravating that we can’t get this out of Scikit-learn’s implementation directly, but not difficult. final_cents = []final_inert = [] for sample in range(NUM_ATTEMPTS): print('\nCentroid attempt: ', sample) km = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=1, n_init=1)#, verbose=1) km.fit(data_sample) inertia_start = km.inertia_ intertia_end = 0 cents = km.cluster_centers_ for iter in range(NUM_ITER): km = KMeans(n_clusters=NUM_CLUSTERS, init=cents, max_iter=1, n_init=1) km.fit(data_sample) print('Iteration: ', iter) print('Inertia:', km.inertia_) print('Centroids:', km.cluster_centers_) inertia_end = km.inertia_ cents = km.cluster_centers_ final_cents.append(cents) final_inert.append(inertia_end) print('Difference between initial and final inertia: ', inertia_start-inertia_end)Centroid attempt: 0Iteration: 0Inertia: 885.1279991728289Centroids: [[0.67629991 0.54950506 0.14924545] [0.78911957 0.97469266 0.09090362] [0.61465665 0.32348368 0.11496346] [0.73784495 0.83111278 0.11263995] [0.34518925 0.37622882 0.1508636 ] [0.18220657 0.18489484 0.19303869] [0.55688642 0.35810877 0.32704852] [0.6884195 0.65798194 0.48258798] [0.62945726 0.73950354 0.21866185] [0.52282355 0.12252092 0.36251485]]Iteration: 1Inertia: 861.7158412685387Centroids: [[0.67039882 0.55769658 0.15204125] [0.78156936 0.96504069 0.09821352] [0.61009844 0.33444322 0.11527662] [0.75151713 0.79798919 0.1225065 ] [0.33091899 0.39011157 0.14788905] [0.18246521 0.18602087 0.19239602] [0.55246091 0.3507018 0.33212609] [0.68998302 0.65595219 0.48521344] [0.60291234 0.73999001 0.23322449] [0.51953015 0.12140833 0.34820443]]Iteration: 2Inertia: 839.2470653106332Centroids: [[0.65447477 0.55594052 0.15747416] [0.77412386 0.952986 0.10887517] [0.60761544 0.34326727 0.11544127] [0.77183027 0.76936972 0.12249837] [0.32151587 0.39281244 0.14797103] [0.18240552 0.18375276 0.19278224] [0.55052636 0.34639191 0.33667632] [0.691699 0.65507199 0.48648245] [0.59408317 0.73763362 0.23387334] [0.51879974 0.11982321 0.34035345]]Difference between initial and final inertia: 99.6102464383905... After this is done, let’s see how we did in our centroid search. First we check a list of our final inertias (or within-cluster sum-of-squares), looking for the lowest value. We then set the associated centroids as the initial centroids for our next step. # Get best centroids to use for full clusteringbest_cents = final_cents[final_inert.index(min(final_inert))]best_cents And here’s what those centroids look like: array([[0.55053207, 0.16588572, 0.44981164], [0.78661867, 0.77450779, 0.11764745], [0.656176 , 0.55398196, 0.4748823 ], [0.17621429, 0.13463117, 0.17132811], [0.63702675, 0.14021011, 0.18632431], [0.60838757, 0.39809226, 0.14491584], [0.43593405, 0.49377153, 0.14018223], [0.16800744, 0.34174697, 0.19503396], [0.40169376, 0.15386471, 0.23633233], [0.62151433, 0.72434071, 0.25946183]]) And now, with our best initial centroids in hand, we can run k-means clustering on our full dataset. As Scikit-learn allows us to pass in a set of initial centroids, we can exploit this by the comparatively straightforward lines below. km_full = KMeans(n_clusters=NUM_CLUSTERS, init=best_cents, max_iter=100, verbose=1, n_init=1)km_full.fit(data) This particular run of k-means converged in 13 iterations: ...start iterationdone sortingend inner loopIteration 13, inertia 7492.170210199639center shift 1.475641e-03 within tolerance 4.019354e-06 For comparison, here’s a full k-means clustering run using only randomly-initialized centroids (“regular” k-means): km_naive = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=100, verbose=1, n_init=1)km_naive.fit(data) This run took 39 iterations, with a nearly-identical inertia: ...start iterationdone sortingend inner loopIteration 39, inertia 7473.495361902045center shift 1.948248e-03 within tolerance 4.019354e-06 I leave finding the difference of execution times between the 13 iterations and 39 iterations (or similar) to the reader. Needless to say, eating up a few cycles ahead of time on a sample of data (in our case, 10% of the full dataset) saved considerable cycles in the long run, without sacrifice to our overall clustering metric. Of course, additional testing before drawing any generalizations is warranted, and in a future post I will run some experiments on a number of centroid initializiation methods on a variety of datasets and compare with some additional metrics, hopefully to get a clearer picture of ways to go about optimizing unsupervised learning workflows. This post was originally published on KDnuggets.
[ { "code": null, "e": 254, "s": 46, "text": "In this post, we will look at using an iterative approach to searching for a better set of initial centroids for k-means clustering, and will do so by performing this process on a sample of our full dataset." }, { "code": null, "e": 785, "s": 254, "text": "What do we mean by “better?” Since k-means clustering aims to converge on an optimal set of cluster centers (centroids) and cluster membership based on distance from these centroids via successive iterations, it is intuitive that the more optimal the positioning of these initial centroids, the fewer iterations of the k-means clustering algorithms will be required for convergence. Therefore, thinking about ways to find a better set of initial centroid positions is a valid approach to optimizing the k-means clustering process." }, { "code": null, "e": 1545, "s": 785, "text": "What we will do differently, specifically, is to draw a sample of data from our full dataset, and run short runs of of the k-means clustering algorithm on it (not to convergence), short runs which will include, out of necessity, the centroid initialization process. We will repeat these short runs with a number of randomly initialized centroids, and will track the improvement to the measurement metric — within-cluster sum-of-squares — for determining goodness of cluster membership (or, at least, one of the valid metrics for measuring this). The final centroids associated with the random centroid initialization iteration process which provide the lowest inertia is the set of centroids which we will carry forward to our full dataset clustering process." }, { "code": null, "e": 1786, "s": 1545, "text": "The hope is that this up-front work will lead to a better set of initial centroids for our full clustering process, and, hence, a lesser number of k-means clustering iterations and, ultimately, less time required to fully cluster a dataset." }, { "code": null, "e": 2157, "s": 1786, "text": "This would obviously not be the only method of optimizing centroid initialization. In the past we have discussed the naive sharding centroid initialization method, a deterministic method for optimal centroid initialization. Other forms of modifications to the k-means clustering algorithm take different approaches to this problem as well (see k-means++ for comparison)." }, { "code": null, "e": 2202, "s": 2157, "text": "This post will approach our task as follows:" }, { "code": null, "e": 2219, "s": 2202, "text": "prepare the data" }, { "code": null, "e": 2238, "s": 2219, "text": "prepare our sample" }, { "code": null, "e": 2344, "s": 2238, "text": "perform centroid initialization search iterations to determine our “best” collection of initial centroids" }, { "code": null, "e": 2394, "s": 2344, "text": "use results to perform clustering on full dataset" }, { "code": null, "e": 2689, "s": 2394, "text": "A future post will perform and report comparisons of results between various approaches to centroid initialization, for a more comprehensive understanding of the practicalities of implementation. For now, however, let’s introduce and explore this particular approach to centroid initialization." }, { "code": null, "e": 2749, "s": 2689, "text": "For this overview, we will use the 3D road network dataset." }, { "code": null, "e": 3110, "s": 2749, "text": "Since this particular dataset has no missing values, and no class labels, our data preparation will primarily constitute normalization, along with dropping a column which identifies a geographical location from where the additional 3 columns worth of measurements come from, which is not useful for our task. See the dataset description for additional details." }, { "code": null, "e": 3480, "s": 3110, "text": "import numpy as npimport pandas as pdfrom sklearn import preprocessing# Read datasetdata = pd.read_csv('3D_spatial_network.csv', header=None)# Drop first column (not required)data.drop(labels=0, axis=1, inplace=True)# Normalize data (min/max scaling)data_arr = data.valuessc = preprocessing.MinMaxScaler()data_sc = sc.fit_transform(data_arr)data = pd.DataFrame(data_sc)" }, { "code": null, "e": 3520, "s": 3480, "text": "Let’s check out a sampling of our data:" }, { "code": null, "e": 3536, "s": 3520, "text": "data.sample(10)" }, { "code": null, "e": 3844, "s": 3536, "text": "Next, we will pull our sample that will be used to find our “best” initial centroids. Let’s be clear about exactly what we are doing: first, we are pulling a single set of samples from our dataset; then, we will perform successive rounds k-means clustering on this sample data, each iteration of which will:" }, { "code": null, "e": 3937, "s": 3844, "text": "randomly initialize k centroids and perform n iterations of the k-means clustering algorithm" }, { "code": null, "e": 4211, "s": 3937, "text": "the initial inertia (within-cluster sum-of-squares) of each centroid will be noted, as will its final inertia, and the initial centroids which provide the greatest increase in inertia over n iterations will be chosen as our initial centroids for the full dataset clustering" }, { "code": null, "e": 4341, "s": 4211, "text": "Finally, we will then perform full k-means clustering on the full dataset, using the initial clusters found in the previous step." }, { "code": null, "e": 4361, "s": 4341, "text": "2 important points:" }, { "code": null, "e": 5360, "s": 4361, "text": "Why not use greatest decrease in inertia? (The hope being that the initial momentum in this area will continue.) Doing so would also be a valid choice to explore (and changing a single line of code would allow for this). An arbitrary initial experimentation choice, and one which could use more investigation. However, the repetitive execution and comparison on a number of samples initially showed that the lowest inertia and greatest decrease in inertia coincide a great majority of the time, and so the decision may, in fact, be arbitrary, but also inconsequential in practice.Of particular clarification, we are not sampling multiple times from our dataset (e.g. once from our dataset for each iteration of centroid initialization). We are sampling once for all iterations of a single centroid initialization search. One sample, from which we will randomly derive initial centroids many times. Contrast this with the idea of repetitive sampling, once for each centroid initialization iteration." }, { "code": null, "e": 5941, "s": 5360, "text": "Why not use greatest decrease in inertia? (The hope being that the initial momentum in this area will continue.) Doing so would also be a valid choice to explore (and changing a single line of code would allow for this). An arbitrary initial experimentation choice, and one which could use more investigation. However, the repetitive execution and comparison on a number of samples initially showed that the lowest inertia and greatest decrease in inertia coincide a great majority of the time, and so the decision may, in fact, be arbitrary, but also inconsequential in practice." }, { "code": null, "e": 6360, "s": 5941, "text": "Of particular clarification, we are not sampling multiple times from our dataset (e.g. once from our dataset for each iteration of centroid initialization). We are sampling once for all iterations of a single centroid initialization search. One sample, from which we will randomly derive initial centroids many times. Contrast this with the idea of repetitive sampling, once for each centroid initialization iteration." }, { "code": null, "e": 6375, "s": 6360, "text": "Below, we set:" }, { "code": null, "e": 6418, "s": 6375, "text": "sample size as a ratio of our full dataset" }, { "code": null, "e": 6451, "s": 6418, "text": "random state for reproducibility" }, { "code": null, "e": 6490, "s": 6451, "text": "number of clusters (k) for our dataset" }, { "code": null, "e": 6541, "s": 6490, "text": "number of iterations (n) for our k-means algorithm" }, { "code": null, "e": 6644, "s": 6541, "text": "number of attempts at finding our best chance initial centroids while clustering on our sample dataset" }, { "code": null, "e": 6672, "s": 6644, "text": "We then set our sample data" }, { "code": null, "e": 6900, "s": 6672, "text": "# Some variablesSAMPLE_SIZE = 0.1RANDOM_STATE = 42NUM_CLUSTERS = 10 # kNUM_ITER = 3 # nNUM_ATTEMPTS = 5 # mdata_sample = data.sample(frac=SAMPLE_SIZE, random_state=RANDOM_STATE, replace=False)data_sample.shape" }, { "code": null, "e": 7044, "s": 6900, "text": "Now that when we have our data sample (data_sample) we are ready to perform iterations of centroid initialization for comparison and selection." }, { "code": null, "e": 7503, "s": 7044, "text": "Since Scikit-learn’s k-means clustering implementation does not allow for easily obtaining centroids between clustering iterations, we have to hack the workflow a bit. While the verbose option does output some useful information in this regard directly to screen, and redirecting this output and then post-parsing it would be one approach to getting what we need, what we will do is write our own outer iteration loop to control for our n variable ourselves." }, { "code": null, "e": 7924, "s": 7503, "text": "This means that we need to count iterations and capture what we need between these iterations, after each clustering step has run. We will then wrap that clustering iteration loop in a centroid initialization loop, which will initialize k centroids from our sample data m times. This is the hyperparameter specific to our particular instantiation of the k-means centroid initialization process, beyond “regular” k-means." }, { "code": null, "e": 8351, "s": 7924, "text": "Given our above parameters, we will be clustering our dataset into 10 clusters (NUM_CLUSTERS, or k), we will run our centroid search for 3 iterations (NUM_ITER, or n), and we will attempt this with 5 random initial centroids (NUM_ATTEMPTS, or m), after which we will determine our “best” set of centroids to initialize with for full clustering (in our case, the metric is the lowest within-cluster sum-of-squares, or inertia)." }, { "code": null, "e": 8504, "s": 8351, "text": "Prior to any clustering, however, let’s see what a sample of what a single initialization of our k-means looks like, prior to any clustering iterations." }, { "code": null, "e": 9208, "s": 8504, "text": "from sklearn.cluster import KMeanskm = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=1, n_init=1)#, verbose=1)km.fit(data_sample)print('Pre-clustering metrics')print('----------------------')print('Inertia:', km.inertia_)print('Centroids:', km.cluster_centers_)Pre-clustering metrics----------------------Inertia: 898.5527121490726Centroids: [[0.42360342 0.20208702 0.26294088] [0.56835267 0.34756347 0.14179924] [0.66005691 0.73147524 0.38203476] [0.23935675 0.08942105 0.11727529] [0.58630271 0.23417288 0.45793108] [0.1982982 0.11219503 0.23924021] [0.79313864 0.52773534 0.1334036 ] [0.54442269 0.60599501 0.17600424] [0.14588389 0.29821987 0.18053109] [0.73877864 0.8379479 0.12567452]]" }, { "code": null, "e": 9643, "s": 9208, "text": "In the code below, note that we have to manually track our centroids at the start of each iteration and at the end of each iteration, given that we are managing these successive iterations ourselves. We then feed these end centroids into our next loop iteration as the initial centroids, and run for one iteration. A bit tedious, and aggravating that we can’t get this out of Scikit-learn’s implementation directly, but not difficult." }, { "code": null, "e": 11723, "s": 9643, "text": "final_cents = []final_inert = [] for sample in range(NUM_ATTEMPTS): print('\\nCentroid attempt: ', sample) km = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=1, n_init=1)#, verbose=1) km.fit(data_sample) inertia_start = km.inertia_ intertia_end = 0 cents = km.cluster_centers_ for iter in range(NUM_ITER): km = KMeans(n_clusters=NUM_CLUSTERS, init=cents, max_iter=1, n_init=1) km.fit(data_sample) print('Iteration: ', iter) print('Inertia:', km.inertia_) print('Centroids:', km.cluster_centers_) inertia_end = km.inertia_ cents = km.cluster_centers_ final_cents.append(cents) final_inert.append(inertia_end) print('Difference between initial and final inertia: ', inertia_start-inertia_end)Centroid attempt: 0Iteration: 0Inertia: 885.1279991728289Centroids: [[0.67629991 0.54950506 0.14924545] [0.78911957 0.97469266 0.09090362] [0.61465665 0.32348368 0.11496346] [0.73784495 0.83111278 0.11263995] [0.34518925 0.37622882 0.1508636 ] [0.18220657 0.18489484 0.19303869] [0.55688642 0.35810877 0.32704852] [0.6884195 0.65798194 0.48258798] [0.62945726 0.73950354 0.21866185] [0.52282355 0.12252092 0.36251485]]Iteration: 1Inertia: 861.7158412685387Centroids: [[0.67039882 0.55769658 0.15204125] [0.78156936 0.96504069 0.09821352] [0.61009844 0.33444322 0.11527662] [0.75151713 0.79798919 0.1225065 ] [0.33091899 0.39011157 0.14788905] [0.18246521 0.18602087 0.19239602] [0.55246091 0.3507018 0.33212609] [0.68998302 0.65595219 0.48521344] [0.60291234 0.73999001 0.23322449] [0.51953015 0.12140833 0.34820443]]Iteration: 2Inertia: 839.2470653106332Centroids: [[0.65447477 0.55594052 0.15747416] [0.77412386 0.952986 0.10887517] [0.60761544 0.34326727 0.11544127] [0.77183027 0.76936972 0.12249837] [0.32151587 0.39281244 0.14797103] [0.18240552 0.18375276 0.19278224] [0.55052636 0.34639191 0.33667632] [0.691699 0.65507199 0.48648245] [0.59408317 0.73763362 0.23387334] [0.51879974 0.11982321 0.34035345]]Difference between initial and final inertia: 99.6102464383905..." }, { "code": null, "e": 11979, "s": 11723, "text": "After this is done, let’s see how we did in our centroid search. First we check a list of our final inertias (or within-cluster sum-of-squares), looking for the lowest value. We then set the associated centroids as the initial centroids for our next step." }, { "code": null, "e": 12098, "s": 11979, "text": "# Get best centroids to use for full clusteringbest_cents = final_cents[final_inert.index(min(final_inert))]best_cents" }, { "code": null, "e": 12141, "s": 12098, "text": "And here’s what those centroids look like:" }, { "code": null, "e": 12583, "s": 12141, "text": "array([[0.55053207, 0.16588572, 0.44981164], [0.78661867, 0.77450779, 0.11764745], [0.656176 , 0.55398196, 0.4748823 ], [0.17621429, 0.13463117, 0.17132811], [0.63702675, 0.14021011, 0.18632431], [0.60838757, 0.39809226, 0.14491584], [0.43593405, 0.49377153, 0.14018223], [0.16800744, 0.34174697, 0.19503396], [0.40169376, 0.15386471, 0.23633233], [0.62151433, 0.72434071, 0.25946183]])" }, { "code": null, "e": 12819, "s": 12583, "text": "And now, with our best initial centroids in hand, we can run k-means clustering on our full dataset. As Scikit-learn allows us to pass in a set of initial centroids, we can exploit this by the comparatively straightforward lines below." }, { "code": null, "e": 12930, "s": 12819, "text": "km_full = KMeans(n_clusters=NUM_CLUSTERS, init=best_cents, max_iter=100, verbose=1, n_init=1)km_full.fit(data)" }, { "code": null, "e": 12989, "s": 12930, "text": "This particular run of k-means converged in 13 iterations:" }, { "code": null, "e": 13128, "s": 12989, "text": "...start iterationdone sortingend inner loopIteration 13, inertia 7492.170210199639center shift 1.475641e-03 within tolerance 4.019354e-06" }, { "code": null, "e": 13244, "s": 13128, "text": "For comparison, here’s a full k-means clustering run using only randomly-initialized centroids (“regular” k-means):" }, { "code": null, "e": 13355, "s": 13244, "text": "km_naive = KMeans(n_clusters=NUM_CLUSTERS, init='random', max_iter=100, verbose=1, n_init=1)km_naive.fit(data)" }, { "code": null, "e": 13417, "s": 13355, "text": "This run took 39 iterations, with a nearly-identical inertia:" }, { "code": null, "e": 13556, "s": 13417, "text": "...start iterationdone sortingend inner loopIteration 39, inertia 7473.495361902045center shift 1.948248e-03 within tolerance 4.019354e-06" }, { "code": null, "e": 13886, "s": 13556, "text": "I leave finding the difference of execution times between the 13 iterations and 39 iterations (or similar) to the reader. Needless to say, eating up a few cycles ahead of time on a sample of data (in our case, 10% of the full dataset) saved considerable cycles in the long run, without sacrifice to our overall clustering metric." }, { "code": null, "e": 14228, "s": 13886, "text": "Of course, additional testing before drawing any generalizations is warranted, and in a future post I will run some experiments on a number of centroid initializiation methods on a variety of datasets and compare with some additional metrics, hopefully to get a clearer picture of ways to go about optimizing unsupervised learning workflows." } ]
C++ Vector Library - data() Function
The C++ function std::vector::data() returns a pointer to the first element of the vector container. Following is the declaration for std::vector::data() function form std::vector header. value_type* data() noexcept; const value_type* data() const noexcept; None Returns constant pointer if vector object is constant qualified otherwise non-constant pointer. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::vector::data() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v = {1, 2, 3, 4, 5}; int *p; p = v.data(); for (int i = 0; i < v.size(); ++i) cout << *p++ << endl; return 0; } Let us compile and run the above program, this will produce the following result − 1 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2704, "s": 2603, "text": "The C++ function std::vector::data() returns a pointer to the first element of the vector container." }, { "code": null, "e": 2791, "s": 2704, "text": "Following is the declaration for std::vector::data() function form std::vector header." }, { "code": null, "e": 2862, "s": 2791, "text": "value_type* data() noexcept;\nconst value_type* data() const noexcept;\n" }, { "code": null, "e": 2867, "s": 2862, "text": "None" }, { "code": null, "e": 2963, "s": 2867, "text": "Returns constant pointer if vector object is constant qualified otherwise non-constant pointer." }, { "code": null, "e": 3008, "s": 2963, "text": "This member function never throws exception." }, { "code": null, "e": 3027, "s": 3008, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3098, "s": 3027, "text": "The following example shows the usage of std::vector::data() function." }, { "code": null, "e": 3324, "s": 3098, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n int *p;\n\n p = v.data();\n\n for (int i = 0; i < v.size(); ++i)\n cout << *p++ << endl;\n\n return 0;\n}" }, { "code": null, "e": 3407, "s": 3324, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3418, "s": 3407, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 3425, "s": 3418, "text": " Print" }, { "code": null, "e": 3436, "s": 3425, "text": " Add Notes" } ]
Maximize Number of 1's | Practice | GeeksforGeeks
Given a binary array arr of size N and an integer M. Find the maximum number of consecutive 1's produced by flipping at most M 0's. Example 1: Input: N = 3 arr[] = {1, 0, 1} M = 1 Output: 3 Explanation: Maximum subarray is of size 3 which can be made subarray of all 1 after flipping two zeros to 1. Example 2: Input: N = 11 arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1} M = 2 Output: 8 Explanation: Maximum subarray is of size 8 which can be made subarray of all 1 after flipping two zeros to 1. Your Task: Complete the function findZeroes() which takes array arr and two integers n, m, as input parameters and returns an integer denoting the answer. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 107 0 <= M <= N 0 <= arri <= 1 0 siddhant073 weeks ago //Using sliding window technique //O(N) solution int findZeroes(int arr[], int n, int m) { int i = 0; int j = 0; int currLength = 0; int maxLength = 0; int cnt = 0; while(j < n){ if(arr[j] == 1){ currLength++; maxLength = std::max(currLength, maxLength); j++; } else{ cnt++; currLength++; while(cnt > m){ if(arr[i] == 0) cnt--; currLength--; i++; } j++; maxLength = std::max(currLength, maxLength); } } return maxLength; } 0 lindan1231 month ago int findZeroes(int arr[], int n, int m) { if(n==1 && m<=1) { return 1; } int i=0; int j=0; int ans =0; int c=0; for(int i=0;i<n;i++) { if(arr[i]==0) { c++; } while(c>m && j<=i) { if(arr[j]==0) { c--; } j++; } ans = max(ans,i-j+1); } return ans; } Time Taken : 0.0sec Cpp 0 gunjangoyal2821 month ago Simple and short C++ solution using sliding window technique with TC : O(N) and SC : O(1) int findZeroes(int arr[], int n, int m) { // code here int len = 0, start = 0, end = 0, ctr = 0; for(int i=0; i<n; i++){ if(arr[i] == 1){ end++; } else{ if(ctr < m){ ctr++; end++; } else{ while(arr[start] != 0){ start++; } start++; end++; } } len = max(len,(end-start)); } return len; } 0 abhinavsinghbiz2 months ago C++ Code: O(N) && O(1) : Run Time=0.8 secs! Detailed solution on Apni Kaksha! int findZeroes(int arr[], int n, int m){ int zerocount=0,i=0,ans=0; for(int j=0;j<n;j++){ if(arr[j]==0){ zerocount++; } while(zerocount>m){ if(arr[i]==0){ zerocount--; } i++; } ans=max(ans,j-i+1); } return ans; } 0 devopsraj202 months ago def findZeroes(arr, n, m): max_length = 0 left = 0 zeros = [] for i in range(n): # If find zero append it to the zeros array if arr[i] == 0: zeros.append(i) # when zero exceeds the number then pop the first element and left will be the next if len(zeros) > m: left = zeros.pop(0) + 1 # check max_length and assigned if required if i - left + 1 > max_length: max_length = i - left + 1 return max_length 0 jswxingyu13 months ago Python3 def findZeroes(arr, n, m) : # code here # set a window just like the hint shows. left_index = 0 right_index = 0 zeros_count = [] res = 0 for i in range(n): if arr[i] == 0: zeros_count.append(i) if len(zeros_count) <= m: res = max(res, right_index-left_index) else: left_index = zeros_count[0]+1 zeros_count.pop(0) res = max(res, right_index-left_index) else: res = max(res, right_index-left_index) right_index += 1 # print(left_index, right_index) return res + 1 +3 shiva10903 months ago int maxConsecutiveOne = 0 , start = 0 , zeroCount = 0; for(int end = 0; end < n; end++) { if(arr[end] == 0) zeroCount++; while(zeroCount > m) { if(arr[start] == 0) zeroCount--; start++; } maxConsecutiveOne = max(maxConsecutiveOne , end-start+1); } return maxConsecutiveOne; 0 vineelpeddi1234 months ago int ans = 0 , count = 0; int l = 0; vector<int> idx; for(int i = 0 ; i < n ; i++){ if(arr[i] == 0){ idx.push_back(i); } } for(int i = 0 ; i < n ; i++){ if(arr[i] == 1){ count++; }else{ if( m > 0){ count++; m--; }else{ count = i - idx[l]; l++; } } ans = max(ans , count); } return ans; 0 samarthsaxena07776 months ago int s=0,e=0,k=0,max=0; while(e<=n-1) { if(a[e]==0) k++; while(k>m) { if(a[s]==0) { k--; s++; } else s++; } if(max<e-s+1) max=e-s+1; e++; } return max; +1 aayushiiiisingh7 months ago int findZeroes(int arr[], int n, int m) { int cnt0 =0; int l=0; int ans=0; for(int i=0; i<n; i++){ if(arr[i] == 0) cnt0++; while(cnt0 > m){ if(arr[l] == 0) cnt0--; l++; } ans= max(ans, i-l+1); } return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 372, "s": 238, "text": "Given a binary array arr of size N and an integer M. Find the maximum number of consecutive 1's produced by flipping at most M 0's.\n " }, { "code": null, "e": 383, "s": 372, "text": "Example 1:" }, { "code": null, "e": 540, "s": 383, "text": "Input:\nN = 3\narr[] = {1, 0, 1}\nM = 1\nOutput:\n3\nExplanation:\nMaximum subarray is of size 3\nwhich can be made subarray of all 1 after\nflipping two zeros to 1." }, { "code": null, "e": 551, "s": 540, "text": "Example 2:" }, { "code": null, "e": 734, "s": 551, "text": "Input:\nN = 11\narr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1}\nM = 2\nOutput:\n8\nExplanation:\nMaximum subarray is of size 8\nwhich can be made subarray of all 1 after\nflipping two zeros to 1.\n" }, { "code": null, "e": 894, "s": 736, "text": "Your Task:\nComplete the function findZeroes() which takes array arr and two integers n, m, as input parameters and returns an integer denoting the answer. \n " }, { "code": null, "e": 958, "s": 894, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n " }, { "code": null, "e": 1012, "s": 958, "text": "Constraints:\n1 <= N <= 107\n0 <= M <= N\n0 <= arri <= 1" }, { "code": null, "e": 1014, "s": 1012, "text": "0" }, { "code": null, "e": 1036, "s": 1014, "text": "siddhant073 weeks ago" }, { "code": null, "e": 1069, "s": 1036, "text": "//Using sliding window technique" }, { "code": null, "e": 1085, "s": 1069, "text": "//O(N) solution" }, { "code": null, "e": 1805, "s": 1085, "text": " int findZeroes(int arr[], int n, int m) {\n int i = 0;\n int j = 0; \n int currLength = 0;\n int maxLength = 0;\n int cnt = 0;\n while(j < n){\n if(arr[j] == 1){\n currLength++;\n maxLength = std::max(currLength, maxLength);\n j++;\n }\n else{\n cnt++;\n currLength++;\n while(cnt > m){\n if(arr[i] == 0)\n cnt--;\n currLength--;\n i++;\n }\n j++;\n maxLength = std::max(currLength, maxLength);\n }\n }\n return maxLength;\n } " }, { "code": null, "e": 1807, "s": 1805, "text": "0" }, { "code": null, "e": 1828, "s": 1807, "text": "lindan1231 month ago" }, { "code": null, "e": 2374, "s": 1828, "text": "int findZeroes(int arr[], int n, int m) {\n \n if(n==1 && m<=1)\n {\n return 1;\n }\n int i=0;\n int j=0;\n int ans =0;\n int c=0;\n for(int i=0;i<n;i++)\n {\n if(arr[i]==0)\n {\n c++;\n }\n while(c>m && j<=i)\n {\n if(arr[j]==0)\n {\n c--;\n }\n j++;\n }\n ans = max(ans,i-j+1);\n }\n return ans;\n } " }, { "code": null, "e": 2394, "s": 2374, "text": "Time Taken : 0.0sec" }, { "code": null, "e": 2398, "s": 2394, "text": "Cpp" }, { "code": null, "e": 2400, "s": 2398, "text": "0" }, { "code": null, "e": 2426, "s": 2400, "text": "gunjangoyal2821 month ago" }, { "code": null, "e": 2516, "s": 2426, "text": "Simple and short C++ solution using sliding window technique with TC : O(N) and SC : O(1)" }, { "code": null, "e": 3135, "s": 2518, "text": "int findZeroes(int arr[], int n, int m) {\n // code here\n int len = 0, start = 0, end = 0, ctr = 0;\n for(int i=0; i<n; i++){\n if(arr[i] == 1){\n end++;\n }\n else{\n if(ctr < m){\n ctr++;\n end++;\n }\n else{\n while(arr[start] != 0){\n start++;\n }\n start++;\n end++;\n }\n }\n len = max(len,(end-start));\n }\n return len;\n } " }, { "code": null, "e": 3137, "s": 3135, "text": "0" }, { "code": null, "e": 3165, "s": 3137, "text": "abhinavsinghbiz2 months ago" }, { "code": null, "e": 3211, "s": 3165, "text": "C++ Code: O(N) && O(1) : Run Time=0.8 secs! " }, { "code": null, "e": 3246, "s": 3211, "text": "Detailed solution on Apni Kaksha! " }, { "code": null, "e": 3612, "s": 3248, "text": "int findZeroes(int arr[], int n, int m){ int zerocount=0,i=0,ans=0; for(int j=0;j<n;j++){ if(arr[j]==0){ zerocount++; } while(zerocount>m){ if(arr[i]==0){ zerocount--; } i++; } ans=max(ans,j-i+1); } return ans; } " }, { "code": null, "e": 3614, "s": 3612, "text": "0" }, { "code": null, "e": 3638, "s": 3614, "text": "devopsraj202 months ago" }, { "code": null, "e": 4148, "s": 3638, "text": "def findZeroes(arr, n, m):\n max_length = 0\n left = 0\n zeros = []\n for i in range(n):\n # If find zero append it to the zeros array \n if arr[i] == 0:\n zeros.append(i)\n # when zero exceeds the number then pop the first element and left will be the next \n if len(zeros) > m:\n left = zeros.pop(0) + 1\n\n # check max_length and assigned if required\n if i - left + 1 > max_length:\n max_length = i - left + 1\n\n return max_length" }, { "code": null, "e": 4150, "s": 4148, "text": "0" }, { "code": null, "e": 4173, "s": 4150, "text": "jswxingyu13 months ago" }, { "code": null, "e": 4181, "s": 4173, "text": "Python3" }, { "code": null, "e": 4834, "s": 4181, "text": "def findZeroes(arr, n, m) :\n # code here\n # set a window just like the hint shows.\n left_index = 0\n right_index = 0\n zeros_count = []\n res = 0\n\n for i in range(n):\n if arr[i] == 0:\n zeros_count.append(i)\n if len(zeros_count) <= m:\n res = max(res, right_index-left_index)\n else:\n left_index = zeros_count[0]+1\n zeros_count.pop(0)\n res = max(res, right_index-left_index)\n else:\n res = max(res, right_index-left_index) \n\n right_index += 1\n \n # print(left_index, right_index)\n return res + 1" }, { "code": null, "e": 4837, "s": 4834, "text": "+3" }, { "code": null, "e": 4859, "s": 4837, "text": "shiva10903 months ago" }, { "code": null, "e": 5310, "s": 4859, "text": " int maxConsecutiveOne = 0 , start = 0 , zeroCount = 0; for(int end = 0; end < n; end++) { if(arr[end] == 0) zeroCount++; while(zeroCount > m) { if(arr[start] == 0) zeroCount--; start++; } maxConsecutiveOne = max(maxConsecutiveOne , end-start+1); } return maxConsecutiveOne;" }, { "code": null, "e": 5312, "s": 5310, "text": "0" }, { "code": null, "e": 5339, "s": 5312, "text": "vineelpeddi1234 months ago" }, { "code": null, "e": 5841, "s": 5339, "text": " int ans = 0 , count = 0; int l = 0; vector<int> idx; for(int i = 0 ; i < n ; i++){ if(arr[i] == 0){ idx.push_back(i); } } for(int i = 0 ; i < n ; i++){ if(arr[i] == 1){ count++; }else{ if( m > 0){ count++; m--; }else{ count = i - idx[l]; l++; } } ans = max(ans , count); } return ans;" }, { "code": null, "e": 5843, "s": 5841, "text": "0" }, { "code": null, "e": 5873, "s": 5843, "text": "samarthsaxena07776 months ago" }, { "code": null, "e": 6234, "s": 5873, "text": "int s=0,e=0,k=0,max=0; while(e<=n-1) { if(a[e]==0) k++; while(k>m) { if(a[s]==0) { k--; s++; } else s++; } if(max<e-s+1) max=e-s+1; e++; } return max;" }, { "code": null, "e": 6237, "s": 6234, "text": "+1" }, { "code": null, "e": 6265, "s": 6237, "text": "aayushiiiisingh7 months ago" }, { "code": null, "e": 6613, "s": 6265, "text": "int findZeroes(int arr[], int n, int m) { int cnt0 =0; int l=0; int ans=0; for(int i=0; i<n; i++){ if(arr[i] == 0) cnt0++; while(cnt0 > m){ if(arr[l] == 0) cnt0--; l++; } ans= max(ans, i-l+1); } return ans; } " }, { "code": null, "e": 6759, "s": 6613, "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": 6795, "s": 6759, "text": " Login to access your submissions. " }, { "code": null, "e": 6805, "s": 6795, "text": "\nProblem\n" }, { "code": null, "e": 6815, "s": 6805, "text": "\nContest\n" }, { "code": null, "e": 6878, "s": 6815, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7026, "s": 6878, "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": 7234, "s": 7026, "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": 7340, "s": 7234, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Count subarrays having each distinct element occurring at least twice - GeeksforGeeks
04 Oct, 2021 Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice. Examples: Input: arr[] = {1, 1, 2, 2, 2}Output: 6Explanation: Subarrays having each element occurring at least twice are :{{1, 1}, {1, 1, 2, 2}, {1, 1, 2, 2, 2}, {2, 2}, {2, 2, 2}, {2, 2}}.Therefore, the required output is 6. Input: arr[] = {1, 2, 1, 2, 3}Output: 1 Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subarrays of the given array and for each subarray, check if all elements in the subarray occurs at least twice or not. If found to be true, then increment the count. Finally, print the count obtained. Time Complexity: O(N3)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach the idea is to use Hashing. Follow the steps below to solve the problem: Initialize a variable, say cntSub to store the count of subarrays such that each element in the subarray occurs at least twice. Create a Map, say cntFreq, to store the frequency of elements of each subarray. Initialize a variable, say cntUnique, to store the count of elements in a subarray whose frequency is 1. Traverse the array and generate all possible subarrays. For each possible subarray, store the frequency of each element of the array and check if the value of cntUnique is 0 or not. If found to be true, then increment the value of cntSub. Finally, print the value of cntSub. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get the count// of subarrays having each// element occurring at least twiceint cntSubarrays(int arr[], int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray unordered_map<int, int> cntFreq; // Traverse the given // array for (int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for (int j = i; j < N; j++) { // Update frequency cntFreq[arr[j]]++; // Check if frequency of // arr[j] equal to 1 if (cntFreq[arr[j]] == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq[arr[j]] == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codeint main(){ int arr[] = { 1, 1, 2, 2, 2 }; int N = sizeof(arr) / sizeof(arr[0]); cout << cntSubarrays(arr, N);} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to get the count// of subarrays having each// element occurring at least twicestatic int cntSubarrays(int arr[], int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray Map<Integer, Integer> cntFreq = new HashMap<Integer, Integer>(); // Traverse the given // array for(int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for(int j = i; j < N; j++) { // Update frequency cntFreq.put(arr[j], cntFreq.getOrDefault( arr[j], 0) + 1); // Check if frequency of // arr[j] equal to 1 if (cntFreq.get(arr[j]) == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq.get(arr[j]) == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codepublic static void main(String args[]){ int arr[] = { 1, 1, 2, 2, 2 }; int N = arr.length; System.out.println(cntSubarrays(arr, N));}} // This code is contributed by SURENDRA_GANGWAR # Python3 program to implement# the above approachfrom collections import defaultdict # Function to get the count# of subarrays having each# element occurring at least twice def cntSubarrays(arr, N): # Stores count of subarrays # having each distinct element # occurring at least twice cntSub = 0 # Stores count of unique # elements in a subarray cntUnique = 0 # Store frequency of # each element of a subarray cntFreq = defaultdict(lambda : 0) # Traverse the given # array for i in range(N): # Count frequency and # check conditions for # each subarray for j in range(i, N): # Update frequency cntFreq[arr[j]] += 1 # Check if frequency of # arr[j] equal to 1 if (cntFreq[arr[j]] == 1): # Update Count of # unique elements cntUnique += 1 elif (cntFreq[arr[j]] == 2): # Update count of # unique elements cntUnique -= 1 # If each element of subarray # occurs at least twice if (cntUnique == 0): # Update cntSub cntSub += 1 # Remove all elements # from the subarray cntFreq.clear() # Update cntUnique cntUnique = 0 return cntSub # Driver codeif __name__ == '__main__': arr = [ 1, 1, 2, 2, 2 ] N = len(arr) print(cntSubarrays(arr, N)) # This code is contributed by Shivam Singh // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to get the count// of subarrays having each// element occurring at least twicestatic int cntSubarrays(int[] arr, int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray Dictionary<int, int> cntFreq = new Dictionary<int, int>(); // Traverse the given // array for(int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for(int j = i; j < N; j++) { // Update frequency if (cntFreq.ContainsKey(arr[j])) { var val = cntFreq[arr[j]]; cntFreq.Remove(arr[j]); cntFreq.Add(arr[j], val + 1); } else { cntFreq.Add(arr[j], 1); } // Check if frequency of // arr[j] equal to 1 if (cntFreq[arr[j]] == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq[arr[j]] == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.Clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codepublic static void Main(){ int[] arr = { 1, 1, 2, 2, 2 }; int N = arr.Length; Console.Write(cntSubarrays(arr, N));}} // This code is contributed by subhammahato348 <script> // Javascript program to implement// the above approach // Function to get the count// of subarrays having each// element occurring at least twicefunction cntSubarrays(arr, N){ // Stores count of subarrays // having each distinct element // occurring at least twice var cntSub = 0; // Stores count of unique // elements in a subarray var cntUnique = 0; // Store frequency of // each element of a subarray var cntFreq = new Map(); // Traverse the given // array for (var i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for (var j = i; j < N; j++) { // Update frequency if(cntFreq.has(arr[j])) cntFreq.set(arr[j], cntFreq.get(arr[j])+1) else cntFreq.set(arr[j], 1); // Check if frequency of // arr[j] equal to 1 if (cntFreq.get(arr[j]) == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq.get(arr[j]) == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq = new Map(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codevar arr = [1, 1, 2, 2, 2];var N = arr.length;document.write( cntSubarrays(arr, N)); // This code is contributed by itsok.</script> 6 Time Complexity: O(N2)Auxiliary Space: O(N) SHIVAMSINGH67 SURENDRA_GANGWAR subhammahato348 simmytarika5 itsok varshagumber28 gabaa406 arorakashish0911 cpp-unordered_map frequency-counting subarray Arrays Hash Searching Arrays Searching Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 24927, "s": 24899, "text": "\n04 Oct, 2021" }, { "code": null, "e": 25099, "s": 24927, "text": "Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice." }, { "code": null, "e": 25109, "s": 25099, "text": "Examples:" }, { "code": null, "e": 25325, "s": 25109, "text": "Input: arr[] = {1, 1, 2, 2, 2}Output: 6Explanation: Subarrays having each element occurring at least twice are :{{1, 1}, {1, 1, 2, 2}, {1, 1, 2, 2, 2}, {2, 2}, {2, 2, 2}, {2, 2}}.Therefore, the required output is 6." }, { "code": null, "e": 25365, "s": 25325, "text": "Input: arr[] = {1, 2, 1, 2, 3}Output: 1" }, { "code": null, "e": 25678, "s": 25365, "text": "Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subarrays of the given array and for each subarray, check if all elements in the subarray occurs at least twice or not. If found to be true, then increment the count. Finally, print the count obtained." }, { "code": null, "e": 25722, "s": 25678, "text": "Time Complexity: O(N3)Auxiliary Space: O(N)" }, { "code": null, "e": 25846, "s": 25722, "text": "Efficient Approach: To optimize the above approach the idea is to use Hashing. Follow the steps below to solve the problem:" }, { "code": null, "e": 25974, "s": 25846, "text": "Initialize a variable, say cntSub to store the count of subarrays such that each element in the subarray occurs at least twice." }, { "code": null, "e": 26054, "s": 25974, "text": "Create a Map, say cntFreq, to store the frequency of elements of each subarray." }, { "code": null, "e": 26159, "s": 26054, "text": "Initialize a variable, say cntUnique, to store the count of elements in a subarray whose frequency is 1." }, { "code": null, "e": 26398, "s": 26159, "text": "Traverse the array and generate all possible subarrays. For each possible subarray, store the frequency of each element of the array and check if the value of cntUnique is 0 or not. If found to be true, then increment the value of cntSub." }, { "code": null, "e": 26434, "s": 26398, "text": "Finally, print the value of cntSub." }, { "code": null, "e": 26485, "s": 26434, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26489, "s": 26485, "text": "C++" }, { "code": null, "e": 26494, "s": 26489, "text": "Java" }, { "code": null, "e": 26502, "s": 26494, "text": "Python3" }, { "code": null, "e": 26505, "s": 26502, "text": "C#" }, { "code": null, "e": 26516, "s": 26505, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get the count// of subarrays having each// element occurring at least twiceint cntSubarrays(int arr[], int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray unordered_map<int, int> cntFreq; // Traverse the given // array for (int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for (int j = i; j < N; j++) { // Update frequency cntFreq[arr[j]]++; // Check if frequency of // arr[j] equal to 1 if (cntFreq[arr[j]] == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq[arr[j]] == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codeint main(){ int arr[] = { 1, 1, 2, 2, 2 }; int N = sizeof(arr) / sizeof(arr[0]); cout << cntSubarrays(arr, N);}", "e": 28211, "s": 26516, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to get the count// of subarrays having each// element occurring at least twicestatic int cntSubarrays(int arr[], int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray Map<Integer, Integer> cntFreq = new HashMap<Integer, Integer>(); // Traverse the given // array for(int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for(int j = i; j < N; j++) { // Update frequency cntFreq.put(arr[j], cntFreq.getOrDefault( arr[j], 0) + 1); // Check if frequency of // arr[j] equal to 1 if (cntFreq.get(arr[j]) == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq.get(arr[j]) == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codepublic static void main(String args[]){ int arr[] = { 1, 1, 2, 2, 2 }; int N = arr.length; System.out.println(cntSubarrays(arr, N));}} // This code is contributed by SURENDRA_GANGWAR", "e": 30257, "s": 28211, "text": null }, { "code": "# Python3 program to implement# the above approachfrom collections import defaultdict # Function to get the count# of subarrays having each# element occurring at least twice def cntSubarrays(arr, N): # Stores count of subarrays # having each distinct element # occurring at least twice cntSub = 0 # Stores count of unique # elements in a subarray cntUnique = 0 # Store frequency of # each element of a subarray cntFreq = defaultdict(lambda : 0) # Traverse the given # array for i in range(N): # Count frequency and # check conditions for # each subarray for j in range(i, N): # Update frequency cntFreq[arr[j]] += 1 # Check if frequency of # arr[j] equal to 1 if (cntFreq[arr[j]] == 1): # Update Count of # unique elements cntUnique += 1 elif (cntFreq[arr[j]] == 2): # Update count of # unique elements cntUnique -= 1 # If each element of subarray # occurs at least twice if (cntUnique == 0): # Update cntSub cntSub += 1 # Remove all elements # from the subarray cntFreq.clear() # Update cntUnique cntUnique = 0 return cntSub # Driver codeif __name__ == '__main__': arr = [ 1, 1, 2, 2, 2 ] N = len(arr) print(cntSubarrays(arr, N)) # This code is contributed by Shivam Singh", "e": 31857, "s": 30257, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to get the count// of subarrays having each// element occurring at least twicestatic int cntSubarrays(int[] arr, int N){ // Stores count of subarrays // having each distinct element // occurring at least twice int cntSub = 0; // Stores count of unique // elements in a subarray int cntUnique = 0; // Store frequency of // each element of a subarray Dictionary<int, int> cntFreq = new Dictionary<int, int>(); // Traverse the given // array for(int i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for(int j = i; j < N; j++) { // Update frequency if (cntFreq.ContainsKey(arr[j])) { var val = cntFreq[arr[j]]; cntFreq.Remove(arr[j]); cntFreq.Add(arr[j], val + 1); } else { cntFreq.Add(arr[j], 1); } // Check if frequency of // arr[j] equal to 1 if (cntFreq[arr[j]] == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq[arr[j]] == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq.Clear(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codepublic static void Main(){ int[] arr = { 1, 1, 2, 2, 2 }; int N = arr.Length; Console.Write(cntSubarrays(arr, N));}} // This code is contributed by subhammahato348", "e": 34070, "s": 31857, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to get the count// of subarrays having each// element occurring at least twicefunction cntSubarrays(arr, N){ // Stores count of subarrays // having each distinct element // occurring at least twice var cntSub = 0; // Stores count of unique // elements in a subarray var cntUnique = 0; // Store frequency of // each element of a subarray var cntFreq = new Map(); // Traverse the given // array for (var i = 0; i < N; i++) { // Count frequency and // check conditions for // each subarray for (var j = i; j < N; j++) { // Update frequency if(cntFreq.has(arr[j])) cntFreq.set(arr[j], cntFreq.get(arr[j])+1) else cntFreq.set(arr[j], 1); // Check if frequency of // arr[j] equal to 1 if (cntFreq.get(arr[j]) == 1) { // Update Count of // unique elements cntUnique++; } else if (cntFreq.get(arr[j]) == 2) { // Update count of // unique elements cntUnique--; } // If each element of subarray // occurs at least twice if (cntUnique == 0) { // Update cntSub cntSub++; } } // Remove all elements // from the subarray cntFreq = new Map(); // Update cntUnique cntUnique = 0; } return cntSub;} // Driver Codevar arr = [1, 1, 2, 2, 2];var N = arr.length;document.write( cntSubarrays(arr, N)); // This code is contributed by itsok.</script>", "e": 35864, "s": 34070, "text": null }, { "code": null, "e": 35866, "s": 35864, "text": "6" }, { "code": null, "e": 35912, "s": 35868, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 35932, "s": 35918, "text": "SHIVAMSINGH67" }, { "code": null, "e": 35949, "s": 35932, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35965, "s": 35949, "text": "subhammahato348" }, { "code": null, "e": 35978, "s": 35965, "text": "simmytarika5" }, { "code": null, "e": 35984, "s": 35978, "text": "itsok" }, { "code": null, "e": 35999, "s": 35984, "text": "varshagumber28" }, { "code": null, "e": 36008, "s": 35999, "text": "gabaa406" }, { "code": null, "e": 36025, "s": 36008, "text": "arorakashish0911" }, { "code": null, "e": 36043, "s": 36025, "text": "cpp-unordered_map" }, { "code": null, "e": 36062, "s": 36043, "text": "frequency-counting" }, { "code": null, "e": 36071, "s": 36062, "text": "subarray" }, { "code": null, "e": 36078, "s": 36071, "text": "Arrays" }, { "code": null, "e": 36083, "s": 36078, "text": "Hash" }, { "code": null, "e": 36093, "s": 36083, "text": "Searching" }, { "code": null, "e": 36100, "s": 36093, "text": "Arrays" }, { "code": null, "e": 36110, "s": 36100, "text": "Searching" }, { "code": null, "e": 36115, "s": 36110, "text": "Hash" }, { "code": null, "e": 36213, "s": 36115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36222, "s": 36213, "text": "Comments" }, { "code": null, "e": 36235, "s": 36222, "text": "Old Comments" }, { "code": null, "e": 36283, "s": 36235, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36327, "s": 36283, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36350, "s": 36327, "text": "Introduction to Arrays" }, { "code": null, "e": 36382, "s": 36350, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36396, "s": 36382, "text": "Linear Search" }, { "code": null, "e": 36481, "s": 36396, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 36517, "s": 36481, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 36548, "s": 36517, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 36575, "s": 36548, "text": "Count pairs with given sum" } ]
Python Program to Sort an array in wave form - GeeksforGeeks
27 Dec, 2021 Given an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {20, 5, 10, 2, 80, 6, 100, 3} OR any other array that is in wave form Input: arr[] = {20, 10, 8, 6, 4, 2} Output: arr[] = {20, 8, 10, 4, 6, 2} OR {10, 8, 20, 2, 6, 4} OR any other array that is in wave form Input: arr[] = {2, 4, 6, 8, 10, 20} Output: arr[] = {4, 2, 8, 6, 20, 10} OR any other array that is in wave form Input: arr[] = {3, 6, 5, 10, 7, 20} Output: arr[] = {6, 3, 10, 5, 20, 7} OR any other array that is in wave form A Simple Solution is to use sorting. First sort the input array, then swap all adjacent elements.For example, let the input array be {3, 6, 5, 10, 7, 20}. After sorting, we get {3, 5, 6, 7, 10, 20}. After swapping adjacent elements, we get {5, 3, 7, 6, 20, 10}. Below are implementations of this simple approach. Python # Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n): #sort the array arr.sort() # Swap adjacent elements for i in range(0,n-1,2): arr[i], arr[i+1] = arr[i+1], arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)): print arr[i], # This code is contributed by __Devesh Agrawal__ Output: 2 1 10 5 49 23 90 The time complexity of the above solution is O(nLogn) if a O(nLogn) sorting algorithm like Merge Sort, Heap Sort, .. etc is used.This can be done in O(n) time by doing a single traversal of given array. The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements are greater than their adjacent odd elements, we don’t need to worry about odd positioned element. Following are simple steps. 1) Traverse all even positioned elements of input array, and do following. ....a) If current element is smaller than previous odd element, swap previous and current. ....b) If current element is smaller than next odd element, swap next and current. Below are implementations of above simple algorithm. Python # Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n): # Traverse all even elements for i in range(0, n, 2): # If current even element is smaller than previous if (i> 0 and arr[i] < arr[i-1]): arr[i],arr[i-1] = arr[i-1],arr[i] # If current even element is smaller than next if (i < n-1 and arr[i] < arr[i+1]): arr[i],arr[i+1] = arr[i+1],arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)): print arr[i], # This code is contributed by __Devesh Agrawal__ Output: 90 10 49 1 5 2 23 Please refer complete article on Sort an array in wave form for more details! array-rearrange FactSet Zoho Arrays Python Python Programs Sorting Zoho FactSet Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24405, "s": 24377, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24586, "s": 24405, "text": "Given an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ....." }, { "code": null, "e": 24597, "s": 24586, "text": "Examples: " }, { "code": null, "e": 25243, "s": 24597, "text": " Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}\n Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR\n {20, 5, 10, 2, 80, 6, 100, 3} OR\n any other array that is in wave form\n\n Input: arr[] = {20, 10, 8, 6, 4, 2}\n Output: arr[] = {20, 8, 10, 4, 6, 2} OR\n {10, 8, 20, 2, 6, 4} OR\n any other array that is in wave form\n\n Input: arr[] = {2, 4, 6, 8, 10, 20}\n Output: arr[] = {4, 2, 8, 6, 20, 10} OR\n any other array that is in wave form\n\n Input: arr[] = {3, 6, 5, 10, 7, 20}\n Output: arr[] = {6, 3, 10, 5, 20, 7} OR\n any other array that is in wave form\n " }, { "code": null, "e": 25506, "s": 25243, "text": "A Simple Solution is to use sorting. First sort the input array, then swap all adjacent elements.For example, let the input array be {3, 6, 5, 10, 7, 20}. After sorting, we get {3, 5, 6, 7, 10, 20}. After swapping adjacent elements, we get {5, 3, 7, 6, 20, 10}. " }, { "code": null, "e": 25558, "s": 25506, "text": "Below are implementations of this simple approach. " }, { "code": null, "e": 25565, "s": 25558, "text": "Python" }, { "code": "# Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n): #sort the array arr.sort() # Swap adjacent elements for i in range(0,n-1,2): arr[i], arr[i+1] = arr[i+1], arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)): print arr[i], # This code is contributed by __Devesh Agrawal__", "e": 26029, "s": 25565, "text": null }, { "code": null, "e": 26038, "s": 26029, "text": "Output: " }, { "code": null, "e": 26056, "s": 26038, "text": "2 1 10 5 49 23 90" }, { "code": null, "e": 26743, "s": 26056, "text": "The time complexity of the above solution is O(nLogn) if a O(nLogn) sorting algorithm like Merge Sort, Heap Sort, .. etc is used.This can be done in O(n) time by doing a single traversal of given array. The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements are greater than their adjacent odd elements, we don’t need to worry about odd positioned element. Following are simple steps. 1) Traverse all even positioned elements of input array, and do following. ....a) If current element is smaller than previous odd element, swap previous and current. ....b) If current element is smaller than next odd element, swap next and current." }, { "code": null, "e": 26797, "s": 26743, "text": "Below are implementations of above simple algorithm. " }, { "code": null, "e": 26804, "s": 26797, "text": "Python" }, { "code": "# Python function to sort the array arr[0..n-1] in wave form,# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]def sortInWave(arr, n): # Traverse all even elements for i in range(0, n, 2): # If current even element is smaller than previous if (i> 0 and arr[i] < arr[i-1]): arr[i],arr[i-1] = arr[i-1],arr[i] # If current even element is smaller than next if (i < n-1 and arr[i] < arr[i+1]): arr[i],arr[i+1] = arr[i+1],arr[i] # Driver programarr = [10, 90, 49, 2, 1, 5, 23]sortInWave(arr, len(arr))for i in range(0,len(arr)): print arr[i], # This code is contributed by __Devesh Agrawal__", "e": 27496, "s": 26804, "text": null }, { "code": null, "e": 27505, "s": 27496, "text": "Output: " }, { "code": null, "e": 27525, "s": 27505, "text": "90 10 49 1 5 2 23\n " }, { "code": null, "e": 27603, "s": 27525, "text": "Please refer complete article on Sort an array in wave form for more details!" }, { "code": null, "e": 27619, "s": 27603, "text": "array-rearrange" }, { "code": null, "e": 27627, "s": 27619, "text": "FactSet" }, { "code": null, "e": 27632, "s": 27627, "text": "Zoho" }, { "code": null, "e": 27639, "s": 27632, "text": "Arrays" }, { "code": null, "e": 27646, "s": 27639, "text": "Python" }, { "code": null, "e": 27662, "s": 27646, "text": "Python Programs" }, { "code": null, "e": 27670, "s": 27662, "text": "Sorting" }, { "code": null, "e": 27675, "s": 27670, "text": "Zoho" }, { "code": null, "e": 27683, "s": 27675, "text": "FactSet" }, { "code": null, "e": 27690, "s": 27683, "text": "Arrays" }, { "code": null, "e": 27698, "s": 27690, "text": "Sorting" }, { "code": null, "e": 27796, "s": 27698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27805, "s": 27796, "text": "Comments" }, { "code": null, "e": 27818, "s": 27805, "text": "Old Comments" }, { "code": null, "e": 27839, "s": 27818, "text": "Next Greater Element" }, { "code": null, "e": 27864, "s": 27839, "text": "Window Sliding Technique" }, { "code": null, "e": 27891, "s": 27864, "text": "Count pairs with given sum" }, { "code": null, "e": 27940, "s": 27891, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 27978, "s": 27940, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28006, "s": 27978, "text": "Read JSON file using Python" }, { "code": null, "e": 28056, "s": 28006, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28078, "s": 28056, "text": "Python map() function" } ]
C++ Program for the Fractional Knapsack Problem - GeeksforGeeks
19 Jul, 2020 Pre-requisite: Fractional Knapsack Problem Given two arrays weight[] and profit[] the weights and profit of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.Note: Unlike 0/1 knapsack, you are allowed to break the item. Examples: Input: weight[] = {10, 20, 30}, profit[] = {60, 100, 120}, N= 50Output: Maximum profit earned = 240Explanation: Decreasing p/w ratio[] = {6, 5, 4}Taking up the weight values 10, 20, (2 / 3) * 30 Profit = 60 + 100 + 120 * (2 / 3) = 240 Input: weight[] = {10, 40, 20, 24}, profit[] = {100, 280, 120, 120}, N = 60Output: Maximum profit earned = 440Explanation: Decreasing p/w ratio[] = {10, 7, 6, 5}Taking up the weight values 10, 40, (1 / 2) * 120 Profit = 100 + 280 + (1 / 2) * 120 = 440 Method 1 – without using STL: The idea is to use Greedy Approach. Below are the steps: Find the ratio value/weight for each item and sort the item on the basis of this ratio.Choose the item with the highest ratio and add them until we can’t add the next item as a whole.In the end, add the next item as much as we can.Print the maximum profit after the above steps. Find the ratio value/weight for each item and sort the item on the basis of this ratio. Choose the item with the highest ratio and add them until we can’t add the next item as a whole. In the end, add the next item as much as we can. Print the maximum profit after the above steps. Below is the implementation of the above approach: C++ // C++ program to solve fractional// Knapsack Problem#include <bits/stdc++.h> using namespace std; // Structure for an item which stores// weight & corresponding value of Itemstruct Item { int value, weight; // Constructor Item(int value, int weight) : value(value), weight(weight) { }}; // Comparison function to sort Item// according to val/weight ratiobool cmp(struct Item a, struct Item b){ double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2;} // Main greedy function to solve problemdouble fractionalKnapsack(struct Item arr[], int N, int size){ // Sort Item on basis of ratio sort(arr, arr + size, cmp); // Current weight in knapsack int curWeight = 0; // Result (value in Knapsack) double finalvalue = 0.0; // Looping through all Items for (int i = 0; i < size; i++) { // If adding Item won't overflow, // add it completely if (curWeight + arr[i].weight <= N) { curWeight += arr[i].weight; finalvalue += arr[i].value; } // If we can't add current Item, // add fractional part of it else { int remain = N - curWeight; finalvalue += arr[i].value * ((double)remain / arr[i].weight); break; } } // Returning final value return finalvalue;} // Driver Codeint main(){ // Weight of knapsack int N = 60; // Given weights and values as a pairs Item arr[] = { { 100, 10 }, { 280, 40 }, { 120, 20 }, { 120, 24 } }; int size = sizeof(arr) / sizeof(arr[0]); // Function Call cout << "Maximum profit earned = " << fractionalKnapsack(arr, N, size); return 0;} Maximum profit earned = 440 Time Complexity: O(N*log2N)Auxiliary Space: O(1) Method 2 – using STL: Create a map with profit[i] / weight[i] as first and i as Second element for each element.Define a variable max_profit = 0.Traverse the map in reverse fashion:Create a variable named fraction whose value is equivalent to remaining_weight / weight[i].If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i].Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break.Print the max_profit. Create a map with profit[i] / weight[i] as first and i as Second element for each element. Define a variable max_profit = 0. Traverse the map in reverse fashion:Create a variable named fraction whose value is equivalent to remaining_weight / weight[i].If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i].Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break. Create a variable named fraction whose value is equivalent to remaining_weight / weight[i]. If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i]. Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break. Print the max_profit. Below is the implementation of the above approach: C++ // C++ program to Fractional Knapsack// Problem using STL#include <bits/stdc++.h>using namespace std; // Function to find maximum profitvoid maxProfit(vector<int> profit, vector<int> weight, int N){ // Number of total weights present int numOfElements = profit.size(); int i; // Multimap container to store // ratio and index multimap<double, int> ratio; // Variable to store maximum profit double max_profit = 0; for (i = 0; i < numOfElements; i++) { // Insert ratio profit[i] / weight[i] // and corresponding index ratio.insert(make_pair( (double)profit[i] / weight[i], i)); } // Declare a reverse iterator // for Multimap multimap<double, int>::reverse_iterator it; // Traverse the map in reverse order for (it = ratio.rbegin(); it != ratio.rend(); it++) { // Fraction of weight of i'th item // that can be kept in knapsack double fraction = (double)N / weight[it->second]; // if remaining_weight is greater // than the weight of i'th item if (N >= 0 && N >= weight[it->second]) { // increase max_profit by i'th // profit value max_profit += profit[it->second]; // decrement knapsack to form // new remaining_weight N -= weight[it->second]; } // remaining_weight less than // weight of i'th item else if (N < weight[it->second]) { max_profit += fraction * profit[it->second]; break; } } // Print the maximum profit earned cout << "Maximum profit earned is:" << max_profit;} // Driver Codeint main(){ // Size of list int size = 4; // Given profit and weight vector<int> profit(size), weight(size); // Profit of items profit[0] = 100, profit[1] = 280, profit[2] = 120, profit[3] = 120; // Weight of items weight[0] = 10, weight[1] = 40, weight[2] = 20, weight[3] = 24; // Capacity of knapsack int N = 60; // Function Call maxProfit(profit, weight, N);} Maximum profit earned is:440 Time Complexity: O(N)Auxiliary Space: O(N) Fraction Greedy Algorithms knapsack STL C++ Programs Competitive Programming Greedy Greedy STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Iterative Letter Combinations of a Phone Number cout in C++ Program to implement Singly Linked List in C++ using class Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25985, "s": 25957, "text": "\n19 Jul, 2020" }, { "code": null, "e": 26028, "s": 25985, "text": "Pre-requisite: Fractional Knapsack Problem" }, { "code": null, "e": 26266, "s": 26028, "text": "Given two arrays weight[] and profit[] the weights and profit of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.Note: Unlike 0/1 knapsack, you are allowed to break the item." }, { "code": null, "e": 26276, "s": 26266, "text": "Examples:" }, { "code": null, "e": 26511, "s": 26276, "text": "Input: weight[] = {10, 20, 30}, profit[] = {60, 100, 120}, N= 50Output: Maximum profit earned = 240Explanation: Decreasing p/w ratio[] = {6, 5, 4}Taking up the weight values 10, 20, (2 / 3) * 30 Profit = 60 + 100 + 120 * (2 / 3) = 240" }, { "code": null, "e": 26763, "s": 26511, "text": "Input: weight[] = {10, 40, 20, 24}, profit[] = {100, 280, 120, 120}, N = 60Output: Maximum profit earned = 440Explanation: Decreasing p/w ratio[] = {10, 7, 6, 5}Taking up the weight values 10, 40, (1 / 2) * 120 Profit = 100 + 280 + (1 / 2) * 120 = 440" }, { "code": null, "e": 26850, "s": 26763, "text": "Method 1 – without using STL: The idea is to use Greedy Approach. Below are the steps:" }, { "code": null, "e": 27130, "s": 26850, "text": " Find the ratio value/weight for each item and sort the item on the basis of this ratio.Choose the item with the highest ratio and add them until we can’t add the next item as a whole.In the end, add the next item as much as we can.Print the maximum profit after the above steps." }, { "code": null, "e": 27219, "s": 27130, "text": " Find the ratio value/weight for each item and sort the item on the basis of this ratio." }, { "code": null, "e": 27316, "s": 27219, "text": "Choose the item with the highest ratio and add them until we can’t add the next item as a whole." }, { "code": null, "e": 27365, "s": 27316, "text": "In the end, add the next item as much as we can." }, { "code": null, "e": 27413, "s": 27365, "text": "Print the maximum profit after the above steps." }, { "code": null, "e": 27465, "s": 27413, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27469, "s": 27465, "text": "C++" }, { "code": "// C++ program to solve fractional// Knapsack Problem#include <bits/stdc++.h> using namespace std; // Structure for an item which stores// weight & corresponding value of Itemstruct Item { int value, weight; // Constructor Item(int value, int weight) : value(value), weight(weight) { }}; // Comparison function to sort Item// according to val/weight ratiobool cmp(struct Item a, struct Item b){ double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2;} // Main greedy function to solve problemdouble fractionalKnapsack(struct Item arr[], int N, int size){ // Sort Item on basis of ratio sort(arr, arr + size, cmp); // Current weight in knapsack int curWeight = 0; // Result (value in Knapsack) double finalvalue = 0.0; // Looping through all Items for (int i = 0; i < size; i++) { // If adding Item won't overflow, // add it completely if (curWeight + arr[i].weight <= N) { curWeight += arr[i].weight; finalvalue += arr[i].value; } // If we can't add current Item, // add fractional part of it else { int remain = N - curWeight; finalvalue += arr[i].value * ((double)remain / arr[i].weight); break; } } // Returning final value return finalvalue;} // Driver Codeint main(){ // Weight of knapsack int N = 60; // Given weights and values as a pairs Item arr[] = { { 100, 10 }, { 280, 40 }, { 120, 20 }, { 120, 24 } }; int size = sizeof(arr) / sizeof(arr[0]); // Function Call cout << \"Maximum profit earned = \" << fractionalKnapsack(arr, N, size); return 0;}", "e": 29331, "s": 27469, "text": null }, { "code": null, "e": 29360, "s": 29331, "text": "Maximum profit earned = 440\n" }, { "code": null, "e": 29409, "s": 29360, "text": "Time Complexity: O(N*log2N)Auxiliary Space: O(1)" }, { "code": null, "e": 29431, "s": 29409, "text": "Method 2 – using STL:" }, { "code": null, "e": 29972, "s": 29431, "text": "Create a map with profit[i] / weight[i] as first and i as Second element for each element.Define a variable max_profit = 0.Traverse the map in reverse fashion:Create a variable named fraction whose value is equivalent to remaining_weight / weight[i].If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i].Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break.Print the max_profit." }, { "code": null, "e": 30063, "s": 29972, "text": "Create a map with profit[i] / weight[i] as first and i as Second element for each element." }, { "code": null, "e": 30097, "s": 30063, "text": "Define a variable max_profit = 0." }, { "code": null, "e": 30494, "s": 30097, "text": "Traverse the map in reverse fashion:Create a variable named fraction whose value is equivalent to remaining_weight / weight[i].If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i].Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break." }, { "code": null, "e": 30586, "s": 30494, "text": "Create a variable named fraction whose value is equivalent to remaining_weight / weight[i]." }, { "code": null, "e": 30759, "s": 30586, "text": "If remaining_weight is greater than or equals to zero and its value is greater than weight[i] add current profit to max_profit and reduce the remaining weight by weight[i]." }, { "code": null, "e": 30857, "s": 30759, "text": "Else if remaining weight is less than weight[i] add fraction * profit[i] to max_profit and break." }, { "code": null, "e": 30879, "s": 30857, "text": "Print the max_profit." }, { "code": null, "e": 30931, "s": 30879, "text": " Below is the implementation of the above approach:" }, { "code": null, "e": 30935, "s": 30931, "text": "C++" }, { "code": "// C++ program to Fractional Knapsack// Problem using STL#include <bits/stdc++.h>using namespace std; // Function to find maximum profitvoid maxProfit(vector<int> profit, vector<int> weight, int N){ // Number of total weights present int numOfElements = profit.size(); int i; // Multimap container to store // ratio and index multimap<double, int> ratio; // Variable to store maximum profit double max_profit = 0; for (i = 0; i < numOfElements; i++) { // Insert ratio profit[i] / weight[i] // and corresponding index ratio.insert(make_pair( (double)profit[i] / weight[i], i)); } // Declare a reverse iterator // for Multimap multimap<double, int>::reverse_iterator it; // Traverse the map in reverse order for (it = ratio.rbegin(); it != ratio.rend(); it++) { // Fraction of weight of i'th item // that can be kept in knapsack double fraction = (double)N / weight[it->second]; // if remaining_weight is greater // than the weight of i'th item if (N >= 0 && N >= weight[it->second]) { // increase max_profit by i'th // profit value max_profit += profit[it->second]; // decrement knapsack to form // new remaining_weight N -= weight[it->second]; } // remaining_weight less than // weight of i'th item else if (N < weight[it->second]) { max_profit += fraction * profit[it->second]; break; } } // Print the maximum profit earned cout << \"Maximum profit earned is:\" << max_profit;} // Driver Codeint main(){ // Size of list int size = 4; // Given profit and weight vector<int> profit(size), weight(size); // Profit of items profit[0] = 100, profit[1] = 280, profit[2] = 120, profit[3] = 120; // Weight of items weight[0] = 10, weight[1] = 40, weight[2] = 20, weight[3] = 24; // Capacity of knapsack int N = 60; // Function Call maxProfit(profit, weight, N);}", "e": 33084, "s": 30935, "text": null }, { "code": null, "e": 33114, "s": 33084, "text": "Maximum profit earned is:440\n" }, { "code": null, "e": 33157, "s": 33114, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 33166, "s": 33157, "text": "Fraction" }, { "code": null, "e": 33184, "s": 33166, "text": "Greedy Algorithms" }, { "code": null, "e": 33193, "s": 33184, "text": "knapsack" }, { "code": null, "e": 33197, "s": 33193, "text": "STL" }, { "code": null, "e": 33210, "s": 33197, "text": "C++ Programs" }, { "code": null, "e": 33234, "s": 33210, "text": "Competitive Programming" }, { "code": null, "e": 33241, "s": 33234, "text": "Greedy" }, { "code": null, "e": 33248, "s": 33241, "text": "Greedy" }, { "code": null, "e": 33252, "s": 33248, "text": "STL" }, { "code": null, "e": 33350, "s": 33252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33391, "s": 33350, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33412, "s": 33391, "text": "Const keyword in C++" }, { "code": null, "e": 33460, "s": 33412, "text": "Iterative Letter Combinations of a Phone Number" }, { "code": null, "e": 33472, "s": 33460, "text": "cout in C++" }, { "code": null, "e": 33531, "s": 33472, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 33574, "s": 33531, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 33617, "s": 33574, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 33658, "s": 33617, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33736, "s": 33658, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Python | Pandas Timedelta.seconds - GeeksforGeeks
14 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.seconds property in pandas.Timedelta is used to return Number of seconds. Syntax: Timedelta.seconds Parameters: None Returns: return the Number of seconds. Code #1: # importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000000111') # Print the Timedelta object print(td) print(td.seconds) 3 days 06:05:01.000000 21901 Code #2: # importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('7 days 15 min 3 s') # Print the Timedelta object print(td) print(td.seconds) 7 days 00:15:03 903 Code #3: # importing pandas as pd import pandas as pd import datetime # Create the Timedelta object td = pd.Timedelta(133, unit ='s') # Print the Timedelta object print(td) print(td.seconds) 0 days 00:02:13 133 Python pandas-timedelta Python-pandas 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 ? Different ways to create Pandas Dataframe Enumerate() in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON? isupper(), islower(), lower(), upper() in Python and their applications
[ { "code": null, "e": 24962, "s": 24934, "text": "\n14 Jan, 2019" }, { "code": null, "e": 25176, "s": 24962, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25445, "s": 25176, "text": "Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.seconds property in pandas.Timedelta is used to return Number of seconds." }, { "code": null, "e": 25471, "s": 25445, "text": "Syntax: Timedelta.seconds" }, { "code": null, "e": 25488, "s": 25471, "text": "Parameters: None" }, { "code": null, "e": 25527, "s": 25488, "text": "Returns: return the Number of seconds." }, { "code": null, "e": 25536, "s": 25527, "text": "Code #1:" }, { "code": "# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000000111') # Print the Timedelta object print(td) print(td.seconds)", "e": 25721, "s": 25536, "text": null }, { "code": null, "e": 25751, "s": 25721, "text": "3 days 06:05:01.000000\n21901\n" }, { "code": null, "e": 25760, "s": 25751, "text": "Code #2:" }, { "code": "# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('7 days 15 min 3 s') # Print the Timedelta object print(td) print(td.seconds)", "e": 25937, "s": 25760, "text": null }, { "code": null, "e": 25958, "s": 25937, "text": "7 days 00:15:03\n903\n" }, { "code": null, "e": 25967, "s": 25958, "text": "Code #3:" }, { "code": "# importing pandas as pd import pandas as pd import datetime # Create the Timedelta object td = pd.Timedelta(133, unit ='s') # Print the Timedelta object print(td) print(td.seconds)", "e": 26153, "s": 25967, "text": null }, { "code": null, "e": 26174, "s": 26153, "text": "0 days 00:02:13\n133\n" }, { "code": null, "e": 26198, "s": 26174, "text": "Python pandas-timedelta" }, { "code": null, "e": 26212, "s": 26198, "text": "Python-pandas" }, { "code": null, "e": 26219, "s": 26212, "text": "Python" }, { "code": null, "e": 26317, "s": 26219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26335, "s": 26317, "text": "Python Dictionary" }, { "code": null, "e": 26367, "s": 26335, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26409, "s": 26367, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26431, "s": 26409, "text": "Enumerate() in Python" }, { "code": null, "e": 26468, "s": 26431, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26497, "s": 26468, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26539, "s": 26497, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26575, "s": 26539, "text": "Convert integer to string in Python" }, { "code": null, "e": 26617, "s": 26575, "text": "How To Convert Python Dictionary To JSON?" } ]
Life Cycle Phases of Project Management - GeeksforGeeks
25 Mar, 2020 Life cycle phases consist of various separated modules with defined functionalities. Life cycle phases describe the various phases of project management. Life cycle phases are mainly divided into two broad categories: 1. Engineering Phase 2. Production Phase These are explained as following below. 1. Engineering Phase:Engineering phase involves establishing the goal and defines the overall scope of the project. Engineering phase involves the small team size and it is usually less predicted. Engineering phase is further divided into 2 Phases: Inception Phase, and Elaboration Phase. (i). Inception Phase –Inception Phase involves establishing goals and gathering the requirements needed for the software development. It involves the cost estimation and identifying the risk factors. In the inception phase, we mainly work on the scope of the project and architecture. Feasibility analysis is also an important part of the inception phase. (ii). Elaboration Phase –Elaboration phase involves in-depth evaluation and study as well as establishing the strong architecture and infrastructure. In the elaboration phase, we work on the efficiency of our architecture. In this phase, we also analyze use cases and other software diagrams. We reduce the risk to a certain extent and a preliminary user modules in prepared in this phase. 2. Production Phase:In the Production phase, we mainly focus on the Implementation of Project and optimization including the reduced cost and risk factors of our project. It also involves various testing for efficient deployment of the project. It involves the large team size and most of the time it is predictable. It is broadly divided into 2 Phases: Construction Phase, Transition Phase. (i). Construction Phase –In the construction phase, we perform the implementation of our software. In this phase, we minimize the risk and eliminate it. All the features and components are integrated into an application. In this phase, we perform strict testing and process optimization is done. We minimize the development cost and work to improve its efficiency.Construction phase mainly focuses on the implementation and testing of our software. (ii). Transition Phase –In the Transition phase, we perform strict testings mainly beta testing and deployment of software or project. After receiving the feedback from the user, we perform some changes in our software to make it more efficacious. In this phase, the developer works on a project with an user’s view to make software more supportable and user friendly. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DFD for Library Management System What is DFD(Data Flow Diagram)? Software Engineering | Software Design Process RUP and its Phases Software Engineering | Black box testing System Testing Software Development Life Cycle (SDLC) Software Engineering | Incremental process model Data Dictionaries in Software Engineering Use Case Diagram for Library Management System
[ { "code": null, "e": 24974, "s": 24946, "text": "\n25 Mar, 2020" }, { "code": null, "e": 25192, "s": 24974, "text": "Life cycle phases consist of various separated modules with defined functionalities. Life cycle phases describe the various phases of project management. Life cycle phases are mainly divided into two broad categories:" }, { "code": null, "e": 25234, "s": 25192, "text": "1. Engineering Phase\n2. Production Phase " }, { "code": null, "e": 25274, "s": 25234, "text": "These are explained as following below." }, { "code": null, "e": 25563, "s": 25274, "text": "1. Engineering Phase:Engineering phase involves establishing the goal and defines the overall scope of the project. Engineering phase involves the small team size and it is usually less predicted. Engineering phase is further divided into 2 Phases: Inception Phase, and Elaboration Phase." }, { "code": null, "e": 25919, "s": 25563, "text": "(i). Inception Phase –Inception Phase involves establishing goals and gathering the requirements needed for the software development. It involves the cost estimation and identifying the risk factors. In the inception phase, we mainly work on the scope of the project and architecture. Feasibility analysis is also an important part of the inception phase." }, { "code": null, "e": 26309, "s": 25919, "text": "(ii). Elaboration Phase –Elaboration phase involves in-depth evaluation and study as well as establishing the strong architecture and infrastructure. In the elaboration phase, we work on the efficiency of our architecture. In this phase, we also analyze use cases and other software diagrams. We reduce the risk to a certain extent and a preliminary user modules in prepared in this phase." }, { "code": null, "e": 26701, "s": 26309, "text": "2. Production Phase:In the Production phase, we mainly focus on the Implementation of Project and optimization including the reduced cost and risk factors of our project. It also involves various testing for efficient deployment of the project. It involves the large team size and most of the time it is predictable. It is broadly divided into 2 Phases: Construction Phase, Transition Phase." }, { "code": null, "e": 27150, "s": 26701, "text": "(i). Construction Phase –In the construction phase, we perform the implementation of our software. In this phase, we minimize the risk and eliminate it. All the features and components are integrated into an application. In this phase, we perform strict testing and process optimization is done. We minimize the development cost and work to improve its efficiency.Construction phase mainly focuses on the implementation and testing of our software." }, { "code": null, "e": 27519, "s": 27150, "text": "(ii). Transition Phase –In the Transition phase, we perform strict testings mainly beta testing and deployment of software or project. After receiving the feedback from the user, we perform some changes in our software to make it more efficacious. In this phase, the developer works on a project with an user’s view to make software more supportable and user friendly." }, { "code": null, "e": 27540, "s": 27519, "text": "Software Engineering" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27647, "s": 27638, "text": "Comments" }, { "code": null, "e": 27660, "s": 27647, "text": "Old Comments" }, { "code": null, "e": 27694, "s": 27660, "text": "DFD for Library Management System" }, { "code": null, "e": 27726, "s": 27694, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 27773, "s": 27726, "text": "Software Engineering | Software Design Process" }, { "code": null, "e": 27792, "s": 27773, "text": "RUP and its Phases" }, { "code": null, "e": 27833, "s": 27792, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 27848, "s": 27833, "text": "System Testing" }, { "code": null, "e": 27887, "s": 27848, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 27936, "s": 27887, "text": "Software Engineering | Incremental process model" }, { "code": null, "e": 27978, "s": 27936, "text": "Data Dictionaries in Software Engineering" } ]
Calculate Age from given Date of Birth in MySQL?
To calculate age in MySQL from Date of Birth, you can use the following syntax − SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(yourColumnName) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(yourColumnName, 5)) as anyVariableName from yourTableName; To understand the above concept, let us create a table. The following is the query to create a table. mysql> create table AgeCalculatesDemo −> ( −> YourDateOfBirth datetime −> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table with the help of insert command. These records are the DOBs through which we will calculate the age. The following is the query − mysql> insert into AgeCalculatesDemo values(date_add(now(),interval 22 year)); Query OK, 1 row affected (0.23 sec) mysql> truncate table AgeCalculatesDemo; Query OK, 0 rows affected (0.89 sec) mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -22 year)); Query OK, 1 row affected (0.16 sec) mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -12 year)); Query OK, 1 row affected (0.18 sec) mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -19 year)); Query OK, 1 row affected (0.15 sec) mysql> insert into AgeCalculatesDemo values('2010-4-05'); Query OK, 1 row affected (0.25 sec) Now you can display all records with the help of select statement. The following is the query − mysql> select *from AgeCalculatesDemo; The following is the output − +---------------------+ | YourDateOfBirth | +---------------------+ | 1996-12-06 23:35:26 | | 2006-12-06 23:35:32 | | 1999-12-06 23:35:42 | | 2010-04-05 00:00:00 | +---------------------+ 4 rows in set (0.00 sec) Here is the query that can be used to calculate age. mysql> SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(YourDateOfBirth) −> - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(YourDateOfBirth, 5)) as YourAge −> from AgeCalculatesDemo; The following is the output displaying age − +---------+ | YourAge | +---------+ | 22 | | 12 | | 19 | | 8 | +---------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "To calculate age in MySQL from Date of Birth, you can use the following syntax −" }, { "code": null, "e": 1295, "s": 1143, "text": "SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(yourColumnName)\n- (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(yourColumnName, 5)) as anyVariableName from yourTableName;" }, { "code": null, "e": 1397, "s": 1295, "text": "To understand the above concept, let us create a table. The following is the query to create a table." }, { "code": null, "e": 1520, "s": 1397, "text": "mysql> create table AgeCalculatesDemo\n −> (\n −> YourDateOfBirth datetime\n −> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1683, "s": 1520, "text": "Insert some records in the table with the help of insert command. These records are the DOBs through which we will calculate the age. The following is the query −" }, { "code": null, "e": 2323, "s": 1683, "text": "mysql> insert into AgeCalculatesDemo values(date_add(now(),interval 22 year));\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> truncate table AgeCalculatesDemo;\nQuery OK, 0 rows affected (0.89 sec)\n\nmysql> insert into AgeCalculatesDemo values(date_add(now(),interval -22 year));\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into AgeCalculatesDemo values(date_add(now(),interval -12 year));\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into AgeCalculatesDemo values(date_add(now(),interval -19 year));\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into AgeCalculatesDemo values('2010-4-05');\nQuery OK, 1 row affected (0.25 sec)" }, { "code": null, "e": 2419, "s": 2323, "text": "Now you can display all records with the help of select statement. The following is the query −" }, { "code": null, "e": 2458, "s": 2419, "text": "mysql> select *from AgeCalculatesDemo;" }, { "code": null, "e": 2488, "s": 2458, "text": "The following is the output −" }, { "code": null, "e": 2705, "s": 2488, "text": "+---------------------+\n| YourDateOfBirth |\n+---------------------+\n| 1996-12-06 23:35:26 |\n| 2006-12-06 23:35:32 |\n| 1999-12-06 23:35:42 |\n| 2010-04-05 00:00:00 |\n+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2758, "s": 2705, "text": "Here is the query that can be used to calculate age." }, { "code": null, "e": 2927, "s": 2758, "text": "mysql> SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(YourDateOfBirth)\n −> - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(YourDateOfBirth, 5)) as YourAge\n −> from AgeCalculatesDemo;" }, { "code": null, "e": 2972, "s": 2927, "text": "The following is the output displaying age −" }, { "code": null, "e": 3093, "s": 2972, "text": "+---------+\n| YourAge |\n+---------+\n| 22 |\n| 12 |\n| 19 |\n| 8 |\n+---------+\n4 rows in set (0.00 sec)" } ]
Linear Search Program in C
Here we present the implementation of linear search in C programming language. The output of the program is given after the code. #include <stdio.h> #define MAX 20 // array of items on which linear search will be conducted. int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66}; void printline(int count) { int i; for(i = 0;i <count-1;i++) { printf("="); } printf("=\n"); } // this method makes a linear search. int find(int data) { int comparisons = 0; int index = -1; int i; // navigate through all items for(i = 0;i<MAX;i++) { // count the comparisons made comparisons++; // if data found, break the loop if(data == intArray[i]) { index = i; break; } } printf("Total comparisons made: %d", comparisons); return index; } void display() { int i; printf("["); // navigate through all items for(i = 0;i<MAX;i++) { printf("%d ",intArray[i]); } printf("]\n"); } void main() { printf("Input Array: "); display(); printline(50); //find location of 1 int location = find(55); // if element was found if(location != -1) printf("\nElement found at location: %d" ,(location+1)); else printf("Element not found."); } If we compile and run the above program, it will produce the following result − Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ] ================================================== Total comparisons made: 19 Element found at location: 19 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2710, "s": 2580, "text": "Here we present the implementation of linear search in C programming language. The output of the program is given after the code." }, { "code": null, "e": 3892, "s": 2710, "text": "#include <stdio.h>\n\n#define MAX 20\n\n// array of items on which linear search will be conducted.\nint intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};\n\nvoid printline(int count) {\n int i;\n\t\n for(i = 0;i <count-1;i++) {\n printf(\"=\");\n }\n\t\n printf(\"=\\n\");\n}\n\n// this method makes a linear search. \nint find(int data) {\n\n int comparisons = 0;\n int index = -1;\n int i;\n\n // navigate through all items \n for(i = 0;i<MAX;i++) {\n\t\n // count the comparisons made \n comparisons++;\n\t\t\n // if data found, break the loop\n if(data == intArray[i]) {\n index = i;\n break;\n }\n } \n\t\n printf(\"Total comparisons made: %d\", comparisons);\n return index;\n}\n\nvoid display() {\n int i;\n printf(\"[\");\n\t\n // navigate through all items \n for(i = 0;i<MAX;i++) {\n printf(\"%d \",intArray[i]);\n }\n\t\n printf(\"]\\n\");\n}\n\nvoid main() {\n printf(\"Input Array: \");\n display();\n printline(50);\n\t\n //find location of 1\n int location = find(55);\n\n // if element was found \n if(location != -1)\n printf(\"\\nElement found at location: %d\" ,(location+1));\n else\n printf(\"Element not found.\");\n}" }, { "code": null, "e": 3972, "s": 3892, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 4150, "s": 3972, "text": "Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]\n==================================================\nTotal comparisons made: 19\nElement found at location: 19\n" }, { "code": null, "e": 4185, "s": 4150, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4197, "s": 4185, "text": " Ravi Kiran" }, { "code": null, "e": 4232, "s": 4197, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 4251, "s": 4232, "text": " Arnab Chakraborty" }, { "code": null, "e": 4286, "s": 4251, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4301, "s": 4286, "text": " Parth Panjabi" }, { "code": null, "e": 4334, "s": 4301, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4353, "s": 4334, "text": " Arnab Chakraborty" }, { "code": null, "e": 4387, "s": 4353, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4415, "s": 4387, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4451, "s": 4415, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4479, "s": 4451, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4486, "s": 4479, "text": " Print" }, { "code": null, "e": 4497, "s": 4486, "text": " Add Notes" } ]
Embed Interactive charts in Medium/Websites using Plotly and Chartstudio with Python | by Syam Kakarla | Towards Data Science
There is no such thing as information overload. There is only a bad design. — Edward Tufte We all know a picture is worth a thousand words, data visualization is the visual summary of the information that makes it easier to understand/identify patterns and trends instead of looking at thousands of rows in spreadsheets. A good data visualization place the meaning of complex datasets in a precise and concise way. An interactive data visualization makes it even easier to understand and find insights from the data. This article covers creating different interactive plots using Plotly and embedding interactive data visualizations in Medium and websites using Chartstudio. Let’s get started✨ Chartstudio is a platform that hosts your interactive plots/charts in the cloud. It has also developed open-source graphing Application Programming Interface (API) libraries for Python, R, MATLAB, Javascript, and other computer programming languages. The important features of Plotly and chartstudio are: It produces interactive graphs/charts. The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB, etc. Graphs can be exported in various raster as well as vector image formats Let’s see how to connect with chartstudio, Signup to chartstudio platform with credentials like Google, Facebook, Github, e.t.c.Go to Settings > API Keys, save the username and API Key. Signup to chartstudio platform with credentials like Google, Facebook, Github, e.t.c. Go to Settings > API Keys, save the username and API Key. The below code servers the purpose to connect with chartstudio using Python. chartstudio.tools.set_credentials_file takes username and api key to connect with the platform. To embed interactive plots on medium/Websites, we need to store the interactive plots using chartstudio. Let’s see how to save the interactive plots using the Chartstusio Python API. In this article, we are going to use gapminder dataset that contains data that includes one year of numerous country-level indicators of health, wealth, and development. The below code plots a pie chart of the population of Asia in 2007 w.r.t to each country. The plotly.express.pie() method is used to plot the chart. After creating the plot, we have to save it into the chartstudio cloud. To do that we use chart_studio.plotly.plot() method that talked figure object, filename, and other parameters. After executing the below line of code, it results in a hyperlink that can be used to embed in either Medium or other websites. py.plot(pop, filename = 'Population_Asia', auto_open=True)# Outputhttps://plotly.com/~syamkakarla98/41/ Paste the link in Medium to embed the interactive plots/charts. Not only Pie charts but you can also embed 3D Plots, Box plots, Distribution Plots, Multidimensional Plots, Tile Maps, e.t.c. You can also create classification charts using Plotly and embed them using chartstudio. the below example shows how to create a simple KNN classification chart for the synthetic circle's dataset from sklearn.datasets and the resultant figure is shown below. This article helps readers to create interactive plots and embedding them in either Medium or other Websites using Plotly and Chartstudio API with Python.
[ { "code": null, "e": 262, "s": 171, "text": "There is no such thing as information overload. There is only a bad design. — Edward Tufte" }, { "code": null, "e": 688, "s": 262, "text": "We all know a picture is worth a thousand words, data visualization is the visual summary of the information that makes it easier to understand/identify patterns and trends instead of looking at thousands of rows in spreadsheets. A good data visualization place the meaning of complex datasets in a precise and concise way. An interactive data visualization makes it even easier to understand and find insights from the data." }, { "code": null, "e": 846, "s": 688, "text": "This article covers creating different interactive plots using Plotly and embedding interactive data visualizations in Medium and websites using Chartstudio." }, { "code": null, "e": 865, "s": 846, "text": "Let’s get started✨" }, { "code": null, "e": 1170, "s": 865, "text": "Chartstudio is a platform that hosts your interactive plots/charts in the cloud. It has also developed open-source graphing Application Programming Interface (API) libraries for Python, R, MATLAB, Javascript, and other computer programming languages. The important features of Plotly and chartstudio are:" }, { "code": null, "e": 1209, "s": 1170, "text": "It produces interactive graphs/charts." }, { "code": null, "e": 1381, "s": 1209, "text": "The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB, etc." }, { "code": null, "e": 1454, "s": 1381, "text": "Graphs can be exported in various raster as well as vector image formats" }, { "code": null, "e": 1497, "s": 1454, "text": "Let’s see how to connect with chartstudio," }, { "code": null, "e": 1640, "s": 1497, "text": "Signup to chartstudio platform with credentials like Google, Facebook, Github, e.t.c.Go to Settings > API Keys, save the username and API Key." }, { "code": null, "e": 1726, "s": 1640, "text": "Signup to chartstudio platform with credentials like Google, Facebook, Github, e.t.c." }, { "code": null, "e": 1784, "s": 1726, "text": "Go to Settings > API Keys, save the username and API Key." }, { "code": null, "e": 1957, "s": 1784, "text": "The below code servers the purpose to connect with chartstudio using Python. chartstudio.tools.set_credentials_file takes username and api key to connect with the platform." }, { "code": null, "e": 2140, "s": 1957, "text": "To embed interactive plots on medium/Websites, we need to store the interactive plots using chartstudio. Let’s see how to save the interactive plots using the Chartstusio Python API." }, { "code": null, "e": 2310, "s": 2140, "text": "In this article, we are going to use gapminder dataset that contains data that includes one year of numerous country-level indicators of health, wealth, and development." }, { "code": null, "e": 2459, "s": 2310, "text": "The below code plots a pie chart of the population of Asia in 2007 w.r.t to each country. The plotly.express.pie() method is used to plot the chart." }, { "code": null, "e": 2770, "s": 2459, "text": "After creating the plot, we have to save it into the chartstudio cloud. To do that we use chart_studio.plotly.plot() method that talked figure object, filename, and other parameters. After executing the below line of code, it results in a hyperlink that can be used to embed in either Medium or other websites." }, { "code": null, "e": 2874, "s": 2770, "text": "py.plot(pop, filename = 'Population_Asia', auto_open=True)# Outputhttps://plotly.com/~syamkakarla98/41/" }, { "code": null, "e": 2938, "s": 2874, "text": "Paste the link in Medium to embed the interactive plots/charts." }, { "code": null, "e": 3064, "s": 2938, "text": "Not only Pie charts but you can also embed 3D Plots, Box plots, Distribution Plots, Multidimensional Plots, Tile Maps, e.t.c." }, { "code": null, "e": 3323, "s": 3064, "text": "You can also create classification charts using Plotly and embed them using chartstudio. the below example shows how to create a simple KNN classification chart for the synthetic circle's dataset from sklearn.datasets and the resultant figure is shown below." } ]
Tryit Editor v3.7
Tryit: The border property
[]
How to convert string to numerical values in MongoDB?
You need to use some code in order to convert a string to numerical values in MongoDB. Let us first create a collection with a document. The query to create a collection with a document is as follows: > db.convertStringToNumberDemo.insertOne({"EmployeeId":"101","EmployeeName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f56528d10a061296a3c31") } > db.convertStringToNumberDemo.insertOne({"EmployeeId":"1120","EmployeeName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f56648d10a061296a3c32") } > db.convertStringToNumberDemo.insertOne({"EmployeeId":"3210","EmployeeName":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f566e8d10a061296a3c33") } Display all documents from the collection with the help of find() method. The query is as follows − > db.convertStringToNumberDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c7f56528d10a061296a3c31"), "EmployeeId" : "101", "EmployeeName" : "Larry" } { "_id" : ObjectId("5c7f56648d10a061296a3c32"), "EmployeeId" : "1120", "EmployeeName" : "Mike" } { "_id" : ObjectId("5c7f566e8d10a061296a3c33"), "EmployeeId" : "3210", "EmployeeName" : "Sam" } Here is the query to convert a string to numerical values in MongoDB. Change “EmployeeId” string to numerical values. The query is as follows − > db.convertStringToNumberDemo.find().forEach(function(x) ... { ... db.convertStringToNumberDemo.update ... ( ... ... { ... "_id": x._id, ... ... }, ... { ... "$set": ... { ... "EmployeeId": parseInt(x.EmployeeId) ... } ... } ... ) ... } ... ); Now check the documents from the collection. The query is as follows − > db.convertStringToNumberDemo.find().pretty(); The following is the output displaying the string values (EmployeeId) converted to an integer − { "_id" : ObjectId("5c7f56528d10a061296a3c31"), "EmployeeId" : 101, "EmployeeName" : "Larry" } { "_id" : ObjectId("5c7f56648d10a061296a3c32"), "EmployeeId" : 1120, "EmployeeName" : "Mike" } { "_id" : ObjectId("5c7f566e8d10a061296a3c33"), "EmployeeId" : 3210, "EmployeeName" : "Sam" }
[ { "code": null, "e": 1149, "s": 1062, "text": "You need to use some code in order to convert a string to numerical values in MongoDB." }, { "code": null, "e": 1263, "s": 1149, "text": "Let us first create a collection with a document. The query to create a collection with a document is as follows:" }, { "code": null, "e": 1778, "s": 1263, "text": "> db.convertStringToNumberDemo.insertOne({\"EmployeeId\":\"101\",\"EmployeeName\":\"Larry\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7f56528d10a061296a3c31\")\n}\n> db.convertStringToNumberDemo.insertOne({\"EmployeeId\":\"1120\",\"EmployeeName\":\"Mike\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7f56648d10a061296a3c32\")\n}\n> db.convertStringToNumberDemo.insertOne({\"EmployeeId\":\"3210\",\"EmployeeName\":\"Sam\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7f566e8d10a061296a3c33\")\n}" }, { "code": null, "e": 1878, "s": 1778, "text": "Display all documents from the collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 1926, "s": 1878, "text": "> db.convertStringToNumberDemo.find().pretty();" }, { "code": null, "e": 1956, "s": 1926, "text": "The following is the output −" }, { "code": null, "e": 2273, "s": 1956, "text": "{\n \"_id\" : ObjectId(\"5c7f56528d10a061296a3c31\"),\n \"EmployeeId\" : \"101\",\n \"EmployeeName\" : \"Larry\"\n}\n{\n \"_id\" : ObjectId(\"5c7f56648d10a061296a3c32\"),\n \"EmployeeId\" : \"1120\",\n \"EmployeeName\" : \"Mike\"\n}\n{\n \"_id\" : ObjectId(\"5c7f566e8d10a061296a3c33\"),\n \"EmployeeId\" : \"3210\",\n \"EmployeeName\" : \"Sam\"\n}" }, { "code": null, "e": 2417, "s": 2273, "text": "Here is the query to convert a string to numerical values in MongoDB. Change “EmployeeId” string to numerical values. The query is as follows −" }, { "code": null, "e": 2806, "s": 2417, "text": "> db.convertStringToNumberDemo.find().forEach(function(x)\n ... {\n ... db.convertStringToNumberDemo.update\n ... (\n ...\n ... {\n ... \"_id\": x._id,\n ...\n ... },\n ... {\n ... \"$set\":\n ... {\n ... \"EmployeeId\": parseInt(x.EmployeeId)\n ... }\n ... }\n ... )\n ... }\n... );" }, { "code": null, "e": 2877, "s": 2806, "text": "Now check the documents from the collection. The query is as follows −" }, { "code": null, "e": 2925, "s": 2877, "text": "> db.convertStringToNumberDemo.find().pretty();" }, { "code": null, "e": 3021, "s": 2925, "text": "The following is the output displaying the string values (EmployeeId) converted to an integer −" }, { "code": null, "e": 3332, "s": 3021, "text": "{\n \"_id\" : ObjectId(\"5c7f56528d10a061296a3c31\"),\n \"EmployeeId\" : 101,\n \"EmployeeName\" : \"Larry\"\n}\n{\n \"_id\" : ObjectId(\"5c7f56648d10a061296a3c32\"),\n \"EmployeeId\" : 1120,\n \"EmployeeName\" : \"Mike\"\n}\n{\n \"_id\" : ObjectId(\"5c7f566e8d10a061296a3c33\"),\n \"EmployeeId\" : 3210,\n \"EmployeeName\" : \"Sam\"\n}" } ]
Updating a MySQL table with values from another table?
We can update another table with the help of inner join. Let us create two tables. mysql> CREATE table tblFirst -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.48 sec) mysql> INSERT into tblFirst values(1,'John'); Query OK, 1 row affected (0.17 sec) mysql> INSERT into tblFirst values(2,'Bob'); Query OK, 1 row affected (0.26 sec) mysql> INSERT into tblFirst values(3,'David'); Query OK, 1 row affected (0.20 sec) mysql> SELECT * from tblFirst; The following is the output +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Bob | | 3 | David | +------+-------+ 3 rows in set (0.00 sec) mysql> CREATE table UpdTable -> ( -> IncId int auto_increment, -> primary key(IncId), -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.57 sec) mysql> INSERT into UpdTable(id,name) values(1,'Taylor'); Query OK, 1 row affected (0.12 sec) mysql> INSERT into UpdTable(id,name) values(2,'jason'); Query OK, 1 row affected (0.24 sec) mysql> INSERT into UpdTable(id,name) values(3,'carol'); Query OK, 1 row affected (0.14 sec) mysql> INSERT into UpdTable(id,name) values(4,'john'); Query OK, 1 row affected (0.16 sec) mysql> SELECT * from UpdTable; The following is the output mysql> SELECT *from UpdTable; +-------+------+--------+ | IncId | id | name | +-------+------+--------+ | 1 | 1 | Taylor | | 2 | 2 | jason | | 3 | 3 | carol | | 4 | 4 | john | +-------+------+--------+ 4 rows in set (0.00 sec) Look at the above output, the last name is matching from the first table record. Now, I will write the query for UPDATE − mysql> UPDATE UpdTable -> inner join tblFirst ON (UpdTable.name = tblFirst.name) -> SET UpdTable.id = tblFirst.id; Query OK, 1 row affected (0.19 sec) Rows matched: 1 Changed: 1 Warnings: 0 We have updated the last record as follows − The query is mysql> SELECT * from UpdTable; The following is the output +-------+------+--------+ | IncId | id | name | +-------+------+--------+ | 1 | 1 | Taylor | | 2 | 2 | jason | | 3 | 3 | carol | | 4 | 1 | john | +-------+------+--------+ 4 rows in set (0.00 sec) Look at the sample output. The id is updated, which was 4 but now it is 1.
[ { "code": null, "e": 1145, "s": 1062, "text": "We can update another table with the help of inner join. Let us create two tables." }, { "code": null, "e": 1267, "s": 1145, "text": "mysql> CREATE table tblFirst\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.48 sec)\n" }, { "code": null, "e": 1516, "s": 1267, "text": "mysql> INSERT into tblFirst values(1,'John');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> INSERT into tblFirst values(2,'Bob');\nQuery OK, 1 row affected (0.26 sec)\n\nmysql> INSERT into tblFirst values(3,'David');\nQuery OK, 1 row affected (0.20 sec)\n" }, { "code": null, "e": 1548, "s": 1516, "text": "mysql> SELECT * from tblFirst;\n" }, { "code": null, "e": 1576, "s": 1548, "text": "The following is the output" }, { "code": null, "e": 1721, "s": 1576, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Bob |\n| 3 | David |\n+------+-------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 1901, "s": 1721, "text": "mysql> CREATE table UpdTable\n -> (\n -> IncId int auto_increment,\n -> primary key(IncId),\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.57 sec)\n" }, { "code": null, "e": 2273, "s": 1901, "text": "mysql> INSERT into UpdTable(id,name) values(1,'Taylor');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT into UpdTable(id,name) values(2,'jason');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> INSERT into UpdTable(id,name) values(3,'carol');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> INSERT into UpdTable(id,name) values(4,'john');\nQuery OK, 1 row affected (0.16 sec)\n" }, { "code": null, "e": 2305, "s": 2273, "text": "mysql> SELECT * from UpdTable;\n" }, { "code": null, "e": 2333, "s": 2305, "text": "The following is the output" }, { "code": null, "e": 2597, "s": 2333, "text": "mysql> SELECT *from UpdTable;\n+-------+------+--------+\n| IncId | id | name |\n+-------+------+--------+\n| 1 | 1 | Taylor |\n| 2 | 2 | jason |\n| 3 | 3 | carol |\n| 4 | 4 | john |\n+-------+------+--------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 2719, "s": 2597, "text": "Look at the above output, the last name is matching from the first table record.\nNow, I will write the query for UPDATE −" }, { "code": null, "e": 2916, "s": 2719, "text": "mysql> UPDATE UpdTable\n -> inner join tblFirst ON (UpdTable.name = tblFirst.name)\n -> SET UpdTable.id = tblFirst.id;\nQuery OK, 1 row affected (0.19 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n" }, { "code": null, "e": 2961, "s": 2916, "text": "We have updated the last record as follows −" }, { "code": null, "e": 2974, "s": 2961, "text": "The query is" }, { "code": null, "e": 3006, "s": 2974, "text": "mysql> SELECT * from UpdTable;\n" }, { "code": null, "e": 3034, "s": 3006, "text": "The following is the output" }, { "code": null, "e": 3268, "s": 3034, "text": "+-------+------+--------+\n| IncId | id | name |\n+-------+------+--------+\n| 1 | 1 | Taylor |\n| 2 | 2 | jason |\n| 3 | 3 | carol |\n| 4 | 1 | john |\n+-------+------+--------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 3343, "s": 3268, "text": "Look at the sample output. The id is updated, which was 4 but now it is 1." } ]
Optimizing Face Detection on your browser with Tensorflow.js | by Siddhant Baldota | Towards Data Science
Let’s jump on to the most important question. You might have come across a lot of face detection tutorials and projects. This one is different though. It is deployed on the browser and can be used anywhere from proctoring online exams to many different arcade games to using it for detecting face masks, blurring or improving the resolution of the face in real-time (since the region of interest is obtained) while also performing at quite high speeds. Machine learning on the web is the requirement of this age and shouldn’t be restricted to local systems. An alternative approach is face-api.js which uses the Multi-Task CNN but our detector has higher accuracy. Many other projects would be based on face detection models deployed on Flask Apps which are quite slow in comparison. Tensorflow serving makes use of gRPC and Protobuf while Flask apps use REST and JSON. JSON relies on HTTP 1.1 while gRPC uses HTTP/2. HTTP 1.1 suffers from latency issues. A TCP handshake is needed for each individual request, and a large number of requests takes a significant toll on the time needed to load a page. HTTP 1.1 also suffers from Head of Line Blocking which restricts the number of connections to the same domain. With HTTP pipelining, you can send a request while waiting for the response to a previous request, effectively creating a queue. But that introduces other problems. If your request gets stuck behind a slow request then your response time will suffer. HTTP /2 maintains the basic premises and paradigms of HTTP but does away with optional parts of HTTP 1.1. REST supports only the request-response model available in HTTP 1.x. But gRPC takes full advantage of the capabilities of HTTP/2 and lets you stream information constantly. Protobuf is a binary format used to serialize data and is more efficient than JSON. Tensorflow serving can batch requests to the same model, which uses hardware (GPUs) more appropriately. Tensorflow serving has performance equal to code written in C/C++. Moreover, Flask apps are written in Python whereas Tensorflow.js has Node.js or Chrome V8 engine as its server side node. In this project, we use Chrome’s V8 Javascript engine which is an open source high-performance JavaScript engine. To get more intuition on the Chrome V8 engine, read this awesome blog at www.freecodecamp.org Tensorflow.js provides the right kind of hardware acceleration needed using the Web GL layer, which might be considered as a browser-side GPU. WebGL is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing GPU-accelerated usage of physics and image processing and effects as part of the web page canvas. Thus this client side serving face-detector proves to be quicker than the erstwhile flask face detection apps. Tensorflow.js is a machine learning library in Javascript. It is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models. It can be used to develop ML in the browser by using flexible and intuitive APIs to build models from scratch using the low-level JavaScript linear algebra library or the high-level layers API. It can also be used to develop ML in Node.js by running native TensorFlow with the same TensorFlow.js API under the Node.js runtime. Pretrained Tensorflow or Keras models can be used in the browser by the TensorFlow.js model converters. Tensorflow.js can also retrain pre-existing model using sensor data-connected to the browser. To know more about Tensorflow.js , you can check out the official documenation. www.tensorflow.org To get pretrained models, you can clone the following official tfjs GitHub repository github.com A text editor (optional) (Sublime, Brackets, Visual Studio Code, etc.) You can download the Brackets editor from brackets.io Google Chrome www.google.com To use the browser based face detector, check out my GitHub repository github.co If you want to get hands on and do things on your own, here’s a guide Create a starter HTML file Add the following lines to the html file tensorflow.js headers to import the tfjs model in the head tag <script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script><script src=”https://cdn.jsdelivr.net/npm/@tensorflow-models/blazeface"></script> Styling (optional): Create the div(s) for formatting and add the style-sheet link. Add the video element and the canvas Add the JavaScript file link in which the model is loaded Rename your file to index.html Your index.html file should look like this Create a main.css file for some optional styling. Add the following code to it. Change as per convenience You can get some lovely CSS at codepen.io Note: The main.css load a GIF which is for intial loading and is included in the repository. Feel free to use your own GIFs. Create a blaze_pred.js file. Add the following code to it. Explanation We create a self calling function in which we obtain the canvas and video elements by their id. To get the context for the canvas, we use the getContext() method. To recieve the video feed using the navigator.getUserMedia method and adding the stream to the video source object. video.play() is used to play the video but since we have set the visibility to false in the video element of the index.html file, the video feed cannot be physically viewed. The feed which is displayed is the canvas. The face predictions are drawn using the canvas context. To synchronize the video feed and the canvas element, we add an event listener and call a function draw which draws the predictions to it. Create an asynchronous draw function with parameters as the video feed, context, the width and height of the canvas. Draw the current frame of the video feed on it. Load the model using await blazeface.load(). Get the predictions on the model await model.estimateFaces() while setting the returnTensors parameter to false. Draw the bounding box on the canvas context using the predictions tensor. Obtain the confidence score using the predictions tensor and add the text to the canvas context relative to the bounding box. To call the draw function repeatedly set the timeout as 250 ms. Add the working files (index.html, main.css, blaze_pred.js) to a folder. Name the folder tfjs-face_detection. You can give any other name too. If you haven’t done the replication steps, type the following in your shell/terminal/command prompt git clone https://github.com/sid0312/tfjs-face_detection For Linux and Mac Users, user@username:~$ cd tfjs-face_detectionuser@username:~/tfjs-face_detection$ google-chrome index.html For Windows Users, C:\Users\username> cd tfjs-face_detectionC:\Users\username\tfjs-face_detection> index.html Allow access to the webcam Wait for a few seconds and you’re all set! We have successfully detected our face on the browser using Tensorflow.js. You can create your own deep learning face model and convert it into a tfjs model using the tfjs model converter to increase its robustness. Yeah! The one in the video feed is me! Check out my other articles: towardsdatascience.com towardsdatascience.com Happy Computer Vision, Happy Deep Learning and Happy Deployment. Until next time!
[ { "code": null, "e": 218, "s": 172, "text": "Let’s jump on to the most important question." }, { "code": null, "e": 956, "s": 218, "text": "You might have come across a lot of face detection tutorials and projects. This one is different though. It is deployed on the browser and can be used anywhere from proctoring online exams to many different arcade games to using it for detecting face masks, blurring or improving the resolution of the face in real-time (since the region of interest is obtained) while also performing at quite high speeds. Machine learning on the web is the requirement of this age and shouldn’t be restricted to local systems. An alternative approach is face-api.js which uses the Multi-Task CNN but our detector has higher accuracy. Many other projects would be based on face detection models deployed on Flask Apps which are quite slow in comparison." }, { "code": null, "e": 2170, "s": 956, "text": "Tensorflow serving makes use of gRPC and Protobuf while Flask apps use REST and JSON. JSON relies on HTTP 1.1 while gRPC uses HTTP/2. HTTP 1.1 suffers from latency issues. A TCP handshake is needed for each individual request, and a large number of requests takes a significant toll on the time needed to load a page. HTTP 1.1 also suffers from Head of Line Blocking which restricts the number of connections to the same domain. With HTTP pipelining, you can send a request while waiting for the response to a previous request, effectively creating a queue. But that introduces other problems. If your request gets stuck behind a slow request then your response time will suffer. HTTP /2 maintains the basic premises and paradigms of HTTP but does away with optional parts of HTTP 1.1. REST supports only the request-response model available in HTTP 1.x. But gRPC takes full advantage of the capabilities of HTTP/2 and lets you stream information constantly. Protobuf is a binary format used to serialize data and is more efficient than JSON. Tensorflow serving can batch requests to the same model, which uses hardware (GPUs) more appropriately. Tensorflow serving has performance equal to code written in C/C++." }, { "code": null, "e": 2406, "s": 2170, "text": "Moreover, Flask apps are written in Python whereas Tensorflow.js has Node.js or Chrome V8 engine as its server side node. In this project, we use Chrome’s V8 Javascript engine which is an open source high-performance JavaScript engine." }, { "code": null, "e": 2479, "s": 2406, "text": "To get more intuition on the Chrome V8 engine, read this awesome blog at" }, { "code": null, "e": 2500, "s": 2479, "text": "www.freecodecamp.org" }, { "code": null, "e": 2936, "s": 2500, "text": "Tensorflow.js provides the right kind of hardware acceleration needed using the Web GL layer, which might be considered as a browser-side GPU. WebGL is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing GPU-accelerated usage of physics and image processing and effects as part of the web page canvas." }, { "code": null, "e": 3047, "s": 2936, "text": "Thus this client side serving face-detector proves to be quicker than the erstwhile flask face detection apps." }, { "code": null, "e": 3219, "s": 3047, "text": "Tensorflow.js is a machine learning library in Javascript. It is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models." }, { "code": null, "e": 3744, "s": 3219, "text": "It can be used to develop ML in the browser by using flexible and intuitive APIs to build models from scratch using the low-level JavaScript linear algebra library or the high-level layers API. It can also be used to develop ML in Node.js by running native TensorFlow with the same TensorFlow.js API under the Node.js runtime. Pretrained Tensorflow or Keras models can be used in the browser by the TensorFlow.js model converters. Tensorflow.js can also retrain pre-existing model using sensor data-connected to the browser." }, { "code": null, "e": 3824, "s": 3744, "text": "To know more about Tensorflow.js , you can check out the official documenation." }, { "code": null, "e": 3843, "s": 3824, "text": "www.tensorflow.org" }, { "code": null, "e": 3929, "s": 3843, "text": "To get pretrained models, you can clone the following official tfjs GitHub repository" }, { "code": null, "e": 3940, "s": 3929, "text": "github.com" }, { "code": null, "e": 4011, "s": 3940, "text": "A text editor (optional) (Sublime, Brackets, Visual Studio Code, etc.)" }, { "code": null, "e": 4053, "s": 4011, "text": "You can download the Brackets editor from" }, { "code": null, "e": 4065, "s": 4053, "text": "brackets.io" }, { "code": null, "e": 4079, "s": 4065, "text": "Google Chrome" }, { "code": null, "e": 4094, "s": 4079, "text": "www.google.com" }, { "code": null, "e": 4165, "s": 4094, "text": "To use the browser based face detector, check out my GitHub repository" }, { "code": null, "e": 4175, "s": 4165, "text": "github.co" }, { "code": null, "e": 4245, "s": 4175, "text": "If you want to get hands on and do things on your own, here’s a guide" }, { "code": null, "e": 4272, "s": 4245, "text": "Create a starter HTML file" }, { "code": null, "e": 4376, "s": 4272, "text": "Add the following lines to the html file tensorflow.js headers to import the tfjs model in the head tag" }, { "code": null, "e": 4527, "s": 4376, "text": "<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs\"></script><script src=”https://cdn.jsdelivr.net/npm/@tensorflow-models/blazeface\"></script>" }, { "code": null, "e": 4647, "s": 4527, "text": "Styling (optional): Create the div(s) for formatting and add the style-sheet link. Add the video element and the canvas" }, { "code": null, "e": 4705, "s": 4647, "text": "Add the JavaScript file link in which the model is loaded" }, { "code": null, "e": 4736, "s": 4705, "text": "Rename your file to index.html" }, { "code": null, "e": 4779, "s": 4736, "text": "Your index.html file should look like this" }, { "code": null, "e": 4885, "s": 4779, "text": "Create a main.css file for some optional styling. Add the following code to it. Change as per convenience" }, { "code": null, "e": 4916, "s": 4885, "text": "You can get some lovely CSS at" }, { "code": null, "e": 4927, "s": 4916, "text": "codepen.io" }, { "code": null, "e": 5052, "s": 4927, "text": "Note: The main.css load a GIF which is for intial loading and is included in the repository. Feel free to use your own GIFs." }, { "code": null, "e": 5111, "s": 5052, "text": "Create a blaze_pred.js file. Add the following code to it." }, { "code": null, "e": 5123, "s": 5111, "text": "Explanation" }, { "code": null, "e": 5286, "s": 5123, "text": "We create a self calling function in which we obtain the canvas and video elements by their id. To get the context for the canvas, we use the getContext() method." }, { "code": null, "e": 5402, "s": 5286, "text": "To recieve the video feed using the navigator.getUserMedia method and adding the stream to the video source object." }, { "code": null, "e": 5676, "s": 5402, "text": "video.play() is used to play the video but since we have set the visibility to false in the video element of the index.html file, the video feed cannot be physically viewed. The feed which is displayed is the canvas. The face predictions are drawn using the canvas context." }, { "code": null, "e": 5815, "s": 5676, "text": "To synchronize the video feed and the canvas element, we add an event listener and call a function draw which draws the predictions to it." }, { "code": null, "e": 5932, "s": 5815, "text": "Create an asynchronous draw function with parameters as the video feed, context, the width and height of the canvas." }, { "code": null, "e": 6402, "s": 5932, "text": "Draw the current frame of the video feed on it. Load the model using await blazeface.load(). Get the predictions on the model await model.estimateFaces() while setting the returnTensors parameter to false. Draw the bounding box on the canvas context using the predictions tensor. Obtain the confidence score using the predictions tensor and add the text to the canvas context relative to the bounding box. To call the draw function repeatedly set the timeout as 250 ms." }, { "code": null, "e": 6545, "s": 6402, "text": "Add the working files (index.html, main.css, blaze_pred.js) to a folder. Name the folder tfjs-face_detection. You can give any other name too." }, { "code": null, "e": 6645, "s": 6545, "text": "If you haven’t done the replication steps, type the following in your shell/terminal/command prompt" }, { "code": null, "e": 6702, "s": 6645, "text": "git clone https://github.com/sid0312/tfjs-face_detection" }, { "code": null, "e": 6727, "s": 6702, "text": "For Linux and Mac Users," }, { "code": null, "e": 6828, "s": 6727, "text": "user@username:~$ cd tfjs-face_detectionuser@username:~/tfjs-face_detection$ google-chrome index.html" }, { "code": null, "e": 6847, "s": 6828, "text": "For Windows Users," }, { "code": null, "e": 6938, "s": 6847, "text": "C:\\Users\\username> cd tfjs-face_detectionC:\\Users\\username\\tfjs-face_detection> index.html" }, { "code": null, "e": 6965, "s": 6938, "text": "Allow access to the webcam" }, { "code": null, "e": 7008, "s": 6965, "text": "Wait for a few seconds and you’re all set!" }, { "code": null, "e": 7224, "s": 7008, "text": "We have successfully detected our face on the browser using Tensorflow.js. You can create your own deep learning face model and convert it into a tfjs model using the tfjs model converter to increase its robustness." }, { "code": null, "e": 7292, "s": 7224, "text": "Yeah! The one in the video feed is me! Check out my other articles:" }, { "code": null, "e": 7315, "s": 7292, "text": "towardsdatascience.com" }, { "code": null, "e": 7338, "s": 7315, "text": "towardsdatascience.com" } ]
How to cast from VARCHAR to INT in MySQL?
To cast VARCHAR to INT, we can use the cast() function from MySQL. Here is the syntax of cast() function. cast(anyValue as dataType) For our example, we will create a table with the help of create command. mysql> create table VarchartointDemo -> ( -> Value varchar(100) -> ); Query OK, 0 rows affected (0.51 sec) After creating a table, let us insert some records into the table with the help of INSERT command. The query is as follows − mysql> insert into VarchartointDemo values('123'); Query OK, 1 row affected (0.26 sec) mysql> insert into VarchartointDemo values('234'); Query OK, 1 row affected (0.16 sec) Display all records with the help of select statement. mysql> select *from VarchartointDemo; The following is the output. +-------+ | Value | +-------+ | 123 | | 234 | +-------+ 2 rows in set (0.00 sec) Cast varchar to int using the following syntax. SELECT CAST(yourColumnName AS anyDataType) FROM yourTableName; Apply the above syntax to cast varchar to int. mysql> SELECT CAST(Value AS UNSIGNED) FROM VarchartointDemo; The following is the output. +-------------------------+ | CAST(Value AS UNSIGNED) | +-------------------------+ | 123 | | 234 | +-------------------------+ 2 rows in set (0.00 sec) Look at the above output, we have changed varchar to int.
[ { "code": null, "e": 1168, "s": 1062, "text": "To cast VARCHAR to INT, we can use the cast() function from MySQL. Here is the syntax of cast() function." }, { "code": null, "e": 1195, "s": 1168, "text": "cast(anyValue as dataType)" }, { "code": null, "e": 1268, "s": 1195, "text": "For our example, we will create a table with the help of create command." }, { "code": null, "e": 1384, "s": 1268, "text": "mysql> create table VarchartointDemo\n -> (\n -> Value varchar(100)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1509, "s": 1384, "text": "After creating a table, let us insert some records into the table with the help of INSERT command. The query is as follows −" }, { "code": null, "e": 1684, "s": 1509, "text": "mysql> insert into VarchartointDemo values('123');\nQuery OK, 1 row affected (0.26 sec)\n\nmysql> insert into VarchartointDemo values('234');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1739, "s": 1684, "text": "Display all records with the help of select statement." }, { "code": null, "e": 1777, "s": 1739, "text": "mysql> select *from VarchartointDemo;" }, { "code": null, "e": 1806, "s": 1777, "text": "The following is the output." }, { "code": null, "e": 1892, "s": 1806, "text": "+-------+\n| Value |\n+-------+\n| 123 |\n| 234 |\n+-------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 1940, "s": 1892, "text": "Cast varchar to int using the following syntax." }, { "code": null, "e": 2003, "s": 1940, "text": "SELECT CAST(yourColumnName AS anyDataType) FROM yourTableName;" }, { "code": null, "e": 2050, "s": 2003, "text": "Apply the above syntax to cast varchar to int." }, { "code": null, "e": 2111, "s": 2050, "text": "mysql> SELECT CAST(Value AS UNSIGNED) FROM VarchartointDemo;" }, { "code": null, "e": 2140, "s": 2111, "text": "The following is the output." }, { "code": null, "e": 2334, "s": 2140, "text": "+-------------------------+\n| CAST(Value AS UNSIGNED) |\n+-------------------------+\n| 123 |\n| 234 |\n+-------------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 2392, "s": 2334, "text": "Look at the above output, we have changed varchar to int." } ]
Tutorial on Binary Tree - GeeksforGeeks
08 Apr, 2021 The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right is called “Right sub-tree”. Below are the various operations that can be performed on a Binary Tree: The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. Below is the program to illustrate the same: C++ // C++ program to illustrate how to // create a tree #include <iostream> using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to perform the inorder // traversal of the given Tree void inorder(struct treenode* root) { // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << " "; inorder(root->right); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) In this traversal, the root is visited first followed by the left and the right subtree. Below is the program to illustrate the same: C++ // C++ program to demonstrate the // pre-order traversal #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to perform the pre-order // traversal for the given tree void preorder(struct treenode* root) { // If the root is NULL if (root == NULL) return; // Using tree-node type stack STL stack<treenode*> s; while ((root != NULL) || (!s.empty())) { if (root != NULL) { // Print the root cout << root->info << " "; // Push the node in the stack s.push(root); // Move to left subtree root = root->left; } else { // Remove the top of stack root = s.top(); s.pop(); root = root->right; } } cout << endl; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal preorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the left subtree is visited first followed by the root and the right subtree. Below is the program to illustrate the same: C++ // C++ program to illustrate how to // create a tree #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to perform the inorder // traversal of the given Tree void inorder(struct treenode* root) { // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << " "; inorder(root->right); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the left subtree is visited first, followed by the right subtree and root node. Below is the program to illustrate the same: C++ // C++ program to implement the // post-order traversal #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to perform the post-order // traversal of the given tree void postorder(struct treenode* root) { // If the root is NULL return; stack<treenode*> s3; struct treenode* previous = NULL; do { // Iterate until root is present while (root != NULL) { s3.push(root); root = root->left; } while (root == NULL && (!s3.empty())) { root = s3.top(); // If the right subtree is NULL if (root->right == NULL || root->right == previous) { // Print the root information cout << root->info << " "; s3.pop(); // Update the previous previous = root; root = NULL; } // Otherwise else root = root->right; } } while (!s3.empty()); cout << endl; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal postorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same: C++ // C++ program to illustrate the // level order traversal#include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to perform the level-order // traversal void levelorder(struct treenode* root) { // If the root is NULL if (root == NULL) return; // Use queue for traversal queue<treenode*> q; // Print the root's value and // push it into the queue cout << root->info << " "; q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node root = q.front(); q.pop(); // If the root has the left child if (root->left) { cout << root->left->info << " "; q.push(root->left); } // If the root has the right child if (root->right) { cout << root->right->info << " "; q.push(root->right); } } cout << endl; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal levelorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) The element which is largest among all the elements of the binary tree is called the maximum element. Below is the program to illustrate the same: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to find the maximum element // in the given Binary Tree int FindMax(struct treenode* root) { // If the tree is empty if (root == NULL) return 0; queue<treenode*> q; int max; struct treenode* temp; max = root->info; // Push the root in the queue q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node of // the tree root = q.front(); temp = root; q.pop(); // Update the maximum value // of the Tree if (max < temp->info) max = temp->info; if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Return the maximum value return max; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal FindMax(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) The approach to search for any particular element in the tree node is to perform any tree traversal on the given tree and check if there exists any node with the given searched value or not. If found to be true, then print “Element is Found”. Otherwise, print “Element Not Found”. Below is the program to illustrate the same: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to search an element in the // given Binary Tree int FindElement(struct treenode* root, int data) { // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; struct treenode* temp; if (!root) return 0; else { // Push the root q.push(root); // Perform the level-order traversal while (!q.empty()) { // Get the root root = q.front(); temp = root; q.pop(); // If the node with value data // exists then return 1 if (data == temp->info) return 1; // Recursively push the left and // the right child of the node if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Otherwise, not found return 0; } } // Driver Code int main() { int data; // Root of the tree struct treenode* root = NULL; // Create the Tree root = create(); cout << "\nEnter element to searched : "; cin >> data; // Function Call if (FindElement(root, data) == 1) cout << "\nElement is found"; else cout << "Element is not found"; return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(log N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to print the reverse level // order traversal of the given tree void reversetree(struct treenode* root) { // If the root is NULL if (root == NULL) return; queue<treenode*> q; stack<int> s; struct treenode* temp; q.push(root); // Until queue is empty while (!q.empty()) { // Get the front node temp = q.front(); q.pop(); // Push every countered node // data into stack s.push(temp->info); // Check for the left subtree if (temp->left) q.push(temp->left); // Check for the right subtree if (temp->right) q.push(temp->right); } // While S is non-empty, print // all the nodes while (!s.empty()) { cout << s.top() << " "; s.pop(); } } // Driver Code int main() { // Create root node struct treenode* root = NULL; // Create a tree root = create(); cout << "\nReversed tree is : "; reversetree(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) The height of the binary tree is the longest path from the root node to any leaf node in the tree. Below is the program to illustrate the same: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into // the tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to find the height of // the given Binary tree int height(struct treenode* root) { int x, y; // If root is NOT NULL if (root != NULL) { // x will contain the height // of left subtree x = height(root->left); // y will contain the height // of right subtree y = height(root->right); if (x > y) // Leaf node has one height // so x or y + 1 return x + 1; else return y + 1; } return 0; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nHeight of the tree is : " << height(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) The node which is present at the maximum or the last level is called the deepest node. Below is the program to implement the above approach: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Function to find the deepest node // of the given Binary Tree int deepest(struct treenode* root) { // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; q.push(root); // While queue is non-empty while (!q.empty()) { // Get the front node of queue root = q.front(); q.pop(); // Check for the left and // the right subtree if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // Return the value for the // deepest node return (root->info); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nDeepest node of the tree is : " << deepest(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to implement the same: C++ // C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Stores the maximum left size int maxlevelleft = 0; // Function to print the left view of // the tree void leftview(struct treenode* root, int level) { if (root == NULL) return; // If current level is at least // the maximum left level if (level >= maxlevelleft) { // Print the data cout << root->info << " "; maxlevelleft++; } // Left and Right Subtree // recursive calls leftview(root->left, level + 1); leftview(root->right, level + 1); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nLeft view of the tree is : "; // Function Call leftview(root, 0); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) Below is the program to illustrate the same: C++ // C++ program to demonstrate the // above concepts #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Stores the maximum right level int maxlevelright = 0; // Function to print the right view of // the given Binary tree void rightview(struct treenode* root, int level) { // If the root is NULL if (root == NULL) return; // If the current level is greater // than the maximum right level if (level >= maxlevelright) { // Print the data cout << root->info << " "; maxlevelright++; } // Recursively call for the right // and the left subtree rightview(root->right, level + 1); rightview(root->left, level + 1); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nRight view of the tree is : "; rightview(root, 0); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) Below is the program to illustrate the same: C++ // C++ program to demonstrate the // above concepts #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Initialize an ordered map map<int, int> HashMap; // Iterator for the map map<int, int>::iterator it; // Function to print the top view // of the given Binary Tree void topview(struct treenode* root, int level) { // If the root is NULL if (root == NULL) return; // Get the level int i = HashMap.count(level); // Update the root information if (i == 0) HashMap[level] = root->info; // Left and Right recursive calls topview(root->left, level - 1); topview(root->right, level + 1); // Update the current level // with the root's value HashMap[level] = root->info; return; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create a tree root = create(); topview(root, 0); cout << "\nTop view of the tree is : "; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second << " "; } return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program to demonstrate the // above concepts #include "bits/stdc++.h" using namespace std; // Structure of the Binary Tree struct treenode { int info; struct treenode *left, *right; }; // Function to create the Binary Tree struct treenode* create() { int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree; }; // Initialize an ordered Map map<int, pair<int, int> > HashMap; // Iterator for the map map<int, pair<int, int> >::iterator it; // Function to print the bottom view // of the given binary tree void bottomview(struct treenode* root, int level, int height) { // If root is NULL if (root == NULL) return; // If the height of the level is // greater than the current // stored height of the level if (height >= HashMap[level].second) { HashMap[level] = { root->info, height }; } // Left and right recursive calls bottomview(root->left, level - 1, height + 1); bottomview(root->right, level + 1, height + 1); return; } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create the tree root = create(); bottomview(root, 0, 0); cout << "\nBottom view of the tree is : "; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second.first << " "; } return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program to implement // the above approach #include <iostream> using namespace std; // structure of the binary tree struct treenode { // data part int info; // left and right node struct treenode *left, *right; }; // create function for binary // tree creation struct treenode* create() { int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << "\nEnter data to be inserted or type -1 for no insertion : "; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // returning the created tree return tree; }; /* With the simple logic of recursion and swapping, we can create mirror tree. We will swap the the left-node and right-node of root node. We will use recursion and start swapping from the bottom of the tree. */ // function to form mirror image a tree void mirrortree(struct treenode* root) { if (root != NULL) { mirrortree(root->left); mirrortree(root->right); struct treenode* temp; temp = root->left; root->left = root->right; root->right = temp; } return; } // function for the inorder traversal void inorder(struct treenode* root) { if (root == NULL) return; inorder(root->left); cout << root->info << " "; inorder(root->right); } // Driver code int main() { // creating variable of the // structure struct treenode* root = NULL; // calling create function to // create tree root = create(); mirrortree(root); cout << "\nInorder of the mirror tree is = "; inorder(root); return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) Serialization of a tree is defined as the conversion of the given tree into a data-format that can be later restored and the structure of the tree must be maintained. Below is the program to implement the above approach: C++ // C++ program to implement // the above approach #include <iostream> using namespace std; // structure of the binary tree struct treenode { // data part int info; // left and right node struct treenode *left, *right; }; // create function for binary // tree creation struct treenode* create() { int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << "\nEnter data to be inserted or type -1 for no insertion : "; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // returning the created tree return tree; }; // Function to serialize the given // Binary Tree void serialize(struct treenode* root, vector<int>& v) { // If the root is NULL, then // push -1 and return if (root == NULL) { v.push_back(-1); return; } // Otherwise, push the data part v.push_back(root->info); // Recursively Call for the left // and the right Subtree serialize(root->left, v); serialize(root->right, v); } // Driver Code int main() { // Root Node struct treenode* root = NULL; // Create a tree root = create(); vector<int> v; serialize(root, v); cout << "\nSerialize form of the tree is = "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; return 0; } /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Complexity Analysis: Time Complexity: O(n). Auxiliary Space: O(1). Time Complexity: O(n). Auxiliary Space: O(1). Binary Tree Inorder Traversal PostOrder Traversal Preorder Traversal Technical Scripter 2020 tree-level-order tree-traversal Recursion Technical Scripter Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide an array into K subarray with the given condition Recursive Insertion Sort Program to calculate Height and Depth of a node in a Binary Tree Sum of natural numbers using recursion Practice Questions for Recursion | Set 1 Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24687, "s": 24656, "text": " \n08 Apr, 2021\n" }, { "code": null, "e": 25064, "s": 24687, "text": "The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right is called “Right sub-tree”." }, { "code": null, "e": 25137, "s": 25064, "text": "Below are the various operations that can be performed on a Binary Tree:" }, { "code": null, "e": 25318, "s": 25137, "text": "The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. Below is the program to illustrate the same:" }, { "code": null, "e": 25322, "s": 25318, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate how to \n// create a tree \n#include <iostream> \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to perform the inorder \n// traversal of the given Tree \nvoid inorder(struct treenode* root) \n{ \n // If root is NULL \n if (root == NULL) \n return; \n \n // Recursively call for the left \n // and the right subtree \n inorder(root->left); \n cout << root->info << \" \"; \n inorder(root->right); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n inorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 27057, "s": 25332, "text": null }, { "code": null, "e": 27065, "s": 27057, "text": "Output:" }, { "code": null, "e": 27108, "s": 27065, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 27242, "s": 27108, "text": "In this traversal, the root is visited first followed by the left and the right subtree. Below is the program to illustrate the same:" }, { "code": null, "e": 27246, "s": 27242, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to demonstrate the \n// pre-order traversal \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to perform the pre-order \n// traversal for the given tree \nvoid preorder(struct treenode* root) \n{ \n // If the root is NULL \n if (root == NULL) \n return; \n \n // Using tree-node type stack STL \n stack<treenode*> s; \n \n while ((root != NULL) || (!s.empty())) { \n if (root != NULL) { \n // Print the root \n cout << root->info << \" \"; \n \n // Push the node in the stack \n s.push(root); \n \n // Move to left subtree \n root = root->left; \n } \n else { \n // Remove the top of stack \n root = s.top(); \n s.pop(); \n root = root->right; \n } \n } \n \n cout << endl; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n preorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 29394, "s": 27256, "text": null }, { "code": null, "e": 29402, "s": 29394, "text": "Output:" }, { "code": null, "e": 29445, "s": 29402, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 29587, "s": 29445, "text": "In this traversal, the left subtree is visited first followed by the root and the right subtree. Below is the program to illustrate the same:" }, { "code": null, "e": 29591, "s": 29587, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate how to \n// create a tree \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to perform the inorder \n// traversal of the given Tree \nvoid inorder(struct treenode* root) \n{ \n // If root is NULL \n if (root == NULL) \n return; \n \n // Recursively call for the left \n // and the right subtree \n inorder(root->left); \n cout << root->info << \" \"; \n inorder(root->right); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n inorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 31331, "s": 29601, "text": null }, { "code": null, "e": 31339, "s": 31331, "text": "Output:" }, { "code": null, "e": 31382, "s": 31339, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 31526, "s": 31382, "text": "In this traversal, the left subtree is visited first, followed by the right subtree and root node. Below is the program to illustrate the same:" }, { "code": null, "e": 31530, "s": 31526, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to implement the \n// post-order traversal \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to perform the post-order \n// traversal of the given tree \nvoid postorder(struct treenode* root) \n{ \n // If the root is NULL \n return; \n \n stack<treenode*> s3; \n struct treenode* previous = NULL; \n \n do { \n // Iterate until root is present \n while (root != NULL) { \n s3.push(root); \n root = root->left; \n } \n \n while (root == NULL && (!s3.empty())) { \n root = s3.top(); \n \n // If the right subtree is NULL \n if (root->right == NULL \n || root->right == previous) { \n // Print the root information \n cout << root->info << \" \"; \n s3.pop(); \n \n // Update the previous \n previous = root; \n root = NULL; \n } \n \n // Otherwise \n else\n root = root->right; \n } \n \n } while (!s3.empty()); \n cout << endl; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n postorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 33924, "s": 31540, "text": null }, { "code": null, "e": 33932, "s": 33924, "text": "Output:" }, { "code": null, "e": 33975, "s": 33932, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 34079, "s": 33975, "text": "In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same:" }, { "code": null, "e": 34083, "s": 34079, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate the \n// level order traversal#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to perform the level-order \n// traversal \nvoid levelorder(struct treenode* root) \n{ \n // If the root is NULL \n if (root == NULL) \n return; \n \n // Use queue for traversal \n queue<treenode*> q; \n \n // Print the root's value and \n // push it into the queue \n cout << root->info << \" \"; \n q.push(root); \n \n // Iterate until queue is non-empty \n while (!q.empty()) { \n // Get the front node \n root = q.front(); \n q.pop(); \n \n // If the root has the left child \n if (root->left) { \n cout << root->left->info \n << \" \"; \n q.push(root->left); \n } \n \n // If the root has the right child \n if (root->right) { \n cout << root->right->info \n << \" \"; \n q.push(root->right); \n } \n } \n cout << endl; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n levelorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 36383, "s": 34093, "text": null }, { "code": null, "e": 36391, "s": 36383, "text": "Output:" }, { "code": null, "e": 36434, "s": 36391, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 36582, "s": 36434, "text": " The element which is largest among all the elements of the binary tree is called the maximum element. Below is the program to illustrate the same:" }, { "code": null, "e": 36586, "s": 36582, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to find the maximum element \n// in the given Binary Tree \nint FindMax(struct treenode* root) \n{ \n // If the tree is empty \n if (root == NULL) \n return 0; \n \n queue<treenode*> q; \n int max; \n struct treenode* temp; \n \n max = root->info; \n \n // Push the root in the queue \n q.push(root); \n \n // Iterate until queue is non-empty \n while (!q.empty()) { \n \n // Get the front node of \n // the tree \n root = q.front(); \n temp = root; \n q.pop(); \n \n // Update the maximum value \n // of the Tree \n if (max < temp->info) \n max = temp->info; \n \n if (root->left) { \n q.push(root->left); \n } \n if (root->right) { \n q.push(root->right); \n } \n } \n \n // Return the maximum value \n return max; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Function Call \n root = create(); \n \n // Perform Inorder Traversal \n FindMax(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 38815, "s": 36596, "text": null }, { "code": null, "e": 38823, "s": 38815, "text": "Output:" }, { "code": null, "e": 38866, "s": 38823, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 39150, "s": 38866, "text": "The approach to search for any particular element in the tree node is to perform any tree traversal on the given tree and check if there exists any node with the given searched value or not. If found to be true, then print “Element is Found”. Otherwise, print “Element Not Found”. " }, { "code": null, "e": 39195, "s": 39150, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 39199, "s": 39195, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to search an element in the \n// given Binary Tree \nint FindElement(struct treenode* root, \n int data) \n{ \n // If the root is NULL \n if (root == NULL) \n return 0; \n \n queue<treenode*> q; \n struct treenode* temp; \n if (!root) \n return 0; \n \n else { \n // Push the root \n q.push(root); \n \n // Perform the level-order traversal \n while (!q.empty()) { \n // Get the root \n root = q.front(); \n temp = root; \n q.pop(); \n \n // If the node with value data \n // exists then return 1 \n if (data == temp->info) \n return 1; \n \n // Recursively push the left and \n // the right child of the node \n if (root->left) { \n q.push(root->left); \n } \n if (root->right) { \n q.push(root->right); \n } \n } \n \n // Otherwise, not found \n return 0; \n } \n} \n \n// Driver Code \nint main() \n{ \n int data; \n \n // Root of the tree \n struct treenode* root = NULL; \n \n // Create the Tree \n root = create(); \n \n cout << \"\\nEnter element to searched : \"; \n cin >> data; \n \n // Function Call \n if (FindElement(root, data) == 1) \n cout << \"\\nElement is found\"; \n else\n cout << \"Element is not found\"; \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 41774, "s": 39209, "text": null }, { "code": null, "e": 41782, "s": 41774, "text": "Output:" }, { "code": null, "e": 41829, "s": 41782, "text": "Time Complexity: O(log N)Auxiliary Space: O(N)" }, { "code": null, "e": 41874, "s": 41829, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 41878, "s": 41874, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to print the reverse level \n// order traversal of the given tree \nvoid reversetree(struct treenode* root) \n{ \n // If the root is NULL \n if (root == NULL) \n return; \n \n queue<treenode*> q; \n stack<int> s; \n struct treenode* temp; \n q.push(root); \n \n // Until queue is empty \n while (!q.empty()) { \n // Get the front node \n temp = q.front(); \n q.pop(); \n \n // Push every countered node \n // data into stack \n s.push(temp->info); \n \n // Check for the left subtree \n if (temp->left) \n q.push(temp->left); \n \n // Check for the right subtree \n if (temp->right) \n q.push(temp->right); \n } \n \n // While S is non-empty, print \n // all the nodes \n while (!s.empty()) { \n cout << s.top() << \" \"; \n s.pop(); \n } \n} \n \n// Driver Code \nint main() \n{ \n // Create root node \n struct treenode* root = NULL; \n \n // Create a tree \n root = create(); \n \n cout << \"\\nReversed tree is : \"; \n reversetree(root); \n return 0; \n} \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n*/\n\n\n\n\n\n", "e": 44118, "s": 41888, "text": null }, { "code": null, "e": 44126, "s": 44118, "text": "Output:" }, { "code": null, "e": 44169, "s": 44126, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 44313, "s": 44169, "text": "The height of the binary tree is the longest path from the root node to any leaf node in the tree. Below is the program to illustrate the same:" }, { "code": null, "e": 44317, "s": 44313, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into \n // the tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to find the height of \n// the given Binary tree \nint height(struct treenode* root) \n{ \n int x, y; \n \n // If root is NOT NULL \n if (root != NULL) { \n // x will contain the height \n // of left subtree \n x = height(root->left); \n \n // y will contain the height \n // of right subtree \n y = height(root->right); \n \n if (x > y) \n \n // Leaf node has one height \n // so x or y + 1 \n return x + 1; \n else\n return y + 1; \n } \n return 0; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create the tree \n root = create(); \n \n cout << \"\\nHeight of the tree is : \"\n << height(root); \n \n return 0; \n} \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 46280, "s": 44327, "text": null }, { "code": null, "e": 46288, "s": 46280, "text": "Output:" }, { "code": null, "e": 46331, "s": 46288, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 46472, "s": 46331, "text": "The node which is present at the maximum or the last level is called the deepest node. Below is the program to implement the above approach:" }, { "code": null, "e": 46476, "s": 46472, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Function to find the deepest node \n// of the given Binary Tree \nint deepest(struct treenode* root) \n{ \n // If the root is NULL \n if (root == NULL) \n return 0; \n \n queue<treenode*> q; \n \n q.push(root); \n \n // While queue is non-empty \n while (!q.empty()) { \n // Get the front node of queue \n root = q.front(); \n q.pop(); \n \n // Check for the left and \n // the right subtree \n if (root->left) \n q.push(root->left); \n if (root->right) \n q.push(root->right); \n } \n \n // Return the value for the \n // deepest node \n return (root->info); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create the tree \n root = create(); \n \n cout << \"\\nDeepest node of the tree is : \" << deepest(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 48500, "s": 46486, "text": null }, { "code": null, "e": 48508, "s": 48500, "text": "Output:" }, { "code": null, "e": 48551, "s": 48508, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 48595, "s": 48551, "text": "Below is the program to implement the same:" }, { "code": null, "e": 48599, "s": 48595, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Stores the maximum left size \nint maxlevelleft = 0; \n \n// Function to print the left view of \n// the tree \nvoid leftview(struct treenode* root, \n int level) \n{ \n if (root == NULL) \n return; \n \n // If current level is at least \n // the maximum left level \n if (level >= maxlevelleft) { \n // Print the data \n cout << root->info << \" \"; \n maxlevelleft++; \n } \n \n // Left and Right Subtree \n // recursive calls \n leftview(root->left, level + 1); \n leftview(root->right, level + 1); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create the tree \n root = create(); \n \n cout << \"\\nLeft view of the tree is : \"; \n \n // Function Call \n leftview(root, 0); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 50556, "s": 48609, "text": null }, { "code": null, "e": 50564, "s": 50556, "text": "Output:" }, { "code": null, "e": 50607, "s": 50564, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 50652, "s": 50607, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 50656, "s": 50652, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to demonstrate the \n// above concepts \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Stores the maximum right level \nint maxlevelright = 0; \n \n// Function to print the right view of \n// the given Binary tree \nvoid rightview(struct treenode* root, \n int level) \n{ \n // If the root is NULL \n if (root == NULL) \n return; \n \n // If the current level is greater \n // than the maximum right level \n if (level >= maxlevelright) { \n // Print the data \n cout << root->info << \" \"; \n maxlevelright++; \n } \n \n // Recursively call for the right \n // and the left subtree \n rightview(root->right, level + 1); \n rightview(root->left, level + 1); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create the tree \n root = create(); \n \n cout << \"\\nRight view of the tree is : \"; \n \n rightview(root, 0); \n \n return 0; \n} \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n*/\n\n\n\n\n\n", "e": 52704, "s": 50666, "text": null }, { "code": null, "e": 52712, "s": 52704, "text": "Output:" }, { "code": null, "e": 52755, "s": 52712, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 52800, "s": 52755, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 52804, "s": 52800, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to demonstrate the \n// above concepts \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Initialize an ordered map \nmap<int, int> HashMap; \n \n// Iterator for the map \nmap<int, int>::iterator it; \n \n// Function to print the top view \n// of the given Binary Tree \nvoid topview(struct treenode* root, \n int level) \n{ \n // If the root is NULL \n if (root == NULL) \n return; \n \n // Get the level \n int i = HashMap.count(level); \n \n // Update the root information \n if (i == 0) \n HashMap[level] = root->info; \n \n // Left and Right recursive calls \n topview(root->left, level - 1); \n topview(root->right, level + 1); \n \n // Update the current level \n // with the root's value \n HashMap[level] = root->info; \n \n return; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create a tree \n root = create(); \n \n topview(root, 0); \n cout << \"\\nTop view of the tree is : \"; \n \n for (it = HashMap.begin(); \n it != HashMap.end(); it++) { \n cout << it->second << \" \"; \n } \n \n return 0; \n} \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n*/\n\n\n\n\n\n", "e": 55031, "s": 52814, "text": null }, { "code": null, "e": 55039, "s": 55031, "text": "Output:" }, { "code": null, "e": 55082, "s": 55039, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 55127, "s": 55082, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 55131, "s": 55127, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to demonstrate the \n// above concepts \n#include \"bits/stdc++.h\" \nusing namespace std; \n \n// Structure of the Binary Tree \nstruct treenode { \n int info; \n struct treenode *left, \n *right; \n}; \n \n// Function to create the Binary Tree \nstruct treenode* create() \n{ \n int data; \n struct treenode* tree; \n \n // Dynamically allocating memory \n // for the tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted \"\n << \"or type -1 for no insertion : \"; \n \n // Input from the user \n cin >> data; \n \n // Termination Condition \n if (data == -1) \n return 0; \n \n // Assign value from user into tree \n tree->info = data; \n \n // Recursively Call to create the \n // left and the right sub tree \n cout << \"Enter left child of : \"\n << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \"\n << data; \n tree->right = create(); \n \n // Return the created Tree \n return tree; \n}; \n \n// Initialize an ordered Map \nmap<int, pair<int, int> > HashMap; \n \n// Iterator for the map \nmap<int, pair<int, int> >::iterator it; \n \n// Function to print the bottom view \n// of the given binary tree \nvoid bottomview(struct treenode* root, \n int level, int height) \n{ \n // If root is NULL \n if (root == NULL) \n return; \n \n // If the height of the level is \n // greater than the current \n // stored height of the level \n if (height >= HashMap[level].second) { \n HashMap[level] = { root->info, \n height }; \n } \n \n // Left and right recursive calls \n bottomview(root->left, level - 1, \n height + 1); \n bottomview(root->right, level + 1, \n height + 1); \n \n return; \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create the tree \n root = create(); \n \n bottomview(root, 0, 0); \n cout << \"\\nBottom view of the tree is : \"; \n \n for (it = HashMap.begin(); \n it != HashMap.end(); it++) { \n \n cout << it->second.first << \" \"; \n } \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 57469, "s": 55141, "text": null }, { "code": null, "e": 57477, "s": 57469, "text": "Output:" }, { "code": null, "e": 57520, "s": 57477, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 57565, "s": 57520, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 57569, "s": 57565, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to implement \n// the above approach \n#include <iostream> \nusing namespace std; \n \n// structure of the binary tree \nstruct treenode { \n // data part \n int info; \n \n // left and right node \n struct treenode *left, *right; \n}; \n \n// create function for binary \n// tree creation \nstruct treenode* create() \n{ \n int data; \n \n // variable of the structure \n struct treenode* tree; \n \n // dynamically allocating \n // memory for tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted or type -1 for no insertion : \"; \n \n // input from the user \n cin >> data; \n \n // condition for termination \n if (data == -1) \n return 0; \n \n // assigning value from user \n // into tree. \n tree->info = data; \n \n // recursively calling create function \n // for left and right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // returning the created tree \n return tree; \n}; \n \n/* \nWith the simple logic of recursion and \nswapping, we can create mirror tree. \nWe will swap the the left-node and \nright-node of root node. We will use \nrecursion and start swapping from the \nbottom of the tree. \n*/\n \n// function to form mirror image a tree \nvoid mirrortree(struct treenode* root) \n{ \n if (root != NULL) { \n mirrortree(root->left); \n mirrortree(root->right); \n \n struct treenode* temp; \n \n temp = root->left; \n root->left = root->right; \n root->right = temp; \n } \n return; \n} \n \n// function for the inorder traversal \nvoid inorder(struct treenode* root) \n{ \n if (root == NULL) \n return; \n \n inorder(root->left); \n cout << root->info << \" \"; \n inorder(root->right); \n} \n \n// Driver code \nint main() \n{ \n // creating variable of the \n // structure \n struct treenode* root = NULL; \n \n // calling create function to \n // create tree \n root = create(); \n \n mirrortree(root); \n cout << \"\\nInorder of the mirror tree is = \"; \n inorder(root); \n \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 59910, "s": 57579, "text": null }, { "code": null, "e": 59918, "s": 59910, "text": "Output:" }, { "code": null, "e": 59961, "s": 59918, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 60182, "s": 59961, "text": "Serialization of a tree is defined as the conversion of the given tree into a data-format that can be later restored and the structure of the tree must be maintained. Below is the program to implement the above approach:" }, { "code": null, "e": 60186, "s": 60182, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to implement \n// the above approach \n#include <iostream> \nusing namespace std; \n \n// structure of the binary tree \nstruct treenode { \n // data part \n int info; \n \n // left and right node \n struct treenode *left, *right; \n}; \n \n// create function for binary \n// tree creation \nstruct treenode* create() \n{ \n int data; \n \n // variable of the structure \n struct treenode* tree; \n \n // dynamically allocating \n // memory for tree-node \n tree = new treenode; \n \n cout << \"\\nEnter data to be inserted or type -1 for no insertion : \"; \n \n // input from the user \n cin >> data; \n \n // condition for termination \n if (data == -1) \n return 0; \n \n // assigning value from user \n // into tree. \n tree->info = data; \n \n // recursively calling create function \n // for left and right sub tree \n cout << \"Enter left child of : \" << data; \n tree->left = create(); \n \n cout << \"Enter right child of : \" << data; \n tree->right = create(); \n \n // returning the created tree \n return tree; \n}; \n \n// Function to serialize the given \n// Binary Tree \nvoid serialize(struct treenode* root, \n vector<int>& v) \n{ \n // If the root is NULL, then \n // push -1 and return \n if (root == NULL) { \n v.push_back(-1); \n return; \n } \n \n // Otherwise, push the data part \n v.push_back(root->info); \n \n // Recursively Call for the left \n // and the right Subtree \n serialize(root->left, v); \n serialize(root->right, v); \n} \n \n// Driver Code \nint main() \n{ \n // Root Node \n struct treenode* root = NULL; \n \n // Create a tree \n root = create(); \n \n vector<int> v; \n \n serialize(root, v); \n cout << \"\\nSerialize form of the tree is = \"; \n \n for (int i = 0; i < v.size(); i++) \n cout << v[i] << \" \"; \n return 0; \n} \n \n/* Will be creating tree: \n 2 \n / \\ \n 7 5 \n / \\ \\ \n 2 6 9 \n */\n\n\n\n\n\n", "e": 62238, "s": 60196, "text": null }, { "code": null, "e": 62246, "s": 62238, "text": "Output:" }, { "code": null, "e": 62289, "s": 62246, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 62310, "s": 62289, "text": "Complexity Analysis:" }, { "code": null, "e": 62358, "s": 62310, "text": "\nTime Complexity: O(n).\nAuxiliary Space: O(1).\n" }, { "code": null, "e": 62381, "s": 62358, "text": "Time Complexity: O(n)." }, { "code": null, "e": 62404, "s": 62381, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 62418, "s": 62404, "text": "\nBinary Tree\n" }, { "code": null, "e": 62438, "s": 62418, "text": "\nInorder Traversal\n" }, { "code": null, "e": 62460, "s": 62438, "text": "\nPostOrder Traversal\n" }, { "code": null, "e": 62481, "s": 62460, "text": "\nPreorder Traversal\n" }, { "code": null, "e": 62507, "s": 62481, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 62526, "s": 62507, "text": "\ntree-level-order\n" }, { "code": null, "e": 62543, "s": 62526, "text": "\ntree-traversal\n" }, { "code": null, "e": 62555, "s": 62543, "text": "\nRecursion\n" }, { "code": null, "e": 62576, "s": 62555, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 62583, "s": 62576, "text": "\nTree\n" }, { "code": null, "e": 62788, "s": 62583, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 62845, "s": 62788, "text": "Divide an array into K subarray with the given condition" }, { "code": null, "e": 62870, "s": 62845, "text": "Recursive Insertion Sort" }, { "code": null, "e": 62935, "s": 62870, "text": "Program to calculate Height and Depth of a node in a Binary Tree" }, { "code": null, "e": 62974, "s": 62935, "text": "Sum of natural numbers using recursion" }, { "code": null, "e": 63015, "s": 62974, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 63065, "s": 63015, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 63100, "s": 63065, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 63134, "s": 63100, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 63163, "s": 63134, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to create a vector with lowercase as well as uppercase letters in R?
To create a vector with lowercase we can use the word letters and for uppercase the word LETTERS is used in R. If we want to create a vector with both type of letters then both of these words can be combined using c function and if want to create a vector with randomly sampled values of lowercase and uppercase letters then sample function can be used. Live Demo > x1<-c(LETTERS[1:4],letters[1:4]) > x1 [1] "A" "B" "C" "D" "a" "b" "c" "d" Live Demo > x2<-c(LETTERS[1:26],letters[1:26]) > x2 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" [20] "T" "U" "V" "W" "X" "Y" "Z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" [39] "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" Live Demo > x3<-c(LETTERS[1:13],letters[1:13],LETTERS[14:26],letters[14:26]) > x3 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "a" "b" "c" "d" "e" "f" [20] "g" "h" "i" "j" "k" "l" "m" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" [39] "Z" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" Live Demo > x4<-sample(c(LETTERS[1:4],letters[1:4]),100,replace=TRUE) > x4 [1] "a" "B" "a" "B" "D" "D" "c" "b" "d" "D" "a" "B" "b" "c" "d" "c" "B" "C" [19] "D" "d" "b" "C" "b" "b" "C" "D" "d" "A" "B" "A" "D" "a" "a" "c" "b" "b" [37] "B" "A" "d" "a" "b" "b" "D" "B" "c" "b" "b" "b" "B" "B" "D" "b" "a" "C" [55] "d" "b" "c" "B" "A" "A" "a" "c" "C" "B" "c" "D" "A" "C" "D" "D" "B" "c" [73] "b" "C" "d" "C" "B" "D" "A" "A" "B" "A" "B" "c" "d" "C" "B" "a" "b" "B" [91] "b" "B" "B" "A" "a" "B" "b" "A" "a" "a" Live Demo > x5<-sample(c(LETTERS[1:26],letters[1:26]),120,replace=TRUE) > x5 [1] "n" "t" "S" "B" "l" "n" "W" "Z" "a" "k" "X" "P" "E" "V" "Z" "O" "A" "D" [19] "R" "g" "r" "E" "p" "a" "h" "E" "B" "N" "F" "H" "Y" "h" "f" "r" "r" "E" [37] "G" "x" "H" "V" "W" "z" "p" "r" "E" "u" "u" "X" "w" "E" "Q" "G" "k" "N" [55] "f" "P" "S" "o" "p" "w" "C" "g" "T" "p" "D" "T" "f" "N" "j" "z" "d" "v" [73] "D" "a" "L" "J" "B" "g" "T" "y" "a" "L" "G" "E" "Z" "Y" "l" "G" "M" "L" [91] "f" "b" "h" "P" "B" "T" "i" "e" "H" "b" "K" "p" "W" "I" "z" "t" "I" "B" [109] "Q" "T" "z" "e" "n" "q" "m" "I" "n" "g" "r" "B" Live Demo > x6<-sample(c(LETTERS[21:26],letters[21:26]),120,replace=TRUE) > x6 [1] "X" "Z" "Z" "u" "W" "x" "w" "z" "y" "Z" "u" "Z" "x" "z" "V" "X" "y" "x" [19] "V" "U" "x" "Y" "u" "u" "W" "v" "y" "u" "W" "y" "u" "y" "X" "U" "Y" "u" [37] "v" "Z" "u" "X" "Z" "W" "U" "v" "Z" "W" "W" "X" "y" "Z" "z" "X" "U" "U" [55] "w" "y" "W" "U" "W" "X" "y" "V" "v" "V" "V" "Z" "Y" "v" "u" "y" "z" "W" [73] "U" "V" "U" "u" "v" "U" "Z" "Z" "X" "w" "Z" "u" "w" "Y" "X" "y" "Z" "V" [91] "x" "y" "x" "Y" "y" "v" "z" "u" "Y" "z" "W" "v" "u" "u" "V" "v" "Y" "x" [109] "Z" "y" "z" "w" "z" "u" "x" "x" "Z" "V" "x" "U" Live Demo > x7<-sample(c(LETTERS[1:13],letters[1:13]),120,replace=TRUE) > x7 [1] "m" "i" "I" "j" "F" "F" "J" "E" "a" "f" "m" "f" "L" "I" "k" "E" "H" "B" [19] "b" "H" "b" "E" "i" "F" "i" "C" "l" "J" "c" "C" "c" "D" "m" "E" "j" "C" [37] "j" "E" "l" "I" "L" "C" "B" "L" "l" "d" "g" "K" "j" "D" "i" "C" "i" "G" [55] "I" "e" "E" "C" "j" "k" "k" "D" "J" "g" "K" "e" "j" "D" "B" "B" "f" "k" [73] "B" "f" "g" "l" "E" "h" "g" "j" "b" "J" "c" "C" "j" "f" "M" "e" "I" "j" [91] "A" "B" "m" "a" "I" "M" "G" "e" "i" "e" "l" "h" "I" "E" "M" "d" "k" "B" [109] "G" "j" "C" "g" "B" "F" "m" "M" "H" "L" "a" "m" Live Demo > x8<-sample(c(LETTERS[24:26],letters[24:26]),120,replace=TRUE) > x8 [1] "X" "z" "X" "x" "x" "Y" "y" "Z" "x" "z" "Z" "y" "y" "z" "Y" "X" "Y" "X" [19] "Y" "y" "y" "Y" "x" "Y" "Y" "x" "X" "x" "x" "Z" "Y" "z" "x" "X" "x" "z" [37] "z" "Y" "y" "X" "y" "z" "Z" "z" "Z" "x" "Y" "Z" "x" "z" "x" "x" "X" "z" [55] "y" "x" "y" "x" "Z" "x" "Y" "z" "z" "X" "z" "Y" "X" "X" "x" "z" "z" "y" [73] "Z" "z" "Z" "Y" "x" "Y" "x" "Z" "Y" "y" "X" "x" "z" "x" "Z" "x" "z" "y" [91] "Z" "x" "X" "Y" "X" "X" "y" "x" "Y" "z" "z" "X" "Y" "X" "y" "x" "Y" "y" [109] "Y" "X" "z" "Z" "Z" "X" "Y" "Z" "Y" "Z" "X" "Y"
[ { "code": null, "e": 1416, "s": 1062, "text": "To create a vector with lowercase we can use the word letters and for uppercase the word LETTERS is used in R. If we want to create a vector with both type of letters then both of these words can be combined using c function and if want to create a vector with randomly sampled values of lowercase and uppercase letters then sample function can be used." }, { "code": null, "e": 1426, "s": 1416, "text": "Live Demo" }, { "code": null, "e": 1466, "s": 1426, "text": "> x1<-c(LETTERS[1:4],letters[1:4])\n> x1" }, { "code": null, "e": 1502, "s": 1466, "text": "[1] \"A\" \"B\" \"C\" \"D\" \"a\" \"b\" \"c\" \"d\"" }, { "code": null, "e": 1512, "s": 1502, "text": "Live Demo" }, { "code": null, "e": 1554, "s": 1512, "text": "> x2<-c(LETTERS[1:26],letters[1:26])\n> x2" }, { "code": null, "e": 1776, "s": 1554, "text": "[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\"\n[20] \"T\" \"U\" \"V\" \"W\" \"X\" \"Y\" \"Z\" \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\"\n[39] \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"" }, { "code": null, "e": 1786, "s": 1776, "text": "Live Demo" }, { "code": null, "e": 1858, "s": 1786, "text": "> x3<-c(LETTERS[1:13],letters[1:13],LETTERS[14:26],letters[14:26])\n> x3" }, { "code": null, "e": 2080, "s": 1858, "text": "[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"a\" \"b\" \"c\" \"d\" \"e\" \"f\"\n[20] \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\" \"T\" \"U\" \"V\" \"W\" \"X\" \"Y\"\n[39] \"Z\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"" }, { "code": null, "e": 2090, "s": 2080, "text": "Live Demo" }, { "code": null, "e": 2155, "s": 2090, "text": "> x4<-sample(c(LETTERS[1:4],letters[1:4]),100,replace=TRUE)\n> x4" }, { "code": null, "e": 2584, "s": 2155, "text": "[1] \"a\" \"B\" \"a\" \"B\" \"D\" \"D\" \"c\" \"b\" \"d\" \"D\" \"a\" \"B\" \"b\" \"c\" \"d\" \"c\" \"B\" \"C\"\n[19] \"D\" \"d\" \"b\" \"C\" \"b\" \"b\" \"C\" \"D\" \"d\" \"A\" \"B\" \"A\" \"D\" \"a\" \"a\" \"c\" \"b\" \"b\"\n[37] \"B\" \"A\" \"d\" \"a\" \"b\" \"b\" \"D\" \"B\" \"c\" \"b\" \"b\" \"b\" \"B\" \"B\" \"D\" \"b\" \"a\" \"C\"\n[55] \"d\" \"b\" \"c\" \"B\" \"A\" \"A\" \"a\" \"c\" \"C\" \"B\" \"c\" \"D\" \"A\" \"C\" \"D\" \"D\" \"B\" \"c\"\n[73] \"b\" \"C\" \"d\" \"C\" \"B\" \"D\" \"A\" \"A\" \"B\" \"A\" \"B\" \"c\" \"d\" \"C\" \"B\" \"a\" \"b\" \"B\"\n[91] \"b\" \"B\" \"B\" \"A\" \"a\" \"B\" \"b\" \"A\" \"a\" \"a\"" }, { "code": null, "e": 2594, "s": 2584, "text": "Live Demo" }, { "code": null, "e": 2661, "s": 2594, "text": "> x5<-sample(c(LETTERS[1:26],letters[1:26]),120,replace=TRUE)\n> x5" }, { "code": null, "e": 3176, "s": 2661, "text": "[1] \"n\" \"t\" \"S\" \"B\" \"l\" \"n\" \"W\" \"Z\" \"a\" \"k\" \"X\" \"P\" \"E\" \"V\" \"Z\" \"O\" \"A\" \"D\"\n[19] \"R\" \"g\" \"r\" \"E\" \"p\" \"a\" \"h\" \"E\" \"B\" \"N\" \"F\" \"H\" \"Y\" \"h\" \"f\" \"r\" \"r\" \"E\"\n[37] \"G\" \"x\" \"H\" \"V\" \"W\" \"z\" \"p\" \"r\" \"E\" \"u\" \"u\" \"X\" \"w\" \"E\" \"Q\" \"G\" \"k\" \"N\"\n[55] \"f\" \"P\" \"S\" \"o\" \"p\" \"w\" \"C\" \"g\" \"T\" \"p\" \"D\" \"T\" \"f\" \"N\" \"j\" \"z\" \"d\" \"v\"\n[73] \"D\" \"a\" \"L\" \"J\" \"B\" \"g\" \"T\" \"y\" \"a\" \"L\" \"G\" \"E\" \"Z\" \"Y\" \"l\" \"G\" \"M\" \"L\"\n[91] \"f\" \"b\" \"h\" \"P\" \"B\" \"T\" \"i\" \"e\" \"H\" \"b\" \"K\" \"p\" \"W\" \"I\" \"z\" \"t\" \"I\" \"B\"\n[109] \"Q\" \"T\" \"z\" \"e\" \"n\" \"q\" \"m\" \"I\" \"n\" \"g\" \"r\" \"B\"" }, { "code": null, "e": 3186, "s": 3176, "text": "Live Demo" }, { "code": null, "e": 3255, "s": 3186, "text": "> x6<-sample(c(LETTERS[21:26],letters[21:26]),120,replace=TRUE)\n> x6" }, { "code": null, "e": 3770, "s": 3255, "text": "[1] \"X\" \"Z\" \"Z\" \"u\" \"W\" \"x\" \"w\" \"z\" \"y\" \"Z\" \"u\" \"Z\" \"x\" \"z\" \"V\" \"X\" \"y\" \"x\"\n[19] \"V\" \"U\" \"x\" \"Y\" \"u\" \"u\" \"W\" \"v\" \"y\" \"u\" \"W\" \"y\" \"u\" \"y\" \"X\" \"U\" \"Y\" \"u\"\n[37] \"v\" \"Z\" \"u\" \"X\" \"Z\" \"W\" \"U\" \"v\" \"Z\" \"W\" \"W\" \"X\" \"y\" \"Z\" \"z\" \"X\" \"U\" \"U\"\n[55] \"w\" \"y\" \"W\" \"U\" \"W\" \"X\" \"y\" \"V\" \"v\" \"V\" \"V\" \"Z\" \"Y\" \"v\" \"u\" \"y\" \"z\" \"W\"\n[73] \"U\" \"V\" \"U\" \"u\" \"v\" \"U\" \"Z\" \"Z\" \"X\" \"w\" \"Z\" \"u\" \"w\" \"Y\" \"X\" \"y\" \"Z\" \"V\"\n[91] \"x\" \"y\" \"x\" \"Y\" \"y\" \"v\" \"z\" \"u\" \"Y\" \"z\" \"W\" \"v\" \"u\" \"u\" \"V\" \"v\" \"Y\" \"x\"\n[109] \"Z\" \"y\" \"z\" \"w\" \"z\" \"u\" \"x\" \"x\" \"Z\" \"V\" \"x\" \"U\"" }, { "code": null, "e": 3780, "s": 3770, "text": "Live Demo" }, { "code": null, "e": 3847, "s": 3780, "text": "> x7<-sample(c(LETTERS[1:13],letters[1:13]),120,replace=TRUE)\n> x7" }, { "code": null, "e": 4362, "s": 3847, "text": "[1] \"m\" \"i\" \"I\" \"j\" \"F\" \"F\" \"J\" \"E\" \"a\" \"f\" \"m\" \"f\" \"L\" \"I\" \"k\" \"E\" \"H\" \"B\"\n[19] \"b\" \"H\" \"b\" \"E\" \"i\" \"F\" \"i\" \"C\" \"l\" \"J\" \"c\" \"C\" \"c\" \"D\" \"m\" \"E\" \"j\" \"C\"\n[37] \"j\" \"E\" \"l\" \"I\" \"L\" \"C\" \"B\" \"L\" \"l\" \"d\" \"g\" \"K\" \"j\" \"D\" \"i\" \"C\" \"i\" \"G\"\n[55] \"I\" \"e\" \"E\" \"C\" \"j\" \"k\" \"k\" \"D\" \"J\" \"g\" \"K\" \"e\" \"j\" \"D\" \"B\" \"B\" \"f\" \"k\"\n[73] \"B\" \"f\" \"g\" \"l\" \"E\" \"h\" \"g\" \"j\" \"b\" \"J\" \"c\" \"C\" \"j\" \"f\" \"M\" \"e\" \"I\" \"j\"\n[91] \"A\" \"B\" \"m\" \"a\" \"I\" \"M\" \"G\" \"e\" \"i\" \"e\" \"l\" \"h\" \"I\" \"E\" \"M\" \"d\" \"k\" \"B\"\n[109] \"G\" \"j\" \"C\" \"g\" \"B\" \"F\" \"m\" \"M\" \"H\" \"L\" \"a\" \"m\"" }, { "code": null, "e": 4372, "s": 4362, "text": "Live Demo" }, { "code": null, "e": 4441, "s": 4372, "text": "> x8<-sample(c(LETTERS[24:26],letters[24:26]),120,replace=TRUE)\n> x8" }, { "code": null, "e": 4956, "s": 4441, "text": "[1] \"X\" \"z\" \"X\" \"x\" \"x\" \"Y\" \"y\" \"Z\" \"x\" \"z\" \"Z\" \"y\" \"y\" \"z\" \"Y\" \"X\" \"Y\" \"X\"\n[19] \"Y\" \"y\" \"y\" \"Y\" \"x\" \"Y\" \"Y\" \"x\" \"X\" \"x\" \"x\" \"Z\" \"Y\" \"z\" \"x\" \"X\" \"x\" \"z\"\n[37] \"z\" \"Y\" \"y\" \"X\" \"y\" \"z\" \"Z\" \"z\" \"Z\" \"x\" \"Y\" \"Z\" \"x\" \"z\" \"x\" \"x\" \"X\" \"z\"\n[55] \"y\" \"x\" \"y\" \"x\" \"Z\" \"x\" \"Y\" \"z\" \"z\" \"X\" \"z\" \"Y\" \"X\" \"X\" \"x\" \"z\" \"z\" \"y\"\n[73] \"Z\" \"z\" \"Z\" \"Y\" \"x\" \"Y\" \"x\" \"Z\" \"Y\" \"y\" \"X\" \"x\" \"z\" \"x\" \"Z\" \"x\" \"z\" \"y\"\n[91] \"Z\" \"x\" \"X\" \"Y\" \"X\" \"X\" \"y\" \"x\" \"Y\" \"z\" \"z\" \"X\" \"Y\" \"X\" \"y\" \"x\" \"Y\" \"y\"\n[109] \"Y\" \"X\" \"z\" \"Z\" \"Z\" \"X\" \"Y\" \"Z\" \"Y\" \"Z\" \"X\" \"Y\"" } ]
Accenture Interview Experience for ASE | Off-Campus 2021 - GeeksforGeeks
26 Aug, 2021 Round 1: Cognitive & Technical and Coding Assessment (5th August 2021) This assessment is split into 2 stages. Stage 1: The Cognitive and Technical assessment is a mandatory assessment and will be an elimination round. You must meet their sectional and sub-sectional cut-off to proceed ahead in their recruitments process. You will have 90min to complete 90 questions. Level – Easy & Medium When you are done with stage 1 you need to wait for 5-10 minutes. If (stage1 == cleared){ cout<<"stage2"<<endl; } else{ cout<<"End"<<endl; } Stage 2: After clearing stage 1, you must participate in the Coding assessment and these scores will be considered for our final decisions. You will have 45min to complete 2 coding questions. Level – Easy & Medium When you are done with the coding assessment, you will receive a link for the communication assessment. Round 2: Communication Assessment (7th August 2021) You will receive this mail within 5 days after completing your Round 1. Accenture communication test consists of 6 sections in total. Every section has multiple questions and each question is asked by a different speaker (pre-recorded). Questions are asked orally and no text is displayed (except for the first section). You need to orally answer every question. You will be given 20-30 seconds to answer a question. The next question will be asked immediately after the present one. In other terms, Questions are asked continuously without a break. Section 1: Reading Section 2: Listening Section 3: Q & A Section 4: Jumbled Sentences Section 5: Retelling a story Section 6: Speaking Round 3: Interview Round (13th August 2021) You will receive this mail within a week after completing your Round 2. You need to book a slot for your interview. These are the questions that I was asked during my interview. Introduce Yourself Brief me about your project and then the questions were all about my project. Any hobbies? Any Extra co-curricular activity? Any Achievement My interview was for about 15 – 20 Minutes. P.S: You might need to wait for more than 10 minutes, So don’t panic. P.P.S: I am still waiting for my Interview result. Accenture Marketing Off-Campus Interview Experiences Accenture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE-1 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Infosys DSE Interview Experience 2021
[ { "code": null, "e": 24637, "s": 24609, "text": "\n26 Aug, 2021" }, { "code": null, "e": 24708, "s": 24637, "text": "Round 1: Cognitive & Technical and Coding Assessment (5th August 2021)" }, { "code": null, "e": 24748, "s": 24708, "text": "This assessment is split into 2 stages." }, { "code": null, "e": 25006, "s": 24748, "text": "Stage 1: The Cognitive and Technical assessment is a mandatory assessment and will be an elimination round. You must meet their sectional and sub-sectional cut-off to proceed ahead in their recruitments process. You will have 90min to complete 90 questions." }, { "code": null, "e": 25029, "s": 25006, "text": "Level – Easy & Medium " }, { "code": null, "e": 25095, "s": 25029, "text": "When you are done with stage 1 you need to wait for 5-10 minutes." }, { "code": null, "e": 25170, "s": 25095, "text": "If (stage1 == cleared){\ncout<<\"stage2\"<<endl;\n}\nelse{\ncout<<\"End\"<<endl;\n}" }, { "code": null, "e": 25362, "s": 25170, "text": "Stage 2: After clearing stage 1, you must participate in the Coding assessment and these scores will be considered for our final decisions. You will have 45min to complete 2 coding questions." }, { "code": null, "e": 25385, "s": 25362, "text": "Level – Easy & Medium " }, { "code": null, "e": 25489, "s": 25385, "text": "When you are done with the coding assessment, you will receive a link for the communication assessment." }, { "code": null, "e": 25541, "s": 25489, "text": "Round 2: Communication Assessment (7th August 2021)" }, { "code": null, "e": 25614, "s": 25541, "text": "You will receive this mail within 5 days after completing your Round 1. " }, { "code": null, "e": 25676, "s": 25614, "text": "Accenture communication test consists of 6 sections in total." }, { "code": null, "e": 25863, "s": 25676, "text": "Every section has multiple questions and each question is asked by a different speaker (pre-recorded). Questions are asked orally and no text is displayed (except for the first section)." }, { "code": null, "e": 25905, "s": 25863, "text": "You need to orally answer every question." }, { "code": null, "e": 25959, "s": 25905, "text": "You will be given 20-30 seconds to answer a question." }, { "code": null, "e": 26092, "s": 25959, "text": "The next question will be asked immediately after the present one. In other terms, Questions are asked continuously without a break." }, { "code": null, "e": 26111, "s": 26092, "text": "Section 1: Reading" }, { "code": null, "e": 26132, "s": 26111, "text": "Section 2: Listening" }, { "code": null, "e": 26149, "s": 26132, "text": "Section 3: Q & A" }, { "code": null, "e": 26178, "s": 26149, "text": "Section 4: Jumbled Sentences" }, { "code": null, "e": 26207, "s": 26178, "text": "Section 5: Retelling a story" }, { "code": null, "e": 26229, "s": 26207, "text": "Section 6: Speaking " }, { "code": null, "e": 26273, "s": 26229, "text": "Round 3: Interview Round (13th August 2021)" }, { "code": null, "e": 26346, "s": 26273, "text": "You will receive this mail within a week after completing your Round 2. " }, { "code": null, "e": 26391, "s": 26346, "text": "You need to book a slot for your interview. " }, { "code": null, "e": 26453, "s": 26391, "text": "These are the questions that I was asked during my interview." }, { "code": null, "e": 26473, "s": 26453, "text": " Introduce Yourself" }, { "code": null, "e": 26552, "s": 26473, "text": " Brief me about your project and then the questions were all about my project." }, { "code": null, "e": 26617, "s": 26552, "text": " Any hobbies? Any Extra co-curricular activity? Any Achievement " }, { "code": null, "e": 26662, "s": 26617, "text": "My interview was for about 15 – 20 Minutes. " }, { "code": null, "e": 26733, "s": 26662, "text": "P.S: You might need to wait for more than 10 minutes, So don’t panic. " }, { "code": null, "e": 26784, "s": 26733, "text": "P.P.S: I am still waiting for my Interview result." }, { "code": null, "e": 26794, "s": 26784, "text": "Accenture" }, { "code": null, "e": 26804, "s": 26794, "text": "Marketing" }, { "code": null, "e": 26815, "s": 26804, "text": "Off-Campus" }, { "code": null, "e": 26837, "s": 26815, "text": "Interview Experiences" }, { "code": null, "e": 26847, "s": 26837, "text": "Accenture" }, { "code": null, "e": 26945, "s": 26847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26954, "s": 26945, "text": "Comments" }, { "code": null, "e": 26967, "s": 26954, "text": "Old Comments" }, { "code": null, "e": 27026, "s": 26967, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27076, "s": 27026, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27148, "s": 27076, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 27186, "s": 27148, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 27246, "s": 27186, "text": "Oracle Interview Experience | Set 69 (Application Engineer)" }, { "code": null, "e": 27311, "s": 27246, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 27361, "s": 27311, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 27407, "s": 27361, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27445, "s": 27407, "text": "Amazon Interview Experience for SDE-1" } ]
Find String Matches in a Vector or Matrix in R Programming - str_detect() Function - GeeksforGeeks
03 Jun, 2020 str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the element of the Vector or matrix. Note: This function uses 'stringr' Library. Syntax: str_detect(string, pattern) Parameter:string: specified stringpattern: Pattern to be matched Example 1: # R Program to illustrate # the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx <- c("Geeks", "Hello", "Welcome", "For") # Pattern to be matchedpat <- "Geeks" # Calling str_detect() functionstr_detect(x, pat) Output: [1] TRUE FALSE FALSE FALSE Example 2: # R Program to illustrate # the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx1 <- c("Geeks", "Geeks", "Welcome", "Geeks")x2 <- c("Geeks", "Hello", "Geeks") result <- array(c(x1, x2), dim = c(2, 2, 2)) # Pattern to be matchedpat <- "Geeks" # Printing Matrixresult # Calling str_detect() functionstr_detect(result, pat) Output: ,, 1 [, 1] [, 2] [1, ] "Geeks" "Welcome" [2, ] "Geeks" "Geeks",, 2 [, 1] [, 2] [1, ] "Geeks" "Geeks" [2, ] "Hello" "Geeks" [1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program 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? K-Means Clustering in R Programming
[ { "code": null, "e": 24847, "s": 24819, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25078, "s": 24847, "text": "str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the element of the Vector or matrix." }, { "code": null, "e": 25122, "s": 25078, "text": "Note: This function uses 'stringr' Library." }, { "code": null, "e": 25158, "s": 25122, "text": "Syntax: str_detect(string, pattern)" }, { "code": null, "e": 25223, "s": 25158, "text": "Parameter:string: specified stringpattern: Pattern to be matched" }, { "code": null, "e": 25234, "s": 25223, "text": "Example 1:" }, { "code": "# R Program to illustrate # the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx <- c(\"Geeks\", \"Hello\", \"Welcome\", \"For\") # Pattern to be matchedpat <- \"Geeks\" # Calling str_detect() functionstr_detect(x, pat)", "e": 25479, "s": 25234, "text": null }, { "code": null, "e": 25487, "s": 25479, "text": "Output:" }, { "code": null, "e": 25516, "s": 25487, "text": "[1] TRUE FALSE FALSE FALSE\n" }, { "code": null, "e": 25527, "s": 25516, "text": "Example 2:" }, { "code": "# R Program to illustrate # the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx1 <- c(\"Geeks\", \"Geeks\", \"Welcome\", \"Geeks\")x2 <- c(\"Geeks\", \"Hello\", \"Geeks\") result <- array(c(x1, x2), dim = c(2, 2, 2)) # Pattern to be matchedpat <- \"Geeks\" # Printing Matrixresult # Calling str_detect() functionstr_detect(result, pat)", "e": 25885, "s": 25527, "text": null }, { "code": null, "e": 25893, "s": 25885, "text": "Output:" }, { "code": null, "e": 26096, "s": 25893, "text": ",, 1\n\n [, 1] [, 2] \n[1, ] \"Geeks\" \"Welcome\"\n[2, ] \"Geeks\" \"Geeks\",, 2\n\n [, 1] [, 2] \n[1, ] \"Geeks\" \"Geeks\"\n[2, ] \"Hello\" \"Geeks\"\n\n[1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE\n" }, { "code": null, "e": 26107, "s": 26096, "text": "R Language" }, { "code": null, "e": 26205, "s": 26107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26214, "s": 26205, "text": "Comments" }, { "code": null, "e": 26227, "s": 26214, "text": "Old Comments" }, { "code": null, "e": 26285, "s": 26227, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26329, "s": 26285, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26381, "s": 26329, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26413, "s": 26381, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26465, "s": 26413, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26497, "s": 26465, "text": "Printing Output of an R Program" }, { "code": null, "e": 26535, "s": 26497, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26570, "s": 26535, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26628, "s": 26570, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Plotly - Subplots and Inset Plots
Here, we will understand the concept of subplots and inset plots in Plotly. Sometimes it is helpful to compare different views of data side by side. This supports the concept of subplots. It offers make_subplots() function in plotly.tools module. The function returns a Figure object. The following statement creates two subplots in one row. fig = tools.make_subplots(rows = 1, cols = 2) We can now add two different traces (the exp and log traces in example above) to the figure. fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) The Layout of figure is further configured by specifying title, width, height, etc. using update() method. fig['layout'].update(height = 600, width = 800s, title = 'subplots') Here's the complete script − from plotly import tools import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import numpy as np x = np.arange(1,11) y1 = np.exp(x) y2 = np.log(x) trace1 = go.Scatter( x = x, y = y1, name = 'exp' ) trace2 = go.Scatter( x = x, y = y2, name = 'log' ) fig = tools.make_subplots(rows = 1, cols = 2) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig['layout'].update(height = 600, width = 800, title = 'subplot') iplot(fig) This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ] To display a subplot as inset, we need to configure its trace object. First the xaxis and yaxis properties of inset trace to ‘x2’ and ‘y2’ respectively. Following statement puts ‘log’ trace in inset. trace2 = go.Scatter( x = x, y = y2, xaxis = 'x2', yaxis = 'y2', name = 'log' ) Secondly, configure Layout object where the location of x and y axes of inset is defined by domain property that specifies is position with respective to major axis. xaxis2=dict( domain = [0.1, 0.5], anchor = 'y2' ), yaxis2 = dict( domain = [0.5, 0.9], anchor = 'x2' ) Complete script to display log trace in inset and exp trace on main axis is given below − trace1 = go.Scatter( x = x, y = y1, name = 'exp' ) trace2 = go.Scatter( x = x, y = y2, xaxis = 'x2', yaxis = 'y2', name = 'log' ) data = [trace1, trace2] layout = go.Layout( yaxis = dict(showline = True), xaxis2 = dict( domain = [0.1, 0.5], anchor = 'y2' ), yaxis2 = dict( showline = True, domain = [0.5, 0.9], anchor = 'x2' ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) The output is mentioned below − 12 Lectures 53 mins Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2360, "text": "Here, we will understand the concept of subplots and inset plots in Plotly." }, { "code": null, "e": 2645, "s": 2436, "text": "Sometimes it is helpful to compare different views of data side by side. This supports the concept of subplots. It offers make_subplots() function in plotly.tools module. The function returns a Figure object." }, { "code": null, "e": 2702, "s": 2645, "text": "The following statement creates two subplots in one row." }, { "code": null, "e": 2749, "s": 2702, "text": "fig = tools.make_subplots(rows = 1, cols = 2)\n" }, { "code": null, "e": 2842, "s": 2749, "text": "We can now add two different traces (the exp and log traces in example above) to the figure." }, { "code": null, "e": 2905, "s": 2842, "text": "fig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\n" }, { "code": null, "e": 3012, "s": 2905, "text": "The Layout of figure is further configured by specifying title, width, height, etc. using update() method." }, { "code": null, "e": 3082, "s": 3012, "text": "fig['layout'].update(height = 600, width = 800s, title = 'subplots')\n" }, { "code": null, "e": 3111, "s": 3082, "text": "Here's the complete script −" }, { "code": null, "e": 3659, "s": 3111, "text": "from plotly import tools\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\nimport numpy as np\nx = np.arange(1,11)\ny1 = np.exp(x)\ny2 = np.log(x)\ntrace1 = go.Scatter(\n x = x,\n y = y1,\n name = 'exp'\n)\ntrace2 = go.Scatter(\n x = x,\n y = y2,\n name = 'log'\n)\nfig = tools.make_subplots(rows = 1, cols = 2)\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig['layout'].update(height = 600, width = 800, title = 'subplot')\niplot(fig)" }, { "code": null, "e": 3729, "s": 3659, "text": "This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ]" }, { "code": null, "e": 3929, "s": 3729, "text": "To display a subplot as inset, we need to configure its trace object. First the xaxis and yaxis properties of inset trace to ‘x2’ and ‘y2’ respectively. Following statement puts ‘log’ trace in inset." }, { "code": null, "e": 4023, "s": 3929, "text": "trace2 = go.Scatter(\n x = x,\n y = y2,\n xaxis = 'x2',\n yaxis = 'y2',\n name = 'log'\n)" }, { "code": null, "e": 4189, "s": 4023, "text": "Secondly, configure Layout object where the location of x and y axes of inset is defined by domain property that specifies is position with respective to major axis." }, { "code": null, "e": 4304, "s": 4189, "text": "xaxis2=dict(\n domain = [0.1, 0.5],\n anchor = 'y2'\n),\nyaxis2 = dict(\n domain = [0.5, 0.9],\n anchor = 'x2'\n)" }, { "code": null, "e": 4394, "s": 4304, "text": "Complete script to display log trace in inset and exp trace on main axis is given below −" }, { "code": null, "e": 4845, "s": 4394, "text": "trace1 = go.Scatter(\n x = x,\n y = y1,\n name = 'exp'\n)\ntrace2 = go.Scatter(\n x = x,\n y = y2,\n xaxis = 'x2',\n yaxis = 'y2',\n name = 'log'\n)\ndata = [trace1, trace2]\nlayout = go.Layout(\n yaxis = dict(showline = True),\n xaxis2 = dict(\n domain = [0.1, 0.5],\n anchor = 'y2'\n ),\n yaxis2 = dict(\n showline = True,\n domain = [0.5, 0.9],\n anchor = 'x2'\n )\n)\nfig = go.Figure(data=data, layout=layout)\niplot(fig)" }, { "code": null, "e": 4877, "s": 4845, "text": "The output is mentioned below −" }, { "code": null, "e": 4909, "s": 4877, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4929, "s": 4909, "text": " Pranjal Srivastava" }, { "code": null, "e": 4936, "s": 4929, "text": " Print" }, { "code": null, "e": 4947, "s": 4936, "text": " Add Notes" } ]
How to find all pairs of elements in Java array whose sum is equal to a given number?
To find all pairs of elements in Java array whose sum is equal to a given number − Add each element in the array to all the remaining elements (except itself). Verify if the sum is equal to the required number. If true, print their indices. import java.util.Arrays; import java.util.Scanner; public class sample { public static void main(String args[]){ //Reading the array from the user Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } //Reading the number System.out.println("Enter the number: "); int num = sc.nextInt(); System.out.println("The array created is: "+Arrays.toString(myArray)); System.out.println("indices of the elements whose sum is: "+num); for(int i=0; i<myArray.length; i++){ for (int j=i; j<myArray.length; j++){ if((myArray[i]+myArray[j])== num && i!=j){ System.out.println(i+", "+j); } } } } } Enter the size of the array that is to be created: 8 Enter the elements of the array: 15 12 4 16 9 8 24 0 Enter the number: 24 The array created is: [15, 12, 4, 16, 9, 8, 24, 0] indices of the elements whose sum is: 24 0, 4 3, 5 6, 7
[ { "code": null, "e": 1145, "s": 1062, "text": "To find all pairs of elements in Java array whose sum is equal to a given number −" }, { "code": null, "e": 1222, "s": 1145, "text": "Add each element in the array to all the remaining elements (except itself)." }, { "code": null, "e": 1273, "s": 1222, "text": "Verify if the sum is equal to the required number." }, { "code": null, "e": 1303, "s": 1273, "text": "If true, print their indices." }, { "code": null, "e": 2275, "s": 1303, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class sample {\n public static void main(String args[]){\n //Reading the array from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created: \");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array: \");\n for(int i=0; i<size; i++){\n myArray[i] = sc.nextInt();\n }\n //Reading the number\n System.out.println(\"Enter the number: \");\n int num = sc.nextInt();\n System.out.println(\"The array created is: \"+Arrays.toString(myArray));\n System.out.println(\"indices of the elements whose sum is: \"+num);\n for(int i=0; i<myArray.length; i++){\n for (int j=i; j<myArray.length; j++){\n if((myArray[i]+myArray[j])== num && i!=j){\n System.out.println(i+\", \"+j);\n }\n }\n }\n }\n}" }, { "code": null, "e": 2509, "s": 2275, "text": "Enter the size of the array that is to be created:\n8\nEnter the elements of the array:\n15\n12\n4\n16\n9\n8\n24\n0\nEnter the number:\n24\nThe array created is: [15, 12, 4, 16, 9, 8, 24, 0]\nindices of the elements whose sum is: 24\n0, 4\n3, 5\n6, 7" } ]
VueJS - Examples
<html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> #databinding{ padding: 20px 15px 15px 15px; margin: 0 0 25px 0; width: auto; background-color: #e7e7e7; } span, option, input { font-size:25px; } </style> <div id = "databinding" style = ""> <h1>Currency Converter</h1> <span>Enter Amount:</span><input type = "number" v-model.number = "amount" placeholder = "Enter Amount" /><br/><br/> <span>Convert From:</span> <select v-model = "convertfrom" style = "width:300px;font-size:25px;"> <option v-for = "(a, index) in currencyfrom" v-bind:value = "a.name">{{a.desc}}</option> </select> <span>Convert To:</span> <select v-model = "convertto" style = "width:300px;font-size:25px;"> <option v-for = "(a, index) in currencyfrom" v-bind:value = "a.name">{{a.desc}}</option> </select><br/><br/> <span> {{amount}} {{convertfrom}} equals {{finalamount}} {{convertto}}</span> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { name:'', currencyfrom : [ {name : "USD", desc:"US Dollar"}, {name:"EUR", desc:"Euro"}, {name:"INR", desc:"Indian Rupee"}, {name:"BHD", desc:"Bahraini Dinar"} ], convertfrom: "INR", convertto:"USD", amount :"" }, computed :{ finalamount:function() { var to = this.convertto; var from = this.convertfrom; var final; switch(from) { case "INR": if (to == "USD") { final = this.amount * 0.016; } if (to == "EUR") { final = this.amount * 0.013; } if (to == "INR") { final = this.amount; } if (to == "BHD") { final = this.amount * 0.0059; } break; case "USD": if (to == "INR") { final = this.amount * 63.88; } if (to == "EUR") { final = this.amount * 0.84; } if (to == "USD") { final = this.amount; } if (to == "BHD") { final = this.amount * 0.38; } break; case "EUR": if (to == "INR") { final = this.amount * 76.22; } if (to == "USD") { final = this.amount * 1.19; } if (to == "EUR") { final = this.amount; } if (to == "BHD") { final = this.amount * 0.45; } break; case "BHD": if (to == "INR") { final = this.amount *169.44; } if (to == "USD") { final = this.amount * 2.65; } if (to == "EUR") { final = this.amount * 2.22; } if (to == "BHD") { final = this.amount; } break } return final; } } }); </script> </body> </html> Explanation − In the above example, we have created a currency converter that converts one value of currency to the selected value of other currency. We have created two dropdowns of currency. When we enter the amount to convert in the textbox, the same is displayed below after conversion. We are using the computed property to do the necessary calculation for currency conversion. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> #databinding{ padding: 20px 15px 15px 15px; margin: 0 0 25px 0; width: auto; } span, option, input { font-size:20px; } .Table{ display: table; width:80%; } .Title{ display: table-caption; text-align: center; font-weight: bold; font-size: larger; } .Heading{ display: table-row; font-weight: bold; text-align: center; } .Row{ display: table-row; } .Cell{ display: table-cell; border: solid; border-width: thin; padding-left: 5px; padding-right: 5px; width:30%; } </style> <div id = "databinding" style = ""> <h1>Customer Details</h1> <span>First Name</span> <input type = "text" placeholder = "Enter First Name" v-model = "fname"/> <span>Last Name</span> <input type = "text" placeholder = "Enter Last Name" v-model = "lname"/> <span>Address</span> <input type = "text" placeholder = "Enter Address" v-model = "addr"/> <button v-on:click = "showdata" v-bind:style = "styleobj">Add</button> <br/> <br/> <customercomponent v-for = "(item, index) in custdet" v-bind:item = "item" v-bind:index = "index" v-bind:itr = "item" v-bind:key = "item.fname" v-on:removeelement = "custdet.splice(index, 1)"> </customercomponent> </div> <script type = "text/javascript"> Vue.component('customercomponent',{ template : '<div class = "Table"><div class = "Row" v-bind:style = "styleobj"><div class = "Cell"><p>{{itr.fname}}</p></div><div class = "Cell"><p>{{itr.lname}}</p></div><div class = "Cell"><p>{{itr.addr}}</p></div><div class = "Cell"><p><button v-on:click = "$emit(\'removeelement\')">X</button></p></div></div></div>', props: ['itr', 'index'], data: function() { return { styleobj : { backgroundColor:this.getcolor(), fontSize : 20 } } }, methods:{ getcolor : function() { if (this.index % 2) { return "#FFE633"; } else { return "#D4CA87"; } } } }); var vm = new Vue({ el: '#databinding', data: { fname:'', lname:'', addr : '', custdet:[], styleobj: { backgroundColor: '#2196F3!important', cursor: 'pointer', padding: '8px 16px', verticalAlign: 'middle', } }, methods :{ showdata : function() { this.custdet.push({ fname: this.fname, lname: this.lname, addr : this.addr }); this.fname = ""; this.lname = ""; this.addr = ""; } } }); </script> </body> </html> Explanation − In the above example, we have three texboxes to enter - the First Name, Last Name and Address. There is an add button, which adds the values entered in the textboxes in a table format with a delete button. The table format is created using components. The click button interacts with the parent component using the emit event to delete the elemet from the array. The values entered are stored in the array and the same are shared with the child component using the prop property. Print Add Notes Bookmark this page
[ { "code": null, "e": 6061, "s": 1936, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n #databinding{\n padding: 20px 15px 15px 15px;\n margin: 0 0 25px 0;\n width: auto;\n background-color: #e7e7e7;\n }\n span, option, input {\n font-size:25px;\n }\n </style>\n \n <div id = \"databinding\" style = \"\">\n <h1>Currency Converter</h1>\n <span>Enter Amount:</span><input type = \"number\" v-model.number = \"amount\" placeholder = \"Enter Amount\" /><br/><br/>\n <span>Convert From:</span>\n <select v-model = \"convertfrom\" style = \"width:300px;font-size:25px;\">\n <option v-for = \"(a, index) in currencyfrom\" v-bind:value = \"a.name\">{{a.desc}}</option>\n </select>\n <span>Convert To:</span>\n <select v-model = \"convertto\" style = \"width:300px;font-size:25px;\">\n <option v-for = \"(a, index) in currencyfrom\" v-bind:value = \"a.name\">{{a.desc}}</option>\n </select><br/><br/>\n <span> {{amount}} {{convertfrom}} equals {{finalamount}} {{convertto}}</span>\n </div>\n \n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n name:'',\n currencyfrom : [\n {name : \"USD\", desc:\"US Dollar\"},\n {name:\"EUR\", desc:\"Euro\"},\n {name:\"INR\", desc:\"Indian Rupee\"},\n {name:\"BHD\", desc:\"Bahraini Dinar\"}\n ],\n convertfrom: \"INR\",\n convertto:\"USD\",\n amount :\"\"\n },\n computed :{\n finalamount:function() {\n var to = this.convertto;\n var from = this.convertfrom;\n var final;\n switch(from) {\n case \"INR\":\n if (to == \"USD\") {\n final = this.amount * 0.016;\n }\n if (to == \"EUR\") {\n final = this.amount * 0.013;\n }\n if (to == \"INR\") {\n final = this.amount;\n }\n if (to == \"BHD\") {\n final = this.amount * 0.0059;\n }\n break;\n case \"USD\":\n if (to == \"INR\") {\n final = this.amount * 63.88;\n }\n if (to == \"EUR\") {\n final = this.amount * 0.84;\n }\n if (to == \"USD\") {\n final = this.amount;\n }\n if (to == \"BHD\") {\n final = this.amount * 0.38;\n }\n break;\n case \"EUR\":\n if (to == \"INR\") {\n final = this.amount * 76.22;\n }\n if (to == \"USD\") {\n final = this.amount * 1.19;\n }\n if (to == \"EUR\") {\n final = this.amount;\n }\n if (to == \"BHD\") {\n final = this.amount * 0.45;\n }\n break;\n case \"BHD\":\n if (to == \"INR\") {\n final = this.amount *169.44;\n }\n if (to == \"USD\") {\n final = this.amount * 2.65;\n }\n if (to == \"EUR\") {\n final = this.amount * 2.22;\n }\n if (to == \"BHD\") {\n final = this.amount;\n }\n break\n }\n return final;\n }\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 6444, "s": 6061, "text": "Explanation − In the above example, we have created a currency converter that converts one value of currency to the selected value of other currency. We have created two dropdowns of currency. When we enter the amount to convert in the textbox, the same is displayed below after conversion. We are using the computed property to do the necessary calculation for currency conversion." }, { "code": null, "e": 10092, "s": 6444, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n #databinding{\n padding: 20px 15px 15px 15px;\n margin: 0 0 25px 0;\n width: auto;\n }\n span, option, input {\n font-size:20px;\n }\n .Table{\n display: table;\n width:80%;\n }\n .Title{\n display: table-caption;\n text-align: center;\n font-weight: bold;\n font-size: larger;\n }\n .Heading{\n display: table-row;\n font-weight: bold;\n text-align: center;\n }\n .Row{\n display: table-row;\n }\n .Cell{\n display: table-cell;\n border: solid;\n border-width: thin;\n padding-left: 5px;\n padding-right: 5px;\n width:30%;\n }\n </style>\n \n <div id = \"databinding\" style = \"\">\n <h1>Customer Details</h1>\n <span>First Name</span>\n <input type = \"text\" placeholder = \"Enter First Name\" v-model = \"fname\"/>\n <span>Last Name</span>\n <input type = \"text\" placeholder = \"Enter Last Name\" v-model = \"lname\"/>\n <span>Address</span>\n <input type = \"text\" placeholder = \"Enter Address\" v-model = \"addr\"/>\n <button v-on:click = \"showdata\" v-bind:style = \"styleobj\">Add</button>\n <br/>\n <br/>\n <customercomponent\n v-for = \"(item, index) in custdet\"\n v-bind:item = \"item\"\n v-bind:index = \"index\"\n v-bind:itr = \"item\"\n v-bind:key = \"item.fname\"\n v-on:removeelement = \"custdet.splice(index, 1)\">\n </customercomponent>\n </div>\n \n <script type = \"text/javascript\">\n Vue.component('customercomponent',{\n template : '<div class = \"Table\"><div class = \"Row\" v-bind:style = \"styleobj\"><div class = \"Cell\"><p>{{itr.fname}}</p></div><div class = \"Cell\"><p>{{itr.lname}}</p></div><div class = \"Cell\"><p>{{itr.addr}}</p></div><div class = \"Cell\"><p><button v-on:click = \"$emit(\\'removeelement\\')\">X</button></p></div></div></div>',\n props: ['itr', 'index'],\n data: function() {\n return {\n styleobj : {\n backgroundColor:this.getcolor(),\n fontSize : 20\n }\n }\n },\n methods:{\n getcolor : function() {\n if (this.index % 2) {\n return \"#FFE633\";\n } else {\n return \"#D4CA87\";\n }\n }\n }\n });\n var vm = new Vue({\n el: '#databinding',\n data: {\n fname:'',\n lname:'',\n addr : '',\n custdet:[],\n styleobj: {\n backgroundColor: '#2196F3!important',\n cursor: 'pointer',\n padding: '8px 16px',\n verticalAlign: 'middle',\n }\n },\n methods :{\n showdata : function() {\n this.custdet.push({\n fname: this.fname,\n lname: this.lname,\n addr : this.addr\n });\n this.fname = \"\";\n this.lname = \"\";\n this.addr = \"\";\n }\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 10312, "s": 10092, "text": "Explanation − In the above example, we have three texboxes to enter - the First Name, Last Name and Address. There is an add button, which adds the values entered in the textboxes in a table format with a delete button." }, { "code": null, "e": 10586, "s": 10312, "text": "The table format is created using components. The click button interacts with the parent component using the emit event to delete the elemet from the array. The values entered are stored in the array and the same are shared with the child component using the prop property." }, { "code": null, "e": 10593, "s": 10586, "text": " Print" }, { "code": null, "e": 10604, "s": 10593, "text": " Add Notes" } ]
How to change the scale of Y-axis if the histogram bars are higher than the axis size in R?
When we create a histogram using hist function in R, often the Y-axis labels are smaller than the one or more bars of the histogram. Therefore, the histogram does not look appealing and it becomes a little difficult to match the Y-axis values with the bars size. To solve this problem, we can use ylim argument of hist function in which the range can be supplied to plot on the Y-axis labels. Consider the below data and its histogram − Live Demo set.seed(101) x<-runif(100,2,5) hist(x) Creating the same histogram with higher Y-axis − hist(x,ylim=c(0,25))
[ { "code": null, "e": 1325, "s": 1062, "text": "When we create a histogram using hist function in R, often the Y-axis labels are smaller than the one or more bars of the histogram. Therefore, the histogram does not look appealing and it becomes a little difficult to match the Y-axis values with the bars size." }, { "code": null, "e": 1455, "s": 1325, "text": "To solve this problem, we can use ylim argument of hist function in which the range can be supplied to plot on the Y-axis labels." }, { "code": null, "e": 1499, "s": 1455, "text": "Consider the below data and its histogram −" }, { "code": null, "e": 1510, "s": 1499, "text": " Live Demo" }, { "code": null, "e": 1550, "s": 1510, "text": "set.seed(101)\nx<-runif(100,2,5)\nhist(x)" }, { "code": null, "e": 1599, "s": 1550, "text": "Creating the same histogram with higher Y-axis −" }, { "code": null, "e": 1621, "s": 1599, "text": "hist(x,ylim=c(0,25))\n" } ]
Convert Fahrenheit to Celsius using C Program
The logic that we implement to convert Fahrenheit to Celsius is as follows − celsius = (fahrenheit - 32)*5/9; Refer to the algorithm given below to convert Fahrenheit to Celsius. Step 1: Declare two variables farh, cels Step 2: Enter Fahrenheit value at run time Step 3: Apply formula to convert Cels=(farh-32)*5/9; Step 4: Print cels Following is the C program to convert Fahrenheit to Celsius − Live Demo #include<stdio.h> int main(){ float fahrenheit, celsius; //get the limit of fibonacci series printf("Enter Fahrenheit: \n"); scanf("%f",&fahrenheit); celsius = (fahrenheit - 32)*5/9; printf("Celsius: %f \n", celsius); return 0; } When the above program is executed, it produces the following result − Enter Fahrenheit: 100 Celsius: 37.777779
[ { "code": null, "e": 1139, "s": 1062, "text": "The logic that we implement to convert Fahrenheit to Celsius is as follows −" }, { "code": null, "e": 1172, "s": 1139, "text": "celsius = (fahrenheit - 32)*5/9;" }, { "code": null, "e": 1241, "s": 1172, "text": "Refer to the algorithm given below to convert Fahrenheit to Celsius." }, { "code": null, "e": 1405, "s": 1241, "text": "Step 1: Declare two variables farh, cels\nStep 2: Enter Fahrenheit value at run time\nStep 3: Apply formula to convert\n Cels=(farh-32)*5/9;\nStep 4: Print cels" }, { "code": null, "e": 1467, "s": 1405, "text": "Following is the C program to convert Fahrenheit to Celsius −" }, { "code": null, "e": 1478, "s": 1467, "text": " Live Demo" }, { "code": null, "e": 1729, "s": 1478, "text": "#include<stdio.h>\nint main(){\n float fahrenheit, celsius;\n //get the limit of fibonacci series\n printf(\"Enter Fahrenheit: \\n\");\n scanf(\"%f\",&fahrenheit);\n celsius = (fahrenheit - 32)*5/9;\n printf(\"Celsius: %f \\n\", celsius);\n return 0;\n}" }, { "code": null, "e": 1800, "s": 1729, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 1842, "s": 1800, "text": "Enter Fahrenheit:\n\n100\nCelsius: 37.777779" } ]
Tensorflow.js tf.mean() Function - GeeksforGeeks
18 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.mean() function is used to calculate the mean value of the specified Tensor across its dimension. It reduces the given input elements along the dimensions of axes. If the parameter “keepDims” is true, the reduced dimensions are retained with length 1 else the rank of Tensor is reduced by 1. If the axes parameter has no entries, it returns a Tensor with a single element with all reduced dimensions. Syntax: tf.mean (x, axis?, keepDims?) Parameters: This function accepts three parameters which are illustrated below: x: The input tensor for which mean value is being computed. axis: The specified dimension(s) to reduce. By default it reduces all dimensions. It is optional parameter. keepDims: If this parameter value is true, it retains reduced dimensions with length 1 else the rank of Tensor is reduced by 1. It is also optional parameter. Return Value: It returns a Tensor of mean value. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([2, 4, 7]); // Calling the .mean() function over // the above tensorsa.mean().print();b.mean().print();c.mean().print(); Output: Tensor 0.5 Tensor 4 Tensor 4.333333492279053 Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);const c = tf.tensor1d([2, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .mean() function over // the above tensorsa.mean(axis1).print();b.mean(axis2, true).print();c.mean(axis1, false).print();b.mean(axis3, false).print(); Output: Tensor 0.5 Tensor [[2.5, 6.5],] Tensor 4.333333492279053 Tensor [2.5, 6.5] Reference:https://js.tensorflow.org/api/latest/#mean Tensorflow Tensorflow.js 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": "\n18 May, 2021" }, { "code": null, "e": 25564, "s": 25398, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 25972, "s": 25564, "text": "The tf.mean() function is used to calculate the mean value of the specified Tensor across its dimension. It reduces the given input elements along the dimensions of axes. If the parameter “keepDims” is true, the reduced dimensions are retained with length 1 else the rank of Tensor is reduced by 1. If the axes parameter has no entries, it returns a Tensor with a single element with all reduced dimensions." }, { "code": null, "e": 25980, "s": 25972, "text": "Syntax:" }, { "code": null, "e": 26010, "s": 25980, "text": "tf.mean (x, axis?, keepDims?)" }, { "code": null, "e": 26090, "s": 26010, "text": "Parameters: This function accepts three parameters which are illustrated below:" }, { "code": null, "e": 26150, "s": 26090, "text": "x: The input tensor for which mean value is being computed." }, { "code": null, "e": 26258, "s": 26150, "text": "axis: The specified dimension(s) to reduce. By default it reduces all dimensions. It is optional parameter." }, { "code": null, "e": 26417, "s": 26258, "text": "keepDims: If this parameter value is true, it retains reduced dimensions with length 1 else the rank of Tensor is reduced by 1. It is also optional parameter." }, { "code": null, "e": 26466, "s": 26417, "text": "Return Value: It returns a Tensor of mean value." }, { "code": null, "e": 26477, "s": 26466, "text": "Example 1:" }, { "code": null, "e": 26488, "s": 26477, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([2, 4, 7]); // Calling the .mean() function over // the above tensorsa.mean().print();b.mean().print();c.mean().print();", "e": 26801, "s": 26488, "text": null }, { "code": null, "e": 26809, "s": 26801, "text": "Output:" }, { "code": null, "e": 26863, "s": 26809, "text": "Tensor\n 0.5\nTensor\n 4\nTensor\n 4.333333492279053" }, { "code": null, "e": 26874, "s": 26863, "text": "Example 2:" }, { "code": null, "e": 26885, "s": 26874, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);const c = tf.tensor1d([2, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .mean() function over // the above tensorsa.mean(axis1).print();b.mean(axis2, true).print();c.mean(axis1, false).print();b.mean(axis3, false).print();", "e": 27354, "s": 26885, "text": null }, { "code": null, "e": 27362, "s": 27354, "text": "Output:" }, { "code": null, "e": 27450, "s": 27362, "text": "Tensor\n 0.5\nTensor\n [[2.5, 6.5],]\nTensor\n 4.333333492279053\nTensor\n [2.5, 6.5]" }, { "code": null, "e": 27503, "s": 27450, "text": "Reference:https://js.tensorflow.org/api/latest/#mean" }, { "code": null, "e": 27514, "s": 27503, "text": "Tensorflow" }, { "code": null, "e": 27528, "s": 27514, "text": "Tensorflow.js" }, { "code": null, "e": 27539, "s": 27528, "text": "JavaScript" }, { "code": null, "e": 27556, "s": 27539, "text": "Web Technologies" }, { "code": null, "e": 27654, "s": 27556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27694, "s": 27654, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27755, "s": 27694, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27796, "s": 27755, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27818, "s": 27796, "text": "JavaScript | Promises" }, { "code": null, "e": 27872, "s": 27818, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27912, "s": 27872, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27945, "s": 27912, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27988, "s": 27945, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28038, "s": 27988, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Environment.NewLine in C#
The Enviornment.NewLine in C# is used to add newline. To set a new line in between words − str = "This is demo text!" + Environment.NewLine + "This is demo text on next line!"; The following is the code − Live Demo using System; using System.IO; namespace Demo { class Program { static void Main(string[] args) { string str = "This is demo text!" + Environment.NewLine + "This is demo text on next line!"; Console.Write(str); } } } This is demo text! This is demo text on next line!
[ { "code": null, "e": 1116, "s": 1062, "text": "The Enviornment.NewLine in C# is used to add newline." }, { "code": null, "e": 1153, "s": 1116, "text": "To set a new line in between words −" }, { "code": null, "e": 1239, "s": 1153, "text": "str = \"This is demo text!\" + Environment.NewLine + \"This is demo text on next line!\";" }, { "code": null, "e": 1267, "s": 1239, "text": "The following is the code −" }, { "code": null, "e": 1278, "s": 1267, "text": " Live Demo" }, { "code": null, "e": 1531, "s": 1278, "text": "using System;\nusing System.IO;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n string str = \"This is demo text!\" + Environment.NewLine + \"This is demo text on next line!\";\n Console.Write(str);\n }\n }\n}" }, { "code": null, "e": 1582, "s": 1531, "text": "This is demo text!\nThis is demo text on next line!" } ]
Arrange Balls | Practice | GeeksforGeeks
There are p balls of type P, q balls of type Q and r balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent. Example 1: Input: p = 2, q = 2, r = 2 Output: 30 Explanation: There are 30 possible arrangements of balls. Some of them are PQR, PRQ, PRP, PRQ, PQR,... Example 2: Input: p = 1, q = 1, r = 1 Output: 6 Explanation: There are 6 possible arrangements and these are PQR, PRQ, QPR, QRP, RPQ, RQP. Your Task: You don't need to read or print anything. Your task is to complete the function CountWays() which takes count of P type balls, Q type balls and R type balls and returns total number of possible arrangements such that no two balls of same type are adjacent modulo 109 + 7. Expected Time Complexity: O(N3) where N = max(p, q, r) Expected Space Complexity: O(N3) Constranits: 1 <= p, q, r <= 100 0 somparna7 months ago GFG article mentions this problem as hard then why is it medium here. :( 0 Yashwant Kumar8 months ago Yashwant Kumar Traceback (most recent call last): File "/home/bbb9a1b5f4d7e0ff26f9ceefd79...", line 42, in <module> p, q, r = input().split(" ")ValueError: too many values to unpack (expected 3)Why this is coming ??something wrong with input test cases ?? 0 Abhishek Ranjan Singh9 months ago Abhishek Ranjan Singh For those getting segmentation fault in the submission, define the function (where you coded the algorithm) and dp array globally. It solved my problem. 0 Abhishek Ranjan Singh9 months ago Abhishek Ranjan Singh Not able to submit the question. Giving segmentation fault. I have used a dp array dp[101][101][101][3]; Please check the issue!!! 0 pradeep gupta1 year ago pradeep gupta Siple java Solution- https://practice.geeksforge... 0 Debarshi Maitra2 years ago Debarshi Maitra Top Down DP : https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... 0 Anik Patra2 years ago Anik Patra recursion with memoization .here is my code link->https://ide.geeksforgeeks.o...we have total four choices--->0,1,2,3when choice is 0 in starting we can choose any of the three type of balls.but when last ball choice is 1 we can only choose 2 or 3.so they will be added.similarly for last ball choice 2 and 3.so we need 4 dimensional dp state. 3 dimensional for 3 types of balls and extar one dimansion for the choice available now; 0 Mohit Gautam2 years ago Mohit Gautam solution here#include <bits stdc++.h="">using namespace std; int total(int p,int q,int r,char last,int tot){ if(tot==0) return 1; int count=0; if(p>0 && last!='P') { count+=total(p-1,q,r,'P',tot-1); } if(q>0 && last!='Q') { count+=total(p,q-1,r,'Q',tot-1); } if(r>0 && last!='R') { count+=total(p,q,r-1,'R',tot-1); } return count;}int main() {int t;cin>>t;while(t--){ int x,y,z; cin>>x>>y>>z; cout<<total(x,y,z,'x',x+y+z)<<endl; }="" return="" 0;="" }=""> 0 hemanth gadarla2 years ago hemanth gadarla https://ide.geeksforgeeks.o...JAVA Solution this approach works for even large 1<=p,q,r<=100 0 Shubham Patel2 years ago Shubham Patel Can anyone please explain the algorithm or provide a better resource to learn it ? 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": 398, "s": 226, "text": "There are p balls of type P, q balls of type Q and r balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.\n " }, { "code": null, "e": 409, "s": 398, "text": "Example 1:" }, { "code": null, "e": 551, "s": 409, "text": "Input: p = 2, q = 2, r = 2\nOutput: 30\nExplanation: There are 30 possible arrangements\nof balls. Some of them are PQR, PRQ, PRP, PRQ,\nPQR,...\n" }, { "code": null, "e": 562, "s": 551, "text": "Example 2:" }, { "code": null, "e": 691, "s": 562, "text": "Input: p = 1, q = 1, r = 1\nOutput: 6\nExplanation: There are 6 possible arrangements\nand these are PQR, PRQ, QPR, QRP, RPQ, RQP.\n" }, { "code": null, "e": 978, "s": 693, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function CountWays() which takes count of P type balls, Q type balls and R type balls and returns total number of possible arrangements such that no two balls of same type are adjacent modulo 109 + 7.\n " }, { "code": null, "e": 1068, "s": 978, "text": "Expected Time Complexity: O(N3) where N = max(p, q, r)\nExpected Space Complexity: O(N3)\n " }, { "code": null, "e": 1103, "s": 1068, "text": "Constranits: \n1 <= p, q, r <= 100 " }, { "code": null, "e": 1105, "s": 1103, "text": "0" }, { "code": null, "e": 1126, "s": 1105, "text": "somparna7 months ago" }, { "code": null, "e": 1199, "s": 1126, "text": "GFG article mentions this problem as hard then why is it medium here. :(" }, { "code": null, "e": 1203, "s": 1201, "text": "0" }, { "code": null, "e": 1230, "s": 1203, "text": "Yashwant Kumar8 months ago" }, { "code": null, "e": 1245, "s": 1230, "text": "Yashwant Kumar" }, { "code": null, "e": 1490, "s": 1245, "text": "Traceback (most recent call last): File \"/home/bbb9a1b5f4d7e0ff26f9ceefd79...\", line 42, in <module> p, q, r = input().split(\" \")ValueError: too many values to unpack (expected 3)Why this is coming ??something wrong with input test cases ??" }, { "code": null, "e": 1492, "s": 1490, "text": "0" }, { "code": null, "e": 1526, "s": 1492, "text": "Abhishek Ranjan Singh9 months ago" }, { "code": null, "e": 1548, "s": 1526, "text": "Abhishek Ranjan Singh" }, { "code": null, "e": 1701, "s": 1548, "text": "For those getting segmentation fault in the submission, define the function (where you coded the algorithm) and dp array globally. It solved my problem." }, { "code": null, "e": 1703, "s": 1701, "text": "0" }, { "code": null, "e": 1737, "s": 1703, "text": "Abhishek Ranjan Singh9 months ago" }, { "code": null, "e": 1759, "s": 1737, "text": "Abhishek Ranjan Singh" }, { "code": null, "e": 1864, "s": 1759, "text": "Not able to submit the question. Giving segmentation fault. I have used a dp array dp[101][101][101][3];" }, { "code": null, "e": 1890, "s": 1864, "text": "Please check the issue!!!" }, { "code": null, "e": 1892, "s": 1890, "text": "0" }, { "code": null, "e": 1916, "s": 1892, "text": "pradeep gupta1 year ago" }, { "code": null, "e": 1930, "s": 1916, "text": "pradeep gupta" }, { "code": null, "e": 1951, "s": 1930, "text": "Siple java Solution-" }, { "code": null, "e": 1982, "s": 1951, "text": "https://practice.geeksforge..." }, { "code": null, "e": 1984, "s": 1982, "text": "0" }, { "code": null, "e": 2011, "s": 1984, "text": "Debarshi Maitra2 years ago" }, { "code": null, "e": 2027, "s": 2011, "text": "Debarshi Maitra" }, { "code": null, "e": 2073, "s": 2027, "text": "Top Down DP : https://ide.geeksforgeeks.o..." }, { "code": null, "e": 2104, "s": 2073, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2106, "s": 2104, "text": "0" }, { "code": null, "e": 2128, "s": 2106, "text": "Anik Patra2 years ago" }, { "code": null, "e": 2139, "s": 2128, "text": "Anik Patra" }, { "code": null, "e": 2572, "s": 2139, "text": "recursion with memoization .here is my code link->https://ide.geeksforgeeks.o...we have total four choices--->0,1,2,3when choice is 0 in starting we can choose any of the three type of balls.but when last ball choice is 1 we can only choose 2 or 3.so they will be added.similarly for last ball choice 2 and 3.so we need 4 dimensional dp state. 3 dimensional for 3 types of balls and extar one dimansion for the choice available now;" }, { "code": null, "e": 2574, "s": 2572, "text": "0" }, { "code": null, "e": 2598, "s": 2574, "text": "Mohit Gautam2 years ago" }, { "code": null, "e": 2611, "s": 2598, "text": "Mohit Gautam" }, { "code": null, "e": 2672, "s": 2611, "text": "solution here#include <bits stdc++.h=\"\">using namespace std;" }, { "code": null, "e": 3136, "s": 2672, "text": "int total(int p,int q,int r,char last,int tot){ if(tot==0) return 1; int count=0; if(p>0 && last!='P') { count+=total(p-1,q,r,'P',tot-1); } if(q>0 && last!='Q') { count+=total(p,q-1,r,'Q',tot-1); } if(r>0 && last!='R') { count+=total(p,q,r-1,'R',tot-1); } return count;}int main() {int t;cin>>t;while(t--){ int x,y,z; cin>>x>>y>>z; cout<<total(x,y,z,'x',x+y+z)<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 3138, "s": 3136, "text": "0" }, { "code": null, "e": 3165, "s": 3138, "text": "hemanth gadarla2 years ago" }, { "code": null, "e": 3181, "s": 3165, "text": "hemanth gadarla" }, { "code": null, "e": 3274, "s": 3181, "text": "https://ide.geeksforgeeks.o...JAVA Solution this approach works for even large 1<=p,q,r<=100" }, { "code": null, "e": 3276, "s": 3274, "text": "0" }, { "code": null, "e": 3301, "s": 3276, "text": "Shubham Patel2 years ago" }, { "code": null, "e": 3315, "s": 3301, "text": "Shubham Patel" }, { "code": null, "e": 3398, "s": 3315, "text": "Can anyone please explain the algorithm or provide a better resource to learn it ?" }, { "code": null, "e": 3544, "s": 3398, "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": 3580, "s": 3544, "text": " Login to access your submissions. " }, { "code": null, "e": 3590, "s": 3580, "text": "\nProblem\n" }, { "code": null, "e": 3600, "s": 3590, "text": "\nContest\n" }, { "code": null, "e": 3663, "s": 3600, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3811, "s": 3663, "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": 4019, "s": 3811, "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": 4125, "s": 4019, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Draw a Pentagon using HTML and CSS? - GeeksforGeeks
07 Feb, 2022 A Pentagon is a 5 sided polygon or geometric shape with 5 internal angles measuring 108 degrees each. The pentagon can be drawn using simple HTML and CSS, the below sections will guide you on how to draw the desired shape. HTML Code: In this section we will create a simple div element using the div class with class name “pentagon”. html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pentagon</title></head><body> <div class="pentagon"></div> </body></html> CSS Code: In this section first we will design the div element with some basic CSS properties and the draw the pentagon, we will use CSS :after Selector which inserts something after the content of an element i.e, in our case the div element. css <style>*{ margin: 0; padding: 0; background-color: white; } /* creating the pentagon shape */ .pentagon{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 0; width: 180px; border-top: 180px solid rgb(0, 66, 128); border-left: 90px solid transparent; border-right: 90px solid transparent; } .pentagon:after{ position: absolute; content: ''; border-bottom: 180px solid rgb(0, 66, 128); border-left: 180px solid transparent; border-right: 180px solid transparent; bottom: 180px; left: -90px; } </style> Final Code: It is the combination of the above two code sections. html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pentagon</title></head><style> *{ margin: 0; padding: 0; background-color: white; } /* creating the pentagon shape */ .pentagon{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 0; width: 180px; border-top: 180px solid rgb(0, 66, 128); border-left: 90px solid transparent; border-right: 90px solid transparent; } .pentagon:after{ position: absolute; content: ''; border-bottom: 180px solid rgb(0, 66, 128); border-left: 180px solid transparent; border-right: 180px solid transparent; bottom: 180px; left: -90px; } </style><body> <div class="pentagon"></div> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. varshagumber28 CSS-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26731, "s": 26703, "text": "\n07 Feb, 2022" }, { "code": null, "e": 26954, "s": 26731, "text": "A Pentagon is a 5 sided polygon or geometric shape with 5 internal angles measuring 108 degrees each. The pentagon can be drawn using simple HTML and CSS, the below sections will guide you on how to draw the desired shape." }, { "code": null, "e": 27065, "s": 26954, "text": "HTML Code: In this section we will create a simple div element using the div class with class name “pentagon”." }, { "code": null, "e": 27070, "s": 27065, "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>Pentagon</title></head><body> <div class=\"pentagon\"></div> </body></html>", "e": 27311, "s": 27070, "text": null }, { "code": null, "e": 27557, "s": 27311, "text": "CSS Code: In this section first we will design the div element with some basic CSS properties and the draw the pentagon, we will use CSS :after Selector which inserts something after the content of an element i.e, in our case the div element." }, { "code": null, "e": 27561, "s": 27557, "text": "css" }, { "code": "<style>*{ margin: 0; padding: 0; background-color: white; } /* creating the pentagon shape */ .pentagon{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 0; width: 180px; border-top: 180px solid rgb(0, 66, 128); border-left: 90px solid transparent; border-right: 90px solid transparent; } .pentagon:after{ position: absolute; content: ''; border-bottom: 180px solid rgb(0, 66, 128); border-left: 180px solid transparent; border-right: 180px solid transparent; bottom: 180px; left: -90px; } </style>", "e": 28162, "s": 27561, "text": null }, { "code": null, "e": 28228, "s": 28162, "text": "Final Code: It is the combination of the above two code sections." }, { "code": null, "e": 28233, "s": 28228, "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>Pentagon</title></head><style> *{ margin: 0; padding: 0; background-color: white; } /* creating the pentagon shape */ .pentagon{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 0; width: 180px; border-top: 180px solid rgb(0, 66, 128); border-left: 90px solid transparent; border-right: 90px solid transparent; } .pentagon:after{ position: absolute; content: ''; border-bottom: 180px solid rgb(0, 66, 128); border-left: 180px solid transparent; border-right: 180px solid transparent; bottom: 180px; left: -90px; } </style><body> <div class=\"pentagon\"></div> </body></html>", "e": 29132, "s": 28233, "text": null }, { "code": null, "e": 29140, "s": 29132, "text": "Output:" }, { "code": null, "e": 29277, "s": 29140, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29292, "s": 29277, "text": "varshagumber28" }, { "code": null, "e": 29301, "s": 29292, "text": "CSS-Misc" }, { "code": null, "e": 29305, "s": 29301, "text": "CSS" }, { "code": null, "e": 29310, "s": 29305, "text": "HTML" }, { "code": null, "e": 29327, "s": 29310, "text": "Web Technologies" }, { "code": null, "e": 29332, "s": 29327, "text": "HTML" }, { "code": null, "e": 29430, "s": 29332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29469, "s": 29430, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29506, "s": 29469, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29535, "s": 29506, "text": "Form validation using jQuery" }, { "code": null, "e": 29570, "s": 29535, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29612, "s": 29570, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29672, "s": 29612, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29725, "s": 29672, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29786, "s": 29725, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29810, "s": 29786, "text": "REST API (Introduction)" } ]
Intersection of two arrays | Practice | GeeksforGeeks
Given two arrays a[] and b[] respectively of size n and m, the task is to print the count of elements in the intersection (or common elements) of the two arrays. For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays. Example 1: Input: n = 5, m = 3 a[] = {89, 24, 75, 11, 23} b[] = {89, 2, 4} Output: 1 Explanation: 89 is the only element in the intersection of two arrays. Example 2: Input: n = 6, m = 5 a[] = {1, 2, 3, 4, 5, 6} b[] = {3, 4, 5, 6, 7} Output: 4 Explanation: 3 4 5 and 6 are the elements in the intersection of two arrays. Your Task: You don't need to read input or print anything. Your task is to complete the function NumberofElementsInIntersection() which takes two integers n and m and their respective arrays a[] and b[] as input. The function should return the count of the number of elements in the intersection. Expected Time Complexity: O(n + m). Expected Auxiliary Space: O(min(n,m)). Constraints: 1 ≤ n, m ≤ 105 1 ≤ a[i], b[i] ≤ 105 +1 kashyapjhon1 day ago C++ Solution Time=(0.63/2.25) EASY: int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code goes here unordered_set<int> u; for(int i=0;i<n;i++){ u.insert(a[i]); } int c=0; for(int i=0;i<m;i++){ auto it= u.find(b[i]); if(it!=u.end()){ c++; u.erase(b[i]); } } return c; } +1 shubham211019976 days ago public static int NumberofElementsInIntersection(int a[], int b[], int n, int m) { HashSet<Integer>h=new HashSet<>(); for(int i:a){ h.add(i); } int res=0; for(int i:b){ if(h.contains(i)){ res++; h.remove(i); } } return res; } 0 raghavendra7776 days ago Python 0.38S def NumberofElementsInIntersection(self,a, b, n, m): #return: expected length of the intersection array. a=set(a) b=set(b) z=a.intersection(b) return len(z) 0 mehtay0376 days ago Python Solution: class Solution: def NumberofElementsInIntersection(self,a, b, n, m): return len(set(a).intersection(set(b))) 0 harshscode1 week ago // set contains unique elements.. // map conatains duplicate elements........ set<int> m; for(int i=0;i<n;i++) m.insert(a[i]); int cnt=0; for(int i=0;i<n1;i++) { if(m.find(b[i])!=m.end()) { m.erase(b[i]); cnt++; } } 0 ahadfardeen1 week ago DON'T IGNORE TO REMOVE THE ALREADY COUNT ELEMENT FROM THE ARRAY OTHERWISE IT WOULD BE COUNT MULTIPLE TIMES class Solution { // Function to return the count of the number of elements in // the intersection of two arrays. public static int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code here HashSet<Integer>hset= new HashSet<>(); for(int i=0;i<n;i++){ hset.add(a[i]); } int count=0; for(int j=0;j<m;j++){ if(hset.contains(b[j])){ count++; hset.remove(b[j]); } } return count; } }; 0 hr15171517hr1 week ago HashSet<Integer> hs1 = new HashSet<>(), hs2 = new HashSet<>(); int res = 0; for (int i = 0; i < n; i++) { hs1.add(a[i]); } for (int i = 0; i < m; i++) { if (hs1.contains(b[i]) && !hs2.contains(b[i])) { hs2.add(b[i]); res++; } } return res; 0 mayank180919992 weeks ago int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code goes here unordered_map<int,int>mp; set<int>s; for(int i=0;i<n;i++){ mp[a[i]]++; } for(int i=0;i<m;i++){ if(mp[b[i]]){ s.insert(b[i]); mp[b[i]]--; } } return s.size(); } 0 abera25832 weeks ago what wrong in my code? unordered_map<int,int>map; for(int i=0;i<n;i++){ map[a[i]]++; } for(int i=0;i<m;i++){ map[b[i]]++; } int count=0; for(auto it:map){ if(it.second!=1){ count++; } } return count; } 0 shrustis1763 weeks ago C++ solution using MAPS //why erase? bcoz intersection has to be unique, so we need to count only once and to prevent it from counting again we erase. int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code goes here unordered_map<int,int>mp; int cnt=0; for(int i=0;i<n; i++) mp[a[i]]++; for(int i=0; i<m; i++) if(mp.count(b[i])) { mp.erase(b[i]); cnt++; } return cnt; } 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": 400, "s": 238, "text": "Given two arrays a[] and b[] respectively of size n and m, the task is to print the count of elements in the intersection (or common elements) of the two arrays." }, { "code": null, "e": 537, "s": 400, "text": "For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays. " }, { "code": null, "e": 548, "s": 537, "text": "Example 1:" }, { "code": null, "e": 697, "s": 548, "text": "Input:\nn = 5, m = 3\na[] = {89, 24, 75, 11, 23}\nb[] = {89, 2, 4}\n\nOutput: 1\n\nExplanation: \n89 is the only element \nin the intersection of two arrays." }, { "code": null, "e": 708, "s": 697, "text": "Example 2:" }, { "code": null, "e": 868, "s": 708, "text": "Input:\nn = 6, m = 5\na[] = {1, 2, 3, 4, 5, 6}\nb[] = {3, 4, 5, 6, 7} \n\nOutput: 4\n\nExplanation: \n3 4 5 and 6 are the elements \nin the intersection of two arrays.\n" }, { "code": null, "e": 1166, "s": 868, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function NumberofElementsInIntersection() which takes two integers n and m and their respective arrays a[] and b[] as input. The function should return the count of the number of elements in the intersection." }, { "code": null, "e": 1243, "s": 1168, "text": "Expected Time Complexity: O(n + m).\nExpected Auxiliary Space: O(min(n,m))." }, { "code": null, "e": 1292, "s": 1243, "text": "Constraints:\n1 ≤ n, m ≤ 105\n1 ≤ a[i], b[i] ≤ 105" }, { "code": null, "e": 1295, "s": 1292, "text": "+1" }, { "code": null, "e": 1316, "s": 1295, "text": "kashyapjhon1 day ago" }, { "code": null, "e": 1352, "s": 1316, "text": "C++ Solution Time=(0.63/2.25) EASY:" }, { "code": null, "e": 1731, "s": 1352, "text": "int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code goes here unordered_set<int> u; for(int i=0;i<n;i++){ u.insert(a[i]); } int c=0; for(int i=0;i<m;i++){ auto it= u.find(b[i]); if(it!=u.end()){ c++; u.erase(b[i]); } } return c; }" }, { "code": null, "e": 1734, "s": 1731, "text": "+1" }, { "code": null, "e": 1760, "s": 1734, "text": "shubham211019976 days ago" }, { "code": null, "e": 2109, "s": 1760, "text": "public static int NumberofElementsInIntersection(int a[], int b[], int n, int m) {\n \n HashSet<Integer>h=new HashSet<>();\n for(int i:a){\n h.add(i);\n }\n int res=0;\n for(int i:b){\n if(h.contains(i)){\n res++;\n h.remove(i);\n }\n }\n return res;\n }" }, { "code": null, "e": 2111, "s": 2109, "text": "0" }, { "code": null, "e": 2136, "s": 2111, "text": "raghavendra7776 days ago" }, { "code": null, "e": 2149, "s": 2136, "text": "Python 0.38S" }, { "code": null, "e": 2336, "s": 2149, "text": "def NumberofElementsInIntersection(self,a, b, n, m): #return: expected length of the intersection array. a=set(a) b=set(b) z=a.intersection(b) return len(z)" }, { "code": null, "e": 2338, "s": 2336, "text": "0" }, { "code": null, "e": 2358, "s": 2338, "text": "mehtay0376 days ago" }, { "code": null, "e": 2375, "s": 2358, "text": "Python Solution:" }, { "code": null, "e": 2446, "s": 2375, "text": "class Solution: def NumberofElementsInIntersection(self,a, b, n, m):" }, { "code": null, "e": 2495, "s": 2446, "text": " return len(set(a).intersection(set(b)))" }, { "code": null, "e": 2501, "s": 2499, "text": "0" }, { "code": null, "e": 2522, "s": 2501, "text": "harshscode1 week ago" }, { "code": null, "e": 2803, "s": 2522, "text": " // set contains unique elements.. // map conatains duplicate elements........ set<int> m; for(int i=0;i<n;i++) m.insert(a[i]); int cnt=0; for(int i=0;i<n1;i++) { if(m.find(b[i])!=m.end()) { m.erase(b[i]); cnt++; } }" }, { "code": null, "e": 2805, "s": 2803, "text": "0" }, { "code": null, "e": 2827, "s": 2805, "text": "ahadfardeen1 week ago" }, { "code": null, "e": 2934, "s": 2827, "text": "DON'T IGNORE TO REMOVE THE ALREADY COUNT ELEMENT FROM THE ARRAY OTHERWISE IT WOULD BE COUNT MULTIPLE TIMES" }, { "code": null, "e": 3463, "s": 2936, "text": "class Solution {\n // Function to return the count of the number of elements in\n // the intersection of two arrays.\n public static int NumberofElementsInIntersection(int a[], int b[], int n, int m) {\n // Your code here\n HashSet<Integer>hset= new HashSet<>();\n for(int i=0;i<n;i++){\n hset.add(a[i]);\n }\n int count=0;\n for(int j=0;j<m;j++){\n if(hset.contains(b[j])){\n count++;\n hset.remove(b[j]);\n }\n }\n return count;\n }\n};" }, { "code": null, "e": 3465, "s": 3463, "text": "0" }, { "code": null, "e": 3488, "s": 3465, "text": "hr15171517hr1 week ago" }, { "code": null, "e": 3844, "s": 3488, "text": "HashSet<Integer> hs1 = new HashSet<>(), hs2 = new HashSet<>();\n int res = 0;\n for (int i = 0; i < n; i++) {\n hs1.add(a[i]);\n }\n for (int i = 0; i < m; i++) {\n if (hs1.contains(b[i]) && !hs2.contains(b[i])) {\n hs2.add(b[i]);\n res++;\n }\n }\n return res;" }, { "code": null, "e": 3846, "s": 3844, "text": "0" }, { "code": null, "e": 3872, "s": 3846, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 4269, "s": 3872, "text": " int NumberofElementsInIntersection(int a[], int b[], int n, int m) {\n \n // Your code goes here\n unordered_map<int,int>mp;\n set<int>s;\n for(int i=0;i<n;i++){\n mp[a[i]]++;\n }\n for(int i=0;i<m;i++){\n if(mp[b[i]]){\n s.insert(b[i]);\n mp[b[i]]--;\n }\n }\n return s.size(); \n }" }, { "code": null, "e": 4271, "s": 4269, "text": "0" }, { "code": null, "e": 4292, "s": 4271, "text": "abera25832 weeks ago" }, { "code": null, "e": 4315, "s": 4292, "text": "what wrong in my code?" }, { "code": null, "e": 4598, "s": 4315, "text": "unordered_map<int,int>map; for(int i=0;i<n;i++){ map[a[i]]++; } for(int i=0;i<m;i++){ map[b[i]]++; } int count=0; for(auto it:map){ if(it.second!=1){ count++; } } return count; }" }, { "code": null, "e": 4600, "s": 4598, "text": "0" }, { "code": null, "e": 4623, "s": 4600, "text": "shrustis1763 weeks ago" }, { "code": null, "e": 4647, "s": 4623, "text": "C++ solution using MAPS" }, { "code": null, "e": 4775, "s": 4647, "text": " //why erase? bcoz intersection has to be unique, so we need to count only once and to prevent it from counting again we erase." }, { "code": null, "e": 5151, "s": 4777, "text": "int NumberofElementsInIntersection(int a[], int b[], int n, int m) { // Your code goes here unordered_map<int,int>mp; int cnt=0; for(int i=0;i<n; i++) mp[a[i]]++; for(int i=0; i<m; i++) if(mp.count(b[i])) { mp.erase(b[i]); cnt++; } return cnt; }" }, { "code": null, "e": 5301, "s": 5155, "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": 5337, "s": 5301, "text": " Login to access your submissions. " }, { "code": null, "e": 5347, "s": 5337, "text": "\nProblem\n" }, { "code": null, "e": 5357, "s": 5347, "text": "\nContest\n" }, { "code": null, "e": 5420, "s": 5357, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5568, "s": 5420, "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": 5776, "s": 5568, "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": 5882, "s": 5776, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to disable browser Autocomplete on web form field/input tag?
18 Nov, 2020 Input text autocomplete is the default feature of any browser. While working with the form or input fields in HTML web page autocomplete feature of the browsers come in the picture. By default autocomplete is enabled in browsers so when submitting the form it remembers the information. So when again open the same form or fill the same input fields it shows the suggestions which were filled earlier by the user. The autocomplete attribute is used to enable and disable autocompletion of text. This attribute contains two values: on off To disable the autocomplete feature in the form or input field the autocomplete attribute set to off. Syntax: autocomplete: on/off Example: This example does not use autocomplete attribute so by default the autocomplete attribute is enable. <!DOCTYPE html><html> <head> <title> HTML autocomplete attribute </title> <style> form { margin: 10%; } .form-control { margin-top: 10px; } </style> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" ></head> <body> <div class="container col-lg-12 form"> <form action="/submit" method="post" enctype="multipart/form-data"> <div class="form-group"> <input type="text" class="form-control form-control-sm" id="name" name="username" placeholder="Enter Name"> <input type="text" class="form-control form-control-sm" id="email" name="email" placeholder="Enter Email"> <input type="text" class="form-control form-control-sm" id="city" name="city" placeholder="Enter City"> <br> <button type="submit" class="btn btn-primary"> Submit </button> </div> </form> </div></body> </html> Output: Note: The autocomplete suggestions will be displayed always as per previously filled information to the form. Example 2: This example sets autocomplete attribute to off. <!DOCTYPE html><html> <head> <title> HTML autocomplete attribute </title> <style> form { margin: 10%; } .form-control { margin-top: 10px; } </style> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" ></head> <body> <div class="container col-lg-12 form"> <form action="/submit" autocomplete="off" method="post" enctype="multipart/form-data"> <div class="form-group"> <input type="text" class="form-control form-control-sm" id="name" name="username" placeholder="Enter Name"> <input type="text" class="form-control form-control-sm" id="email" name="email" placeholder="Enter Email"> <input type="text" class="form-control form-control-sm" id="city" name="city" placeholder="Enter City"> <br> <button type="submit" class="btn btn-primary"> Submit </button> </div> </form> </div></body> </html> Output: Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Nov, 2020" }, { "code": null, "e": 466, "s": 52, "text": "Input text autocomplete is the default feature of any browser. While working with the form or input fields in HTML web page autocomplete feature of the browsers come in the picture. By default autocomplete is enabled in browsers so when submitting the form it remembers the information. So when again open the same form or fill the same input fields it shows the suggestions which were filled earlier by the user." }, { "code": null, "e": 583, "s": 466, "text": "The autocomplete attribute is used to enable and disable autocompletion of text. This attribute contains two values:" }, { "code": null, "e": 586, "s": 583, "text": "on" }, { "code": null, "e": 590, "s": 586, "text": "off" }, { "code": null, "e": 692, "s": 590, "text": "To disable the autocomplete feature in the form or input field the autocomplete attribute set to off." }, { "code": null, "e": 700, "s": 692, "text": "Syntax:" }, { "code": null, "e": 721, "s": 700, "text": "autocomplete: on/off" }, { "code": null, "e": 831, "s": 721, "text": "Example: This example does not use autocomplete attribute so by default the autocomplete attribute is enable." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML autocomplete attribute </title> <style> form { margin: 10%; } .form-control { margin-top: 10px; } </style> <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"stylesheet\" ></head> <body> <div class=\"container col-lg-12 form\"> <form action=\"/submit\" method=\"post\" enctype=\"multipart/form-data\"> <div class=\"form-group\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"name\" name=\"username\" placeholder=\"Enter Name\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"email\" name=\"email\" placeholder=\"Enter Email\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"city\" name=\"city\" placeholder=\"Enter City\"> <br> <button type=\"submit\" class=\"btn btn-primary\"> Submit </button> </div> </form> </div></body> </html> ", "e": 2128, "s": 831, "text": null }, { "code": null, "e": 2136, "s": 2128, "text": "Output:" }, { "code": null, "e": 2246, "s": 2136, "text": "Note: The autocomplete suggestions will be displayed always as per previously filled information to the form." }, { "code": null, "e": 2306, "s": 2246, "text": "Example 2: This example sets autocomplete attribute to off." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML autocomplete attribute </title> <style> form { margin: 10%; } .form-control { margin-top: 10px; } </style> <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"stylesheet\" ></head> <body> <div class=\"container col-lg-12 form\"> <form action=\"/submit\" autocomplete=\"off\" method=\"post\" enctype=\"multipart/form-data\"> <div class=\"form-group\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"name\" name=\"username\" placeholder=\"Enter Name\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"email\" name=\"email\" placeholder=\"Enter Email\"> <input type=\"text\" class=\"form-control form-control-sm\" id=\"city\" name=\"city\" placeholder=\"Enter City\"> <br> <button type=\"submit\" class=\"btn btn-primary\"> Submit </button> </div> </form> </div></body> </html> ", "e": 3613, "s": 2306, "text": null }, { "code": null, "e": 3621, "s": 3613, "text": "Output:" }, { "code": null, "e": 3628, "s": 3621, "text": "Picked" }, { "code": null, "e": 3633, "s": 3628, "text": "HTML" }, { "code": null, "e": 3650, "s": 3633, "text": "Web Technologies" }, { "code": null, "e": 3677, "s": 3650, "text": "Web technologies Questions" }, { "code": null, "e": 3682, "s": 3677, "text": "HTML" } ]
Creating a radar sweep animation using arcade in Python
19 Oct, 2020 The Radar Sweep are used for displays of single level sweeps of radar data, and their display appears in the Main Display window. With the help of arcade module of Python, it is possible to perform a radar sweep animation. Before starting, it is highly recommended to revise concepts of arcade library. To perform a radar sweep animation, follow the below steps:- Step 1: Import arcade as well math module in you respective Ide. import arcade import math Step 2: Specify the parameters for the output window. # Set up the constants WIDTH = 800 _HEIGHT = 600 TITLE = "Radar Sweep" Step 3: These constants control the particulars about the radar. CENTER_X = SCREEN_WIDTH // 2 CENTER_Y = SCREEN_HEIGHT // 2 RADIANS_PER_FRAME = 0.02 SWEEP_LENGTH = 250 Step 4: Define a on_draw function, under which move the angle of the sweep and calculate the end point of our radar sweep, using math . Lastly draw the outline of the radar. def on_draw(_delta_time): # Move the angle of the sweep. on_draw.angle += RADIANS_PER_FRAME # Calculate the end point of our radar sweep. x = SWEEP_LENGTH * math.sin(on_draw.angle) + CENTER_X y = SWEEP_LENGTH * math.cos(on_draw.angle) + CENTER_Y # Start the render. arcade.start_render() # Draw the radar line arcade.draw_line(CENTER_X, CENTER_Y, x, y, arcade.color.OLIVE, 4) # Draw the outline of the radar arcade.draw_circle_outline(CENTER_X, CENTER_Y, SWEEP_LENGTH, arcade.color.DARK_GREEN, 10) # This is a function-specific variable i.e # we need to give them initial # values. on_draw.angle = 0 Step 5: Define main function. def main(): # Open up our window arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) arcade.set_background_color(arcade.color.BLACK) # Tell the computer to call the draw command at # the specified interval. arcade.schedule(on_draw, 1 / 80) # Run the program arcade.run() # close the window. arcade.close_window() main() The radar sweep will looks like this – Complete source code: Python3 import arcadeimport math # Set up the constantsSCREEN_WIDTH = 800SCREEN_HEIGHT = 600SCREEN_TITLE = "Radar Sweep Example" # These constants control the particulars # about the radarCENTER_X = SCREEN_WIDTH // 2CENTER_Y = SCREEN_HEIGHT // 2RADIANS_PER_FRAME = 0.02SWEEP_LENGTH = 250 def on_draw(_delta_time): # Move the angle of the sweep. on_draw.angle += RADIANS_PER_FRAME # Calculate the end point of our radar sweep. Using math. x = SWEEP_LENGTH * math.sin(on_draw.angle) + CENTER_X y = SWEEP_LENGTH * math.cos(on_draw.angle) + CENTER_Y # Start the render. arcade.start_render() # Draw the radar line arcade.draw_line(CENTER_X, CENTER_Y, x, y, arcade.color.OLIVE, 4) # Draw the outline of the radar arcade.draw_circle_outline(CENTER_X, CENTER_Y, SWEEP_LENGTH, arcade.color.DARK_GREEN, 10) on_draw.angle = 0 def main(): # Open up our window arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) arcade.set_background_color(arcade.color.BLACK) # Tell the computer to call the draw command at the specified interval. arcade.schedule(on_draw, 1 / 80) # Run the program arcade.run() # close the window. arcade.close_window() main() Output: Python-Arcade Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Oct, 2020" }, { "code": null, "e": 357, "s": 54, "text": "The Radar Sweep are used for displays of single level sweeps of radar data, and their display appears in the Main Display window. With the help of arcade module of Python, it is possible to perform a radar sweep animation. Before starting, it is highly recommended to revise concepts of arcade library." }, { "code": null, "e": 418, "s": 357, "text": "To perform a radar sweep animation, follow the below steps:-" }, { "code": null, "e": 483, "s": 418, "text": "Step 1: Import arcade as well math module in you respective Ide." }, { "code": null, "e": 509, "s": 483, "text": "import arcade\nimport math" }, { "code": null, "e": 563, "s": 509, "text": "Step 2: Specify the parameters for the output window." }, { "code": null, "e": 634, "s": 563, "text": "# Set up the constants\nWIDTH = 800\n_HEIGHT = 600\nTITLE = \"Radar Sweep\"" }, { "code": null, "e": 699, "s": 634, "text": "Step 3: These constants control the particulars about the radar." }, { "code": null, "e": 802, "s": 699, "text": "CENTER_X = SCREEN_WIDTH // 2\nCENTER_Y = SCREEN_HEIGHT // 2\nRADIANS_PER_FRAME = 0.02\nSWEEP_LENGTH = 250" }, { "code": null, "e": 976, "s": 802, "text": "Step 4: Define a on_draw function, under which move the angle of the sweep and calculate the end point of our radar sweep, using math . Lastly draw the outline of the radar." }, { "code": null, "e": 1640, "s": 976, "text": "def on_draw(_delta_time):\n # Move the angle of the sweep.\n on_draw.angle += RADIANS_PER_FRAME\n \n # Calculate the end point of our radar sweep. \n x = SWEEP_LENGTH * math.sin(on_draw.angle) + CENTER_X\n y = SWEEP_LENGTH * math.cos(on_draw.angle) + CENTER_Y\n \n # Start the render. \n arcade.start_render()\n \n # Draw the radar line\n arcade.draw_line(CENTER_X, CENTER_Y, x, y,\n arcade.color.OLIVE, 4)\n \n # Draw the outline of the radar\n arcade.draw_circle_outline(CENTER_X, CENTER_Y, \n SWEEP_LENGTH, arcade.color.DARK_GREEN, 10)\n\n# This is a function-specific variable i.e \n# we need to give them initial\n# values.\non_draw.angle = 0 " }, { "code": null, "e": 1670, "s": 1640, "text": "Step 5: Define main function." }, { "code": null, "e": 2050, "s": 1670, "text": "def main():\n\n # Open up our window\n arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT,\n SCREEN_TITLE)\n arcade.set_background_color(arcade.color.BLACK)\n \n # Tell the computer to call the draw command at\n # the specified interval.\n arcade.schedule(on_draw, 1 / 80)\n \n # Run the program\n arcade.run()\n \n # close the window.\n arcade.close_window()\n main()" }, { "code": null, "e": 2089, "s": 2050, "text": "The radar sweep will looks like this –" }, { "code": null, "e": 2111, "s": 2089, "text": "Complete source code:" }, { "code": null, "e": 2119, "s": 2111, "text": "Python3" }, { "code": "import arcadeimport math # Set up the constantsSCREEN_WIDTH = 800SCREEN_HEIGHT = 600SCREEN_TITLE = \"Radar Sweep Example\" # These constants control the particulars # about the radarCENTER_X = SCREEN_WIDTH // 2CENTER_Y = SCREEN_HEIGHT // 2RADIANS_PER_FRAME = 0.02SWEEP_LENGTH = 250 def on_draw(_delta_time): # Move the angle of the sweep. on_draw.angle += RADIANS_PER_FRAME # Calculate the end point of our radar sweep. Using math. x = SWEEP_LENGTH * math.sin(on_draw.angle) + CENTER_X y = SWEEP_LENGTH * math.cos(on_draw.angle) + CENTER_Y # Start the render. arcade.start_render() # Draw the radar line arcade.draw_line(CENTER_X, CENTER_Y, x, y, arcade.color.OLIVE, 4) # Draw the outline of the radar arcade.draw_circle_outline(CENTER_X, CENTER_Y, SWEEP_LENGTH, arcade.color.DARK_GREEN, 10) on_draw.angle = 0 def main(): # Open up our window arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) arcade.set_background_color(arcade.color.BLACK) # Tell the computer to call the draw command at the specified interval. arcade.schedule(on_draw, 1 / 80) # Run the program arcade.run() # close the window. arcade.close_window() main()", "e": 3375, "s": 2119, "text": null }, { "code": null, "e": 3383, "s": 3375, "text": "Output:" }, { "code": null, "e": 3397, "s": 3383, "text": "Python-Arcade" }, { "code": null, "e": 3404, "s": 3397, "text": "Python" } ]
Java Program to Iterate Over Characters in String
06 Jun, 2021 Given string str of length N, the task is to traverse the string and print all the characters of the given string using java. Illustration: Input : str = “GeeksforGeeks” Output : G e e k s f o r G e e k s Input : str = "GfG" Output : G f G Methods: Using for loops(Naive approach)Using iterators (Optimal approach) Using for loops(Naive approach) Using iterators (Optimal approach) Method 1: Using for loops The simplest or rather we can say naive approach to solve this problem is to iterate using a for loop by using the variable ‘i’ till the length of the string and then print the value of each character that is present in the string. Example Java // Java Program to Iterate Over Characters in String // Class 1// Main class// To iterate over charactersclass GFG { // Method 1 // To traverse the string and // print the characters of the string static void getChar(String str) { // Traverse the string using for loop for (int i = 0; i < str.length(); i++) { // Printing the current character System.out.print(str.charAt(i)); // Printing a space after each letter System.out.print(" "); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating a String variable to store the string String str = "GeeksforGeeks"; // Calling the getChar method getChar(str); }} G e e k s f o r G e e k s Time complexity is O(N) and space complexity is O(1) Method 2: Using iterators The string can be traversed using an iterator. We would be importing CharacterIterator and StringCharacterIterator classes from java.text package Example: Java // Java Program to Iterate Over Characters in String // Importing input output classesimport java.io.*;// Importing CharacterIterator and StringCharacterIterator// classes from java.text packageimport java.text.CharacterIterator;import java.text.StringCharacterIterator; // Main class// To iterate over charactersclass GFG { // Method 1 // To traverse the string and // print the characters of the string static void getChar(String str) { // Creating a CharacterIterator variable CharacterIterator itr = new StringCharacterIterator(str); // Iterating using while loop while (itr.current() != CharacterIterator.DONE) { // Print the current character System.out.print(itr.current()); // Print a space after each letter System.out.print(" "); // Getting the next input from the user // using the next() method itr.next(); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating a String variable to store the string String str = "GfG"; // Calling the getChar method getChar(str); }} G f G Time Complexity: O(N) and space complexity is of order O(1) Java-String-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2021" }, { "code": null, "e": 178, "s": 52, "text": "Given string str of length N, the task is to traverse the string and print all the characters of the given string using java." }, { "code": null, "e": 192, "s": 178, "text": "Illustration:" }, { "code": null, "e": 258, "s": 192, "text": "Input : str = “GeeksforGeeks”\nOutput : G e e k s f o r G e e k s" }, { "code": null, "e": 294, "s": 258, "text": "Input : str = \"GfG\"\nOutput : G f G" }, { "code": null, "e": 303, "s": 294, "text": "Methods:" }, { "code": null, "e": 369, "s": 303, "text": "Using for loops(Naive approach)Using iterators (Optimal approach)" }, { "code": null, "e": 401, "s": 369, "text": "Using for loops(Naive approach)" }, { "code": null, "e": 436, "s": 401, "text": "Using iterators (Optimal approach)" }, { "code": null, "e": 462, "s": 436, "text": "Method 1: Using for loops" }, { "code": null, "e": 695, "s": 462, "text": "The simplest or rather we can say naive approach to solve this problem is to iterate using a for loop by using the variable ‘i’ till the length of the string and then print the value of each character that is present in the string. " }, { "code": null, "e": 703, "s": 695, "text": "Example" }, { "code": null, "e": 708, "s": 703, "text": "Java" }, { "code": "// Java Program to Iterate Over Characters in String // Class 1// Main class// To iterate over charactersclass GFG { // Method 1 // To traverse the string and // print the characters of the string static void getChar(String str) { // Traverse the string using for loop for (int i = 0; i < str.length(); i++) { // Printing the current character System.out.print(str.charAt(i)); // Printing a space after each letter System.out.print(\" \"); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating a String variable to store the string String str = \"GeeksforGeeks\"; // Calling the getChar method getChar(str); }}", "e": 1493, "s": 708, "text": null }, { "code": null, "e": 1520, "s": 1493, "text": "G e e k s f o r G e e k s " }, { "code": null, "e": 1573, "s": 1520, "text": "Time complexity is O(N) and space complexity is O(1)" }, { "code": null, "e": 1599, "s": 1573, "text": "Method 2: Using iterators" }, { "code": null, "e": 1745, "s": 1599, "text": "The string can be traversed using an iterator. We would be importing CharacterIterator and StringCharacterIterator classes from java.text package" }, { "code": null, "e": 1754, "s": 1745, "text": "Example:" }, { "code": null, "e": 1759, "s": 1754, "text": "Java" }, { "code": "// Java Program to Iterate Over Characters in String // Importing input output classesimport java.io.*;// Importing CharacterIterator and StringCharacterIterator// classes from java.text packageimport java.text.CharacterIterator;import java.text.StringCharacterIterator; // Main class// To iterate over charactersclass GFG { // Method 1 // To traverse the string and // print the characters of the string static void getChar(String str) { // Creating a CharacterIterator variable CharacterIterator itr = new StringCharacterIterator(str); // Iterating using while loop while (itr.current() != CharacterIterator.DONE) { // Print the current character System.out.print(itr.current()); // Print a space after each letter System.out.print(\" \"); // Getting the next input from the user // using the next() method itr.next(); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating a String variable to store the string String str = \"GfG\"; // Calling the getChar method getChar(str); }}", "e": 2976, "s": 1759, "text": null }, { "code": null, "e": 2983, "s": 2976, "text": "G f G " }, { "code": null, "e": 3043, "s": 2983, "text": "Time Complexity: O(N) and space complexity is of order O(1)" }, { "code": null, "e": 3064, "s": 3043, "text": "Java-String-Programs" }, { "code": null, "e": 3071, "s": 3064, "text": "Picked" }, { "code": null, "e": 3076, "s": 3071, "text": "Java" }, { "code": null, "e": 3090, "s": 3076, "text": "Java Programs" }, { "code": null, "e": 3095, "s": 3090, "text": "Java" } ]
Math floorDiv() method in Java
20 Jun, 2018 The java.lang.Math.floorDiv() is a built-in math function in java which returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient. As floorDiv() is static, so object creation is not required. Syntax: public static int floorDiv(data_type x, data_type y) Parameter: The function accepts two parameters as described below. x: The first parameter refers to the dividend value. y: The second parameter refers to the divisor value. The parameters can be data-type int or long. Exception: ArithmeticException: It throws ArithmeticException if the divisor is zero. Return Value: This method returns the largest (closest to positive infinity) integer value that is less than or equal to the algebraic quotient. Below programs illustrate the java.lang.Math.floorDiv() method: Program 1: // Java program to demonstrate working// of java.lang.Math.floorDiv() methodimport java.lang.Math; class Gfg1{ // driver code public static void main(String args[]) { int a = 25, b = 5; System.out.println(Math.floorDiv(a, b)); // 125/50 value is 2.5, but as output is integer // less than or equal to 2.5, So output is 2 int c = 125, d = 50; System.out.println(Math.floorDiv(c, d)); }} 5 2 Program 2: // Java program to demonstrate working// of java.lang.Math.floorDiv() methodimport java.lang.Math; class Gfg2 { // driver code public static void main(String args[]) { int x = 200; int y = 0; System.out.println(Math.floorDiv(x, y)); }} Output: Runtime Error : Exception in thread "main" java.lang.ArithmeticException: / by zero at java.lang.Math.floorDiv(Math.java:1052) at Gfg2.main(File.java:13) Java-Functions java-math Java Mathematical Mathematical Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2018" }, { "code": null, "e": 301, "s": 53, "text": "The java.lang.Math.floorDiv() is a built-in math function in java which returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient. As floorDiv() is static, so object creation is not required." }, { "code": null, "e": 309, "s": 301, "text": "Syntax:" }, { "code": null, "e": 362, "s": 309, "text": "public static int floorDiv(data_type x, data_type y)" }, { "code": null, "e": 429, "s": 362, "text": "Parameter: The function accepts two parameters as described below." }, { "code": null, "e": 482, "s": 429, "text": "x: The first parameter refers to the dividend value." }, { "code": null, "e": 535, "s": 482, "text": "y: The second parameter refers to the divisor value." }, { "code": null, "e": 580, "s": 535, "text": "The parameters can be data-type int or long." }, { "code": null, "e": 591, "s": 580, "text": "Exception:" }, { "code": null, "e": 666, "s": 591, "text": "ArithmeticException: It throws ArithmeticException if the divisor is zero." }, { "code": null, "e": 811, "s": 666, "text": "Return Value: This method returns the largest (closest to positive infinity) integer value that is less than or equal to the algebraic quotient." }, { "code": null, "e": 875, "s": 811, "text": "Below programs illustrate the java.lang.Math.floorDiv() method:" }, { "code": null, "e": 886, "s": 875, "text": "Program 1:" }, { "code": "// Java program to demonstrate working// of java.lang.Math.floorDiv() methodimport java.lang.Math; class Gfg1{ // driver code public static void main(String args[]) { int a = 25, b = 5; System.out.println(Math.floorDiv(a, b)); // 125/50 value is 2.5, but as output is integer // less than or equal to 2.5, So output is 2 int c = 125, d = 50; System.out.println(Math.floorDiv(c, d)); }}", "e": 1335, "s": 886, "text": null }, { "code": null, "e": 1340, "s": 1335, "text": "5\n2\n" }, { "code": null, "e": 1351, "s": 1340, "text": "Program 2:" }, { "code": "// Java program to demonstrate working// of java.lang.Math.floorDiv() methodimport java.lang.Math; class Gfg2 { // driver code public static void main(String args[]) { int x = 200; int y = 0; System.out.println(Math.floorDiv(x, y)); }}", "e": 1625, "s": 1351, "text": null }, { "code": null, "e": 1633, "s": 1625, "text": "Output:" }, { "code": null, "e": 1796, "s": 1633, "text": "Runtime Error :\nException in thread \"main\" java.lang.ArithmeticException: / by zero\n at java.lang.Math.floorDiv(Math.java:1052)\n at Gfg2.main(File.java:13)\n" }, { "code": null, "e": 1811, "s": 1796, "text": "Java-Functions" }, { "code": null, "e": 1821, "s": 1811, "text": "java-math" }, { "code": null, "e": 1826, "s": 1821, "text": "Java" }, { "code": null, "e": 1839, "s": 1826, "text": "Mathematical" }, { "code": null, "e": 1852, "s": 1839, "text": "Mathematical" }, { "code": null, "e": 1857, "s": 1852, "text": "Java" } ]
Groovy - toUpperCase()
Converts all of the characters in this String to upper case. String toUpperCase() None The modified string in upper case. Following is an example of the usage of this method − class Example { static void main(String[] args) { String a = "HelloWorld"; println(a.toUpperCase()); } } When we run the above program, we will get the following result −
[ { "code": null, "e": 2433, "s": 2372, "text": "Converts all of the characters in this String to upper case." }, { "code": null, "e": 2455, "s": 2433, "text": "String toUpperCase()\n" }, { "code": null, "e": 2460, "s": 2455, "text": "None" }, { "code": null, "e": 2495, "s": 2460, "text": "The modified string in upper case." }, { "code": null, "e": 2549, "s": 2495, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2677, "s": 2549, "text": "class Example { \n static void main(String[] args) { \n String a = \"HelloWorld\"; \n println(a.toUpperCase()); \n } \n}" } ]
How to Terminate a Thread in C#
01 Feb, 2019 In C#, a thread can be terminated using Abort() method. Abort() throws ThreadAbortException to the thread in which it called. Due to this exception, the thread is terminated. There are two methods in the overload list of Thread.Abort Method as follows: Abort()Abort(Object) Abort() Abort(Object) This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Generally, this method is used to terminate the thread. Syntax: public void Abort(); Exceptions: SecurityException: If the caller does not have the required permission. ThreadStateException: If the thread that is being aborted is currently suspended. Example: // C# program to illustrate the// concept of Abort() method// on a single threadusing System;using System.Threading; class ExampleofThread { // Non-Static method public void thread() { for (int x = 0; x < 3; x++) { Console.WriteLine(x); } }} // Driver Classclass ThreadExample { // Main method public static void Main() { // Creating instance for mythread() method ExampleofThread obj = new ExampleofThread(); // Creating and initializing threads Thread thr = new Thread(new ThreadStart(obj.thread)); thr.Start(); Console.WriteLine("Thread is abort"); // Abort thr thread // Using Abort() method thr.Abort(); }} Output: Thread is abort Explanation: The above example shows the use of Abort() method which is provided by the Thread class. By using thr.Abort(); statement, we can terminate the execution of thr thread. This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Generally, this method is used to terminate the thread. Syntax: public void Abort(object information); Here, the information contains any information that you want to pass in a thread when it is being stopped. This information is only accessible by using ExceptionState property of ThreadAbortException. Exceptions: SecurityException: If the caller does not have the required permission. ThreadStateException: If the thread that is being aborted is currently suspended. Example: // C# program to illustrate the// concept of Abort(object)using System;using System.Threading; class ExThread { public Thread thr; public ExThread(string name) { thr = new Thread(this.RunThread); thr.Name = name; thr.Start(); } // Enetring point for thread void RunThread() { try { Console.WriteLine(thr.Name + " is starting."); for (int j = 1; j <= 100; j++) { Console.Write(j + " "); if ((j % 10) == 0) { Console.WriteLine(); Thread.Sleep(200); } } Console.WriteLine(thr.Name + " exiting normally."); } catch (ThreadAbortException ex) { Console.WriteLine("Thread is aborted and the code is " + ex.ExceptionState); } }} // Driver Classclass GFG { // Main method static void Main() { // Creating object of ExThread ExThread obj = new ExThread("Thread "); Thread.Sleep(1000); Console.WriteLine("Stop thread"); obj.thr.Abort(100); // Waiting for a thread to terminate. obj.thr.Join(); Console.WriteLine("Main thread is terminating"); }} Output: Thread is starting. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 Stop thread Thread is aborted and the code is 100 Main thread is terminating Important Points: A deadlock can occur if the thread that calls Abort methods holds a lock that the aborted thread requires. If the Abort method is called on a thread which has not been started, then that thread will abort when Start is called. If the Abort method is called on a thread which is blocked or is sleeping then the thread will get interrupted and after that get aborted. If Abort method is called on a suspended thread then a ThreadStateException is thrown in the thread that called Abort, and AbortRequested is added to the ThreadState property of the thread being aborted. A ThreadAbortException is not thrown in the suspended thread until Resume is called. If the Abort method is called on a Managed thread which is currently executing unmanaged code then a ThreadAbortException is not thrown until the thread returns to managed code. If two calls to Abort come at the same time then it is possible for one call to set the state information and the other call to execute the Abort. But, an application cannot detect this situation. After Abort is called on a thread, the state of the thread includes AbortRequested. After the thread has terminated due to the result of a successful call to Abort, the state of the thread is changed to Stopped. With sufficient permissions, a thread which is the target of an Abort can cancel the abort using the ResetAbort method. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.abort?view=netframework-4.7.2 CSharp Multithreading CSharp Thread Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 281, "s": 28, "text": "In C#, a thread can be terminated using Abort() method. Abort() throws ThreadAbortException to the thread in which it called. Due to this exception, the thread is terminated. There are two methods in the overload list of Thread.Abort Method as follows:" }, { "code": null, "e": 302, "s": 281, "text": "Abort()Abort(Object)" }, { "code": null, "e": 310, "s": 302, "text": "Abort()" }, { "code": null, "e": 324, "s": 310, "text": "Abort(Object)" }, { "code": null, "e": 508, "s": 324, "text": "This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Generally, this method is used to terminate the thread." }, { "code": null, "e": 516, "s": 508, "text": "Syntax:" }, { "code": null, "e": 537, "s": 516, "text": "public void Abort();" }, { "code": null, "e": 549, "s": 537, "text": "Exceptions:" }, { "code": null, "e": 621, "s": 549, "text": "SecurityException: If the caller does not have the required permission." }, { "code": null, "e": 703, "s": 621, "text": "ThreadStateException: If the thread that is being aborted is currently suspended." }, { "code": null, "e": 712, "s": 703, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of Abort() method// on a single threadusing System;using System.Threading; class ExampleofThread { // Non-Static method public void thread() { for (int x = 0; x < 3; x++) { Console.WriteLine(x); } }} // Driver Classclass ThreadExample { // Main method public static void Main() { // Creating instance for mythread() method ExampleofThread obj = new ExampleofThread(); // Creating and initializing threads Thread thr = new Thread(new ThreadStart(obj.thread)); thr.Start(); Console.WriteLine(\"Thread is abort\"); // Abort thr thread // Using Abort() method thr.Abort(); }}", "e": 1450, "s": 712, "text": null }, { "code": null, "e": 1458, "s": 1450, "text": "Output:" }, { "code": null, "e": 1475, "s": 1458, "text": "Thread is abort\n" }, { "code": null, "e": 1656, "s": 1475, "text": "Explanation: The above example shows the use of Abort() method which is provided by the Thread class. By using thr.Abort(); statement, we can terminate the execution of thr thread." }, { "code": null, "e": 1912, "s": 1656, "text": "This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Generally, this method is used to terminate the thread." }, { "code": null, "e": 1920, "s": 1912, "text": "Syntax:" }, { "code": null, "e": 1959, "s": 1920, "text": "public void Abort(object information);" }, { "code": null, "e": 2160, "s": 1959, "text": "Here, the information contains any information that you want to pass in a thread when it is being stopped. This information is only accessible by using ExceptionState property of ThreadAbortException." }, { "code": null, "e": 2172, "s": 2160, "text": "Exceptions:" }, { "code": null, "e": 2244, "s": 2172, "text": "SecurityException: If the caller does not have the required permission." }, { "code": null, "e": 2326, "s": 2244, "text": "ThreadStateException: If the thread that is being aborted is currently suspended." }, { "code": null, "e": 2335, "s": 2326, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of Abort(object)using System;using System.Threading; class ExThread { public Thread thr; public ExThread(string name) { thr = new Thread(this.RunThread); thr.Name = name; thr.Start(); } // Enetring point for thread void RunThread() { try { Console.WriteLine(thr.Name + \" is starting.\"); for (int j = 1; j <= 100; j++) { Console.Write(j + \" \"); if ((j % 10) == 0) { Console.WriteLine(); Thread.Sleep(200); } } Console.WriteLine(thr.Name + \" exiting normally.\"); } catch (ThreadAbortException ex) { Console.WriteLine(\"Thread is aborted and the code is \" + ex.ExceptionState); } }} // Driver Classclass GFG { // Main method static void Main() { // Creating object of ExThread ExThread obj = new ExThread(\"Thread \"); Thread.Sleep(1000); Console.WriteLine(\"Stop thread\"); obj.thr.Abort(100); // Waiting for a thread to terminate. obj.thr.Join(); Console.WriteLine(\"Main thread is terminating\"); }}", "e": 3678, "s": 2335, "text": null }, { "code": null, "e": 3686, "s": 3678, "text": "Output:" }, { "code": null, "e": 3931, "s": 3686, "text": "Thread is starting.\n1 2 3 4 5 6 7 8 9 10 \n11 12 13 14 15 16 17 18 19 20 \n21 22 23 24 25 26 27 28 29 30 \n31 32 33 34 35 36 37 38 39 40 \n41 42 43 44 45 46 47 48 49 50 \nStop thread\nThread is aborted and the code is 100\nMain thread is terminating\n" }, { "code": null, "e": 3949, "s": 3931, "text": "Important Points:" }, { "code": null, "e": 4056, "s": 3949, "text": "A deadlock can occur if the thread that calls Abort methods holds a lock that the aborted thread requires." }, { "code": null, "e": 4176, "s": 4056, "text": "If the Abort method is called on a thread which has not been started, then that thread will abort when Start is called." }, { "code": null, "e": 4315, "s": 4176, "text": "If the Abort method is called on a thread which is blocked or is sleeping then the thread will get interrupted and after that get aborted." }, { "code": null, "e": 4519, "s": 4315, "text": "If Abort method is called on a suspended thread then a ThreadStateException is thrown in the thread that called Abort, and AbortRequested is added to the ThreadState property of the thread being aborted." }, { "code": null, "e": 4604, "s": 4519, "text": "A ThreadAbortException is not thrown in the suspended thread until Resume is called." }, { "code": null, "e": 4782, "s": 4604, "text": "If the Abort method is called on a Managed thread which is currently executing unmanaged code then a ThreadAbortException is not thrown until the thread returns to managed code." }, { "code": null, "e": 4979, "s": 4782, "text": "If two calls to Abort come at the same time then it is possible for one call to set the state information and the other call to execute the Abort. But, an application cannot detect this situation." }, { "code": null, "e": 5311, "s": 4979, "text": "After Abort is called on a thread, the state of the thread includes AbortRequested. After the thread has terminated due to the result of a successful call to Abort, the state of the thread is changed to Stopped. With sufficient permissions, a thread which is the target of an Abort can cancel the abort using the ResetAbort method." }, { "code": null, "e": 5322, "s": 5311, "text": "Reference:" }, { "code": null, "e": 5420, "s": 5322, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.abort?view=netframework-4.7.2" }, { "code": null, "e": 5442, "s": 5420, "text": "CSharp Multithreading" }, { "code": null, "e": 5462, "s": 5442, "text": "CSharp Thread Class" }, { "code": null, "e": 5465, "s": 5462, "text": "C#" } ]
How to Create Animation Loading Bar using CSS ?
09 Jul, 2020 Loading Bar with animation can be created using HTML and CSS. We will create a Loader that is the part of an operating system that is responsible for loading programs and libraries. The progress bar is a graphical control element used to visualize the progression of an extended computer operation, so here we use the progress bar as an animation in loader. We will create a loading bar using HTML and CSS properties. HTML Code: In this section, we will design the basic structure of the HTML code. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Loader Bar</title> <link rel="stylesheet" href="style.css"></head> <body> <div class="loader"> <div class="loading_1"></div> <div class="loading_2">Loading GfG...</div> </div></body> </html> CSS Code: In this section, we will use some CSS property to design the loading bar. We will use @keyframes which specifies animation code. The animation is created by gradually changing from one set of CSS styles to another. The changes in styles happen in percent using the keywords “from” (0%) and “to” (100%). We can change the set of CSS styles many times. <style> body { background-color: #262626; font-family: Lato, sans-serif; } .loader { width: 150px; margin: 150px auto 70px; position: relative; } .loader .loading_1 { position: relative; width: 100%; height: 10px; border: 1px solid yellowgreen; border-radius: 10px; animation: turn 4s linear 1.75s infinite; } .loader .loading_1:before { content: ""; display: block; position: absolute; width: 0; height: 100%; background-color: yellowgreen; box-shadow: 10px 0px 15px 0px yellowgreen; animation: load 2s linear infinite; } .loader .loading_2 { position: absolute; width: 100%; top: 10px; color: green; font-size: 22px; text-align: center; animation: bounce 2s linear infinite; } @keyframes load { 0% { width: 0%; } 87.5% { width: 100%; } } @keyframes turn { 0% { transform: rotateY(0deg); } 6.25%, 50% { transform: rotateY(180deg); } 56.25%, 100% { transform: rotateY(360deg); } } @keyframes bounce { 0%, 100% { top: 10px; } 12.5% { top: 30px; } }</style> Complete Code: It is the combination of above two code section of HTML and CSS. In the following code, we have added the CSS code internally in the HTML code. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Loader Bar</title> <style> body { background-color: #262626; font-family: Lato, sans-serif; } .loader { width: 150px; margin: 150px auto 70px; position: relative; } .loader .loading_1 { position: relative; width: 100%; height: 10px; border: 1px solid yellowgreen; border-radius: 10px; animation: turn 4s linear 1.75s infinite; } .loader .loading_1:before { content: ""; display: block; position: absolute; width: 0; height: 100%; background-color: yellowgreen; box-shadow: 10px 0px 15px 0px yellowgreen; animation: load 2s linear infinite; } .loader .loading_2 { position: absolute; width: 100%; top: 10px; color: green; font-size: 22px; text-align: center; animation: bounce 2s linear infinite; } @keyframes load { 0% { width: 0%; } 87.5% { width: 100%; } } @keyframes turn { 0% { transform: rotateY(0deg); } 6.25%, 50% { transform: rotateY(180deg); } 56.25%, 100% { transform: rotateY(360deg); } } @keyframes bounce { 0%, 100% { top: 10px; } 12.5% { top: 30px; } } </style></head> <body> <div class="loader"> <div class="loading_1"></div> <div class="loading_2">Loading GfG...</div> </div></body> </html> Output: The following image shows the loading bar with animation. CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2020" }, { "code": null, "e": 116, "s": 54, "text": "Loading Bar with animation can be created using HTML and CSS." }, { "code": null, "e": 472, "s": 116, "text": "We will create a Loader that is the part of an operating system that is responsible for loading programs and libraries. The progress bar is a graphical control element used to visualize the progression of an extended computer operation, so here we use the progress bar as an animation in loader. We will create a loading bar using HTML and CSS properties." }, { "code": null, "e": 553, "s": 472, "text": "HTML Code: In this section, we will design the basic structure of the HTML code." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Loader Bar</title> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"loader\"> <div class=\"loading_1\"></div> <div class=\"loading_2\">Loading GfG...</div> </div></body> </html>", "e": 935, "s": 553, "text": null }, { "code": null, "e": 1296, "s": 935, "text": "CSS Code: In this section, we will use some CSS property to design the loading bar. We will use @keyframes which specifies animation code. The animation is created by gradually changing from one set of CSS styles to another. The changes in styles happen in percent using the keywords “from” (0%) and “to” (100%). We can change the set of CSS styles many times." }, { "code": "<style> body { background-color: #262626; font-family: Lato, sans-serif; } .loader { width: 150px; margin: 150px auto 70px; position: relative; } .loader .loading_1 { position: relative; width: 100%; height: 10px; border: 1px solid yellowgreen; border-radius: 10px; animation: turn 4s linear 1.75s infinite; } .loader .loading_1:before { content: \"\"; display: block; position: absolute; width: 0; height: 100%; background-color: yellowgreen; box-shadow: 10px 0px 15px 0px yellowgreen; animation: load 2s linear infinite; } .loader .loading_2 { position: absolute; width: 100%; top: 10px; color: green; font-size: 22px; text-align: center; animation: bounce 2s linear infinite; } @keyframes load { 0% { width: 0%; } 87.5% { width: 100%; } } @keyframes turn { 0% { transform: rotateY(0deg); } 6.25%, 50% { transform: rotateY(180deg); } 56.25%, 100% { transform: rotateY(360deg); } } @keyframes bounce { 0%, 100% { top: 10px; } 12.5% { top: 30px; } }</style>", "e": 2702, "s": 1296, "text": null }, { "code": null, "e": 2861, "s": 2702, "text": "Complete Code: It is the combination of above two code section of HTML and CSS. In the following code, we have added the CSS code internally in the HTML code." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Loader Bar</title> <style> body { background-color: #262626; font-family: Lato, sans-serif; } .loader { width: 150px; margin: 150px auto 70px; position: relative; } .loader .loading_1 { position: relative; width: 100%; height: 10px; border: 1px solid yellowgreen; border-radius: 10px; animation: turn 4s linear 1.75s infinite; } .loader .loading_1:before { content: \"\"; display: block; position: absolute; width: 0; height: 100%; background-color: yellowgreen; box-shadow: 10px 0px 15px 0px yellowgreen; animation: load 2s linear infinite; } .loader .loading_2 { position: absolute; width: 100%; top: 10px; color: green; font-size: 22px; text-align: center; animation: bounce 2s linear infinite; } @keyframes load { 0% { width: 0%; } 87.5% { width: 100%; } } @keyframes turn { 0% { transform: rotateY(0deg); } 6.25%, 50% { transform: rotateY(180deg); } 56.25%, 100% { transform: rotateY(360deg); } } @keyframes bounce { 0%, 100% { top: 10px; } 12.5% { top: 30px; } } </style></head> <body> <div class=\"loader\"> <div class=\"loading_1\"></div> <div class=\"loading_2\">Loading GfG...</div> </div></body> </html>", "e": 4876, "s": 2861, "text": null }, { "code": null, "e": 4942, "s": 4876, "text": "Output: The following image shows the loading bar with animation." }, { "code": null, "e": 4951, "s": 4942, "text": "CSS-Misc" }, { "code": null, "e": 4961, "s": 4951, "text": "HTML-Misc" }, { "code": null, "e": 4965, "s": 4961, "text": "CSS" }, { "code": null, "e": 4970, "s": 4965, "text": "HTML" }, { "code": null, "e": 4987, "s": 4970, "text": "Web Technologies" }, { "code": null, "e": 4992, "s": 4987, "text": "HTML" }, { "code": null, "e": 5090, "s": 4992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5129, "s": 5090, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5168, "s": 5129, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5207, "s": 5168, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 5236, "s": 5207, "text": "Form validation using jQuery" }, { "code": null, "e": 5273, "s": 5236, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 5297, "s": 5273, "text": "REST API (Introduction)" }, { "code": null, "e": 5350, "s": 5297, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5410, "s": 5350, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5471, "s": 5410, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Ruby | Class Method and Variables
11 Nov, 2019 Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.Syntax 1: def class_method_name # some code end Here, we can access the above method only with the help of an object.Syntax 2: def class_name.class_method_name or self.class_method_name # some code end Here, we can access the above method there is no need to create objects of the Class as we can directly access it.Here, the self keyword refers to the entire class itself, not to an instance of the class. In this case, we are inside the class only, not inside an instance method of that class. So, we are in the class scope. Class Variables are the variables that are defined inside the class, where only the class method has access to. Class Variables starts with @@ and must be initialized first then they can be used in method definitions.Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module within which the class variables are defined.When a class variables is override it will produce warnings with the -w option. Syntax: @@variable_name = value What is the use of class variables and methods? Let’s say for suppose we want to keep a count of how many grocery items you have added to your shopping items, for that, we need a variable apart from instance variable as instance variable appears unique for every object created and by using a global variable it can be easily manipulated from anywhere from the program. So, for we use a class variable and with the help of a class method we can keep track of the total number of grocery items got listed and in many various other ways. Below is the example: # Program in Ruby for a count of total Grocery itemsclass Grocery # class variable@@total_count = 0 # class array@@items_list = [] def add_item(item) # adding item to the array @@items_list.push(item) @@total_count += 1#countingend def print_items puts "Total number of items --> #@@total_count"; puts "All items --> #@@items_list";end# direct accessdef Grocery.printitems_only# or self.printitems_only puts "\nGrocery.printitems_only", @@items_list.join("\n");endend list = Grocery.new() list.add_item("shampoo")list.add_item("face wash")list.add_item("serum")list.add_item("mud pack")list.add_item("tea tree oil")list.add_item("toner") list.print_items # direct accessGrocery.printitems_only # throws an errorlist.printitems_only Output Total number of items --> 6 All items --> ["shampoo", "face wash", "serum", "mud pack", "tea tree oil", "toner"] Grocery.printitems_only shampoo face wash serum mud pack tea tree oil toner main.rb:35:in `': undefined method `printitems_only' for # (NoMethodError) Did you mean? print_items Here we are using the @@total_count class variable, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@total_count class variable and increment its value by 1. And, we are using the @@items_list class array, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@items_list class array and adds the item name to the array. We can access the class variables anywhere in the class in both class and instance methods. And if we use either self.printitems_only or Grocery.printitems_only they execute the same but while accessing we can only access by class name as self represents the class only inside the class. Picked Ruby class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Include v/s Extend in Ruby Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Array select() function Ruby | Case Statement Ruby | Hash delete() function Ruby | unless Statement and unless Modifier Ruby | Data Types Ruby | String capitalize() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2019" }, { "code": null, "e": 350, "s": 28, "text": "Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.Syntax 1:" }, { "code": null, "e": 390, "s": 350, "text": "def class_method_name\n # some code\nend" }, { "code": null, "e": 469, "s": 390, "text": "Here, we can access the above method only with the help of an object.Syntax 2:" }, { "code": null, "e": 546, "s": 469, "text": "def class_name.class_method_name or self.class_method_name\n # some code\nend" }, { "code": null, "e": 871, "s": 546, "text": "Here, we can access the above method there is no need to create objects of the Class as we can directly access it.Here, the self keyword refers to the entire class itself, not to an instance of the class. In this case, we are inside the class only, not inside an instance method of that class. So, we are in the class scope." }, { "code": null, "e": 1344, "s": 871, "text": "Class Variables are the variables that are defined inside the class, where only the class method has access to. Class Variables starts with @@ and must be initialized first then they can be used in method definitions.Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module within which the class variables are defined.When a class variables is override it will produce warnings with the -w option." }, { "code": null, "e": 1352, "s": 1344, "text": "Syntax:" }, { "code": null, "e": 1376, "s": 1352, "text": "@@variable_name = value" }, { "code": null, "e": 1424, "s": 1376, "text": "What is the use of class variables and methods?" }, { "code": null, "e": 1746, "s": 1424, "text": "Let’s say for suppose we want to keep a count of how many grocery items you have added to your shopping items, for that, we need a variable apart from instance variable as instance variable appears unique for every object created and by using a global variable it can be easily manipulated from anywhere from the program." }, { "code": null, "e": 1912, "s": 1746, "text": "So, for we use a class variable and with the help of a class method we can keep track of the total number of grocery items got listed and in many various other ways." }, { "code": null, "e": 1934, "s": 1912, "text": "Below is the example:" }, { "code": "# Program in Ruby for a count of total Grocery itemsclass Grocery # class variable@@total_count = 0 # class array@@items_list = [] def add_item(item) # adding item to the array @@items_list.push(item) @@total_count += 1#countingend def print_items puts \"Total number of items --> #@@total_count\"; puts \"All items --> #@@items_list\";end# direct accessdef Grocery.printitems_only# or self.printitems_only puts \"\\nGrocery.printitems_only\", @@items_list.join(\"\\n\");endend list = Grocery.new() list.add_item(\"shampoo\")list.add_item(\"face wash\")list.add_item(\"serum\")list.add_item(\"mud pack\")list.add_item(\"tea tree oil\")list.add_item(\"toner\") list.print_items # direct accessGrocery.printitems_only # throws an errorlist.printitems_only", "e": 2695, "s": 1934, "text": null }, { "code": null, "e": 2702, "s": 2695, "text": "Output" }, { "code": null, "e": 2995, "s": 2702, "text": "Total number of items --> 6\nAll items --> [\"shampoo\", \"face wash\", \"serum\", \"mud pack\", \"tea tree oil\", \"toner\"]\n\nGrocery.printitems_only\nshampoo\nface wash\nserum\nmud pack\ntea tree oil\ntoner\nmain.rb:35:in `': undefined method `printitems_only' for # (NoMethodError)\nDid you mean? print_items\n" }, { "code": null, "e": 3738, "s": 2995, "text": "Here we are using the @@total_count class variable, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@total_count class variable and increment its value by 1. And, we are using the @@items_list class array, inside of our #add_item(item) method, which is an instance method. when a new item is added, the method accesses the @@items_list class array and adds the item name to the array. We can access the class variables anywhere in the class in both class and instance methods. And if we use either self.printitems_only or Grocery.printitems_only they execute the same but while accessing we can only access by class name as self represents the class only inside the class." }, { "code": null, "e": 3745, "s": 3738, "text": "Picked" }, { "code": null, "e": 3756, "s": 3745, "text": "Ruby class" }, { "code": null, "e": 3769, "s": 3756, "text": "Ruby-Methods" }, { "code": null, "e": 3774, "s": 3769, "text": "Ruby" }, { "code": null, "e": 3872, "s": 3774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3918, "s": 3872, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 3945, "s": 3918, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 3969, "s": 3945, "text": "Global Variable in Ruby" }, { "code": null, "e": 4012, "s": 3969, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 4043, "s": 4012, "text": "Ruby | Array select() function" }, { "code": null, "e": 4065, "s": 4043, "text": "Ruby | Case Statement" }, { "code": null, "e": 4095, "s": 4065, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 4139, "s": 4095, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 4157, "s": 4139, "text": "Ruby | Data Types" } ]
ML | Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression
01 Feb, 2022 Dataset : It is given by Kaggle from UCI Machine Learning Repository, in one of its challenge https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. Logistic Regression is used to predict whether the given patient is having Malignant or Benign tumor based on the attributes in the given dataset. Code : Loading Libraries Python3 # performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as plt Code : Loading dataset Python3 data = pd.read_csv("..\\breast-cancer-wisconsin-data\\data.csv") print (data.head) Output : Code : Loading dataset Python3 data.info() Output : RangeIndex: 569 entries, 0 to 568 Data columns (total 33 columns): id 569 non-null int64 diagnosis 569 non-null object radius_mean 569 non-null float64 texture_mean 569 non-null float64 perimeter_mean 569 non-null float64 area_mean 569 non-null float64 smoothness_mean 569 non-null float64 compactness_mean 569 non-null float64 concavity_mean 569 non-null float64 concave points_mean 569 non-null float64 symmetry_mean 569 non-null float64 fractal_dimension_mean 569 non-null float64 radius_se 569 non-null float64 texture_se 569 non-null float64 perimeter_se 569 non-null float64 area_se 569 non-null float64 smoothness_se 569 non-null float64 compactness_se 569 non-null float64 concavity_se 569 non-null float64 concave points_se 569 non-null float64 symmetry_se 569 non-null float64 fractal_dimension_se 569 non-null float64 radius_worst 569 non-null float64 texture_worst 569 non-null float64 perimeter_worst 569 non-null float64 area_worst 569 non-null float64 smoothness_worst 569 non-null float64 compactness_worst 569 non-null float64 concavity_worst 569 non-null float64 concave points_worst 569 non-null float64 symmetry_worst 569 non-null float64 fractal_dimension_worst 569 non-null float64 Unnamed: 32 0 non-null float64 dtypes: float64(31), int64(1), object(1) memory usage: 146.8+ KB Code: We are dropping columns – ‘id’ and ‘Unnamed: 32’ as they have no role in prediction Python3 data.drop(['Unnamed: 32', 'id'], axis = 1)data.diagnosis = [1 if each == "M" else 0 for each in data.diagnosis] Code : Input and Output data Python3 y = data.diagnosis.valuesx_data = data.drop(['diagnosis'], axis = 1) Code : Normalisation Python3 x = (x_data - np.min(x_data))/(np.max(x_data) - np.min(x_data)).values Code : Splitting data for training and testing. Python3 from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.15, random_state = 42) x_train = x_train.Tx_test = x_test.Ty_train = y_train.Ty_test = y_test.T print("x train: ", x_train.shape)print("x test: ", x_test.shape)print("y train: ", y_train.shape)print("y test: ", y_test.shape) Code : Weight and bias Python3 def initialize_weights_and_bias(dimension): w = np.full((dimension, 1), 0.01) b = 0.0 return w, b Code : Sigmoid Function – calculating z value. Python3 # z = np.dot(w.T, x_train)+bdef sigmoid(z): y_head = 1/(1 + np.exp(-z)) return y_head Code : Forward-Backward Propagation Python3 def forward_backward_propagation(w, b, x_train, y_train): z = np.dot(w.T, x_train) + b y_head = sigmoid(z) loss = - y_train * np.log(y_head) - (1 - y_train) * np.log(1 - y_head) # x_train.shape[1] is for scaling cost = (np.sum(loss)) / x_train.shape[1] # backward propagation derivative_weight = (np.dot(x_train, ( (y_head - y_train).T))) / x_train.shape[1] derivative_bias = np.sum( y_head-y_train) / x_train.shape[1] gradients = {"derivative_weight": derivative_weight, "derivative_bias": derivative_bias} return cost, gradients Code : Updating Parameters Python3 def update(w, b, x_train, y_train, learning_rate, number_of_iterarion): cost_list = [] cost_list2 = [] index = [] # updating(learning) parameters is number_of_iterarion times for i in range(number_of_iterarion): # make forward and backward propagation and find cost and gradients cost, gradients = forward_backward_propagation(w, b, x_train, y_train) cost_list.append(cost) # lets update w = w - learning_rate * gradients["derivative_weight"] b = b - learning_rate * gradients["derivative_bias"] if i % 10 == 0: cost_list2.append(cost) index.append(i) print ("Cost after iteration % i: % f" %(i, cost)) # update(learn) parameters weights and bias parameters = {"weight": w, "bias": b} plt.plot(index, cost_list2) plt.xticks(index, rotation ='vertical') plt.xlabel("Number of Iterarion") plt.ylabel("Cost") plt.show() return parameters, gradients, cost_list Code : Predictions Python3 def predict(w, b, x_test): # x_test is a input for forward propagation z = sigmoid(np.dot(w.T, x_test)+b) Y_prediction = np.zeros((1, x_test.shape[1])) # if z is bigger than 0.5, our prediction is sign one (y_head = 1), # if z is smaller than 0.5, our prediction is sign zero (y_head = 0), for i in range(z.shape[1]): if z[0, i]<= 0.5: Y_prediction[0, i] = 0 else: Y_prediction[0, i] = 1 return Y_prediction Code : Logistic Regression Python3 def logistic_regression(x_train, y_train, x_test, y_test, learning_rate, num_iterations): dimension = x_train.shape[0] w, b = initialize_weights_and_bias(dimension) parameters, gradients, cost_list = update( w, b, x_train, y_train, learning_rate, num_iterations) y_prediction_test = predict( parameters["weight"], parameters["bias"], x_test) y_prediction_train = predict( parameters["weight"], parameters["bias"], x_train) # train / test Errors print("train accuracy: {} %".format( 100 - np.mean(np.abs(y_prediction_train - y_train)) * 100)) print("test accuracy: {} %".format( 100 - np.mean(np.abs(y_prediction_test - y_test)) * 100)) logistic_regression(x_train, y_train, x_test, y_test, learning_rate = 1, num_iterations = 100) Output : Cost after iteration 0: 0.692836 Cost after iteration 10: 0.498576 Cost after iteration 20: 0.404996 Cost after iteration 30: 0.350059 Cost after iteration 40: 0.313747 Cost after iteration 50: 0.287767 Cost after iteration 60: 0.268114 Cost after iteration 70: 0.252627 Cost after iteration 80: 0.240036 Cost after iteration 90: 0.229543 Cost after iteration 100: 0.220624 Cost after iteration 110: 0.212920 Cost after iteration 120: 0.206175 Cost after iteration 130: 0.200201 Cost after iteration 140: 0.194860 Output : train accuracy: 95.23809523809524 % test accuracy: 94.18604651162791 % Code : Checking results with linear_model.LogisticRegression Python3 from sklearn import linear_modellogreg = linear_model.LogisticRegression(random_state = 42, max_iter = 150)print("test accuracy: {} ".format( logreg.fit(x_train.T, y_train.T).score(x_test.T, y_test.T)))print("train accuracy: {} ".format( logreg.fit(x_train.T, y_train.T).score(x_train.T, y_train.T))) Output : test accuracy: 0.9651162790697675 train accuracy: 0.9668737060041408 23620uday2021 avtarkumar719 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Supervised and Unsupervised learning Search Algorithms in AI Decision Tree Introduction with example Introduction to Recurrent Neural Network Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Feb, 2022" }, { "code": null, "e": 454, "s": 52, "text": "Dataset : It is given by Kaggle from UCI Machine Learning Repository, in one of its challenge https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. Logistic Regression is used to predict whether the given patient is having Malignant or Benign tumor based on the attributes in the given dataset. Code : Loading Libraries " }, { "code": null, "e": 462, "s": 454, "text": "Python3" }, { "code": "# performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as plt", "e": 592, "s": 462, "text": null }, { "code": null, "e": 617, "s": 592, "text": "Code : Loading dataset " }, { "code": null, "e": 625, "s": 617, "text": "Python3" }, { "code": "data = pd.read_csv(\"..\\\\breast-cancer-wisconsin-data\\\\data.csv\") print (data.head)", "e": 708, "s": 625, "text": null }, { "code": null, "e": 719, "s": 708, "text": "Output : " }, { "code": null, "e": 744, "s": 719, "text": "Code : Loading dataset " }, { "code": null, "e": 752, "s": 744, "text": "Python3" }, { "code": "data.info()", "e": 764, "s": 752, "text": null }, { "code": null, "e": 775, "s": 764, "text": "Output : " }, { "code": null, "e": 2486, "s": 775, "text": "RangeIndex: 569 entries, 0 to 568\nData columns (total 33 columns):\nid 569 non-null int64\ndiagnosis 569 non-null object\nradius_mean 569 non-null float64\ntexture_mean 569 non-null float64\nperimeter_mean 569 non-null float64\narea_mean 569 non-null float64\nsmoothness_mean 569 non-null float64\ncompactness_mean 569 non-null float64\nconcavity_mean 569 non-null float64\nconcave points_mean 569 non-null float64\nsymmetry_mean 569 non-null float64\nfractal_dimension_mean 569 non-null float64\nradius_se 569 non-null float64\ntexture_se 569 non-null float64\nperimeter_se 569 non-null float64\narea_se 569 non-null float64\nsmoothness_se 569 non-null float64\ncompactness_se 569 non-null float64\nconcavity_se 569 non-null float64\nconcave points_se 569 non-null float64\nsymmetry_se 569 non-null float64\nfractal_dimension_se 569 non-null float64\nradius_worst 569 non-null float64\ntexture_worst 569 non-null float64\nperimeter_worst 569 non-null float64\narea_worst 569 non-null float64\nsmoothness_worst 569 non-null float64\ncompactness_worst 569 non-null float64\nconcavity_worst 569 non-null float64\nconcave points_worst 569 non-null float64\nsymmetry_worst 569 non-null float64\nfractal_dimension_worst 569 non-null float64\nUnnamed: 32 0 non-null float64\ndtypes: float64(31), int64(1), object(1)\nmemory usage: 146.8+ KB" }, { "code": null, "e": 2578, "s": 2486, "text": "Code: We are dropping columns – ‘id’ and ‘Unnamed: 32’ as they have no role in prediction " }, { "code": null, "e": 2586, "s": 2578, "text": "Python3" }, { "code": "data.drop(['Unnamed: 32', 'id'], axis = 1)data.diagnosis = [1 if each == \"M\" else 0 for each in data.diagnosis]", "e": 2698, "s": 2586, "text": null }, { "code": null, "e": 2729, "s": 2698, "text": "Code : Input and Output data " }, { "code": null, "e": 2737, "s": 2729, "text": "Python3" }, { "code": "y = data.diagnosis.valuesx_data = data.drop(['diagnosis'], axis = 1)", "e": 2806, "s": 2737, "text": null }, { "code": null, "e": 2829, "s": 2806, "text": "Code : Normalisation " }, { "code": null, "e": 2837, "s": 2829, "text": "Python3" }, { "code": "x = (x_data - np.min(x_data))/(np.max(x_data) - np.min(x_data)).values", "e": 2908, "s": 2837, "text": null }, { "code": null, "e": 2958, "s": 2908, "text": "Code : Splitting data for training and testing. " }, { "code": null, "e": 2966, "s": 2958, "text": "Python3" }, { "code": "from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.15, random_state = 42) x_train = x_train.Tx_test = x_test.Ty_train = y_train.Ty_test = y_test.T print(\"x train: \", x_train.shape)print(\"x test: \", x_test.shape)print(\"y train: \", y_train.shape)print(\"y test: \", y_test.shape)", "e": 3319, "s": 2966, "text": null }, { "code": null, "e": 3344, "s": 3319, "text": "Code : Weight and bias " }, { "code": null, "e": 3352, "s": 3344, "text": "Python3" }, { "code": "def initialize_weights_and_bias(dimension): w = np.full((dimension, 1), 0.01) b = 0.0 return w, b", "e": 3459, "s": 3352, "text": null }, { "code": null, "e": 3508, "s": 3459, "text": "Code : Sigmoid Function – calculating z value. " }, { "code": null, "e": 3516, "s": 3508, "text": "Python3" }, { "code": "# z = np.dot(w.T, x_train)+bdef sigmoid(z): y_head = 1/(1 + np.exp(-z)) return y_head", "e": 3608, "s": 3516, "text": null }, { "code": null, "e": 3646, "s": 3608, "text": "Code : Forward-Backward Propagation " }, { "code": null, "e": 3654, "s": 3646, "text": "Python3" }, { "code": "def forward_backward_propagation(w, b, x_train, y_train): z = np.dot(w.T, x_train) + b y_head = sigmoid(z) loss = - y_train * np.log(y_head) - (1 - y_train) * np.log(1 - y_head) # x_train.shape[1] is for scaling cost = (np.sum(loss)) / x_train.shape[1] # backward propagation derivative_weight = (np.dot(x_train, ( (y_head - y_train).T))) / x_train.shape[1] derivative_bias = np.sum( y_head-y_train) / x_train.shape[1] gradients = {\"derivative_weight\": derivative_weight, \"derivative_bias\": derivative_bias} return cost, gradients", "e": 4268, "s": 3654, "text": null }, { "code": null, "e": 4297, "s": 4268, "text": "Code : Updating Parameters " }, { "code": null, "e": 4305, "s": 4297, "text": "Python3" }, { "code": "def update(w, b, x_train, y_train, learning_rate, number_of_iterarion): cost_list = [] cost_list2 = [] index = [] # updating(learning) parameters is number_of_iterarion times for i in range(number_of_iterarion): # make forward and backward propagation and find cost and gradients cost, gradients = forward_backward_propagation(w, b, x_train, y_train) cost_list.append(cost) # lets update w = w - learning_rate * gradients[\"derivative_weight\"] b = b - learning_rate * gradients[\"derivative_bias\"] if i % 10 == 0: cost_list2.append(cost) index.append(i) print (\"Cost after iteration % i: % f\" %(i, cost)) # update(learn) parameters weights and bias parameters = {\"weight\": w, \"bias\": b} plt.plot(index, cost_list2) plt.xticks(index, rotation ='vertical') plt.xlabel(\"Number of Iterarion\") plt.ylabel(\"Cost\") plt.show() return parameters, gradients, cost_list", "e": 5286, "s": 4305, "text": null }, { "code": null, "e": 5307, "s": 5286, "text": "Code : Predictions " }, { "code": null, "e": 5315, "s": 5307, "text": "Python3" }, { "code": "def predict(w, b, x_test): # x_test is a input for forward propagation z = sigmoid(np.dot(w.T, x_test)+b) Y_prediction = np.zeros((1, x_test.shape[1])) # if z is bigger than 0.5, our prediction is sign one (y_head = 1), # if z is smaller than 0.5, our prediction is sign zero (y_head = 0), for i in range(z.shape[1]): if z[0, i]<= 0.5: Y_prediction[0, i] = 0 else: Y_prediction[0, i] = 1 return Y_prediction", "e": 5782, "s": 5315, "text": null }, { "code": null, "e": 5811, "s": 5782, "text": "Code : Logistic Regression " }, { "code": null, "e": 5819, "s": 5811, "text": "Python3" }, { "code": "def logistic_regression(x_train, y_train, x_test, y_test, learning_rate, num_iterations): dimension = x_train.shape[0] w, b = initialize_weights_and_bias(dimension) parameters, gradients, cost_list = update( w, b, x_train, y_train, learning_rate, num_iterations) y_prediction_test = predict( parameters[\"weight\"], parameters[\"bias\"], x_test) y_prediction_train = predict( parameters[\"weight\"], parameters[\"bias\"], x_train) # train / test Errors print(\"train accuracy: {} %\".format( 100 - np.mean(np.abs(y_prediction_train - y_train)) * 100)) print(\"test accuracy: {} %\".format( 100 - np.mean(np.abs(y_prediction_test - y_test)) * 100)) logistic_regression(x_train, y_train, x_test, y_test, learning_rate = 1, num_iterations = 100)", "e": 6668, "s": 5819, "text": null }, { "code": null, "e": 6679, "s": 6668, "text": "Output : " }, { "code": null, "e": 7193, "s": 6679, "text": "Cost after iteration 0: 0.692836\nCost after iteration 10: 0.498576\nCost after iteration 20: 0.404996\nCost after iteration 30: 0.350059\nCost after iteration 40: 0.313747\nCost after iteration 50: 0.287767\nCost after iteration 60: 0.268114\nCost after iteration 70: 0.252627\nCost after iteration 80: 0.240036\nCost after iteration 90: 0.229543\nCost after iteration 100: 0.220624\nCost after iteration 110: 0.212920\nCost after iteration 120: 0.206175\nCost after iteration 130: 0.200201\nCost after iteration 140: 0.194860" }, { "code": null, "e": 7206, "s": 7195, "text": "Output : " }, { "code": null, "e": 7277, "s": 7206, "text": "train accuracy: 95.23809523809524 %\ntest accuracy: 94.18604651162791 %" }, { "code": null, "e": 7340, "s": 7277, "text": "Code : Checking results with linear_model.LogisticRegression " }, { "code": null, "e": 7348, "s": 7340, "text": "Python3" }, { "code": "from sklearn import linear_modellogreg = linear_model.LogisticRegression(random_state = 42, max_iter = 150)print(\"test accuracy: {} \".format( logreg.fit(x_train.T, y_train.T).score(x_test.T, y_test.T)))print(\"train accuracy: {} \".format( logreg.fit(x_train.T, y_train.T).score(x_train.T, y_train.T)))", "e": 7655, "s": 7348, "text": null }, { "code": null, "e": 7666, "s": 7655, "text": "Output : " }, { "code": null, "e": 7737, "s": 7666, "text": "test accuracy: 0.9651162790697675 \ntrain accuracy: 0.9668737060041408 " }, { "code": null, "e": 7753, "s": 7739, "text": "23620uday2021" }, { "code": null, "e": 7767, "s": 7753, "text": "avtarkumar719" }, { "code": null, "e": 7784, "s": 7767, "text": "Machine Learning" }, { "code": null, "e": 7791, "s": 7784, "text": "Python" }, { "code": null, "e": 7808, "s": 7791, "text": "Machine Learning" }, { "code": null, "e": 7906, "s": 7808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7929, "s": 7906, "text": "Reinforcement learning" }, { "code": null, "e": 7966, "s": 7929, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 7990, "s": 7966, "text": "Search Algorithms in AI" }, { "code": null, "e": 8030, "s": 7990, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 8071, "s": 8030, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 8099, "s": 8071, "text": "Read JSON file using Python" }, { "code": null, "e": 8149, "s": 8099, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 8171, "s": 8149, "text": "Python map() function" }, { "code": null, "e": 8189, "s": 8171, "text": "Python Dictionary" } ]
HTML full form
30 Jun, 2022 HTML stands for Hypertext Markup Language. It is a standard markup language used to design the documents displayed in the browsers as a web page. This language can become more interactive and attractive by using CSS ( Cascading Style Sheet) and JS (JavaScript) within it. The HTML word defines some specific meaning within it. Hypertext comes from the Hyperlink which means connections between several pages, Markup means the defined elements will be the page layout and elements within the page. The language combines both the feature and makes it Hypertext Markup Language. Initially, the HTML was released in the year of 1993 and developed by Tim Berners-Lee in 1990. Currently, the Web Hypertext Application Technology Working Group (WHATWG) community working on the development of the HTML. The current HTML5 version has gained so much popularity because of its newly added features in it. All the website’s skeleton is made of HTML and each browser performs on that and makes that visible and user-friendly to the user. HTML version release year: HTML Structure: The structure of HTML document are given below: HTML <!DOCTYPE html><html><head> <title> <!-- title bar --> </title> <!-- header for the website --></head><body> <!-- body section of the website --></body></html> Characteristics of HTML: Easy to understand: It is the most straightforward language you can say, very easy to grasp this language and easy to develop. Flexibility: This language is so much flexible that you can create whatever you want, a flexible way to design web pages along with the text. Linkable: You can make linkable text like users can connect from one page to another page or website through these characteristics. Limitless features: You can add videos, GIFs, pictures, or sound anything you want that will make the website more attractive and understandable. Support: You can use this language to display the documents on any platform like Windows, Linux, or Mac. Not a Programming Language: HTML is not a programming language as it is only concerned with presenting the information on the web. It is not used to program any logic but to give structure and semantically meaning to our website. Though we can link JavaScript code to it which is a programming language. Language Support: HTML can support various other languages like JavaScript, Ruby, PHP, Perl, and many more. You can also able to run embed python during the runtime. Advantages of HTML: HTML is easy to learn, easy to apply and it’s totally free you will just need a text editor and a browser. HTML is supported by all the browsers and it is the most friendly search engine. HTML can easily integrate with other languages and is easy to develop. It is the basic of all programming languages and the lightest language ever. In HTML, the display changes frequently depending on the window size or the device size making it comfortable to read by the user. Disadvantages of HTML: HTML can be used to create only static Web-page, it can not create dynamic web-page. There is a lack of security in HTML. Creating a simple Web-page required so many tags. HTML language is not centralised i.e. all the web pages that are connected, you have to design them separately else need to use CSS. HTML becomes complex when you try to create a huge website. harsh464565 sanayush1357 HTML-Basics HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 324, "s": 52, "text": "HTML stands for Hypertext Markup Language. It is a standard markup language used to design the documents displayed in the browsers as a web page. This language can become more interactive and attractive by using CSS ( Cascading Style Sheet) and JS (JavaScript) within it." }, { "code": null, "e": 629, "s": 324, "text": "The HTML word defines some specific meaning within it. Hypertext comes from the Hyperlink which means connections between several pages, Markup means the defined elements will be the page layout and elements within the page. The language combines both the feature and makes it Hypertext Markup Language. " }, { "code": null, "e": 1080, "s": 629, "text": "Initially, the HTML was released in the year of 1993 and developed by Tim Berners-Lee in 1990. Currently, the Web Hypertext Application Technology Working Group (WHATWG) community working on the development of the HTML. The current HTML5 version has gained so much popularity because of its newly added features in it. All the website’s skeleton is made of HTML and each browser performs on that and makes that visible and user-friendly to the user. " }, { "code": null, "e": 1107, "s": 1080, "text": "HTML version release year:" }, { "code": null, "e": 1172, "s": 1107, "text": "HTML Structure: The structure of HTML document are given below: " }, { "code": null, "e": 1177, "s": 1172, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> <!-- title bar --> </title> <!-- header for the website --></head><body> <!-- body section of the website --></body></html>", "e": 1356, "s": 1177, "text": null }, { "code": null, "e": 1381, "s": 1356, "text": "Characteristics of HTML:" }, { "code": null, "e": 1508, "s": 1381, "text": "Easy to understand: It is the most straightforward language you can say, very easy to grasp this language and easy to develop." }, { "code": null, "e": 1650, "s": 1508, "text": "Flexibility: This language is so much flexible that you can create whatever you want, a flexible way to design web pages along with the text." }, { "code": null, "e": 1782, "s": 1650, "text": "Linkable: You can make linkable text like users can connect from one page to another page or website through these characteristics." }, { "code": null, "e": 1928, "s": 1782, "text": "Limitless features: You can add videos, GIFs, pictures, or sound anything you want that will make the website more attractive and understandable." }, { "code": null, "e": 2033, "s": 1928, "text": "Support: You can use this language to display the documents on any platform like Windows, Linux, or Mac." }, { "code": null, "e": 2337, "s": 2033, "text": "Not a Programming Language: HTML is not a programming language as it is only concerned with presenting the information on the web. It is not used to program any logic but to give structure and semantically meaning to our website. Though we can link JavaScript code to it which is a programming language." }, { "code": null, "e": 2505, "s": 2337, "text": "Language Support: HTML can support various other languages like JavaScript, Ruby, PHP, Perl, and many more. You can also able to run embed python during the runtime. " }, { "code": null, "e": 2525, "s": 2505, "text": "Advantages of HTML:" }, { "code": null, "e": 2632, "s": 2525, "text": "HTML is easy to learn, easy to apply and it’s totally free you will just need a text editor and a browser." }, { "code": null, "e": 2713, "s": 2632, "text": "HTML is supported by all the browsers and it is the most friendly search engine." }, { "code": null, "e": 2784, "s": 2713, "text": "HTML can easily integrate with other languages and is easy to develop." }, { "code": null, "e": 2861, "s": 2784, "text": "It is the basic of all programming languages and the lightest language ever." }, { "code": null, "e": 2992, "s": 2861, "text": "In HTML, the display changes frequently depending on the window size or the device size making it comfortable to read by the user." }, { "code": null, "e": 3015, "s": 2992, "text": "Disadvantages of HTML:" }, { "code": null, "e": 3100, "s": 3015, "text": "HTML can be used to create only static Web-page, it can not create dynamic web-page." }, { "code": null, "e": 3137, "s": 3100, "text": "There is a lack of security in HTML." }, { "code": null, "e": 3187, "s": 3137, "text": "Creating a simple Web-page required so many tags." }, { "code": null, "e": 3320, "s": 3187, "text": "HTML language is not centralised i.e. all the web pages that are connected, you have to design them separately else need to use CSS." }, { "code": null, "e": 3380, "s": 3320, "text": "HTML becomes complex when you try to create a huge website." }, { "code": null, "e": 3392, "s": 3380, "text": "harsh464565" }, { "code": null, "e": 3405, "s": 3392, "text": "sanayush1357" }, { "code": null, "e": 3417, "s": 3405, "text": "HTML-Basics" }, { "code": null, "e": 3422, "s": 3417, "text": "HTML" }, { "code": null, "e": 3439, "s": 3422, "text": "Web Technologies" }, { "code": null, "e": 3466, "s": 3439, "text": "Web technologies Questions" }, { "code": null, "e": 3471, "s": 3466, "text": "HTML" }, { "code": null, "e": 3569, "s": 3471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3617, "s": 3569, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3679, "s": 3617, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3729, "s": 3679, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3753, "s": 3729, "text": "REST API (Introduction)" }, { "code": null, "e": 3806, "s": 3753, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3839, "s": 3806, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3901, "s": 3839, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3962, "s": 3901, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4012, "s": 3962, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to add Input Slider in React.js ?
28 Dec, 2021 In this article, we are going to learn how we can add input sider in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach: To add our slider input we are going to use the react-input-slider package. The react-input-slider package helps us to integrate the slider input in our app. So first, we will install the react-input-slider package and then we will add a slider input on our homepage. Create ReactJs Application: You can create a new ReactJs project using the below command: npx create-react-app gfg Install the required package: Now we will install the react-input-slider package using the below command: npm i react-input-slider Project Structure: It will look like this. Adding the Slider Input: After installing the package we can easily add a slider input on any page in our app. For this example, we are going to add a slider input to our homepage. Add the below content in the App.js file: Javascript import React, { useState } from 'react';import Slider from 'react-input-slider'; export default function GfgInput() { const [state, setState] = useState({ x: 15, y: 15 }); return ( <div> <h2>GeeksforGeeks ReactJs - Slider Input</h2> <div> ({state.x}, {state.y}) <Slider axis="xy" x={state.x} y={state.y} onChange={setState} /> <Slider axis="x" x={state.x} onChange={({ x }) => setState(state => ({ ...state, x }))} /> <Slider axis="y" y={state.y} onChange= {({ y }) => setState(state => ({ ...state, y }))} /> </div> </div> );} Explanation: In the above example first, we are importing the Slider component and useState hook from react. Then we are using the useState hook to store the value of the input. After that, we are adding our slider input using the installed package. Steps to run the application: Run the below command in the terminal to run the app. npm start React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Dec, 2021" }, { "code": null, "e": 299, "s": 28, "text": "In this article, we are going to learn how we can add input sider in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies." }, { "code": null, "e": 577, "s": 299, "text": "Approach: To add our slider input we are going to use the react-input-slider package. The react-input-slider package helps us to integrate the slider input in our app. So first, we will install the react-input-slider package and then we will add a slider input on our homepage." }, { "code": null, "e": 667, "s": 577, "text": "Create ReactJs Application: You can create a new ReactJs project using the below command:" }, { "code": null, "e": 692, "s": 667, "text": "npx create-react-app gfg" }, { "code": null, "e": 798, "s": 692, "text": "Install the required package: Now we will install the react-input-slider package using the below command:" }, { "code": null, "e": 823, "s": 798, "text": "npm i react-input-slider" }, { "code": null, "e": 866, "s": 823, "text": "Project Structure: It will look like this." }, { "code": null, "e": 1047, "s": 866, "text": "Adding the Slider Input: After installing the package we can easily add a slider input on any page in our app. For this example, we are going to add a slider input to our homepage." }, { "code": null, "e": 1089, "s": 1047, "text": "Add the below content in the App.js file:" }, { "code": null, "e": 1100, "s": 1089, "text": "Javascript" }, { "code": "import React, { useState } from 'react';import Slider from 'react-input-slider'; export default function GfgInput() { const [state, setState] = useState({ x: 15, y: 15 }); return ( <div> <h2>GeeksforGeeks ReactJs - Slider Input</h2> <div> ({state.x}, {state.y}) <Slider axis=\"xy\" x={state.x} y={state.y} onChange={setState} /> <Slider axis=\"x\" x={state.x} onChange={({ x }) => setState(state => ({ ...state, x }))} /> <Slider axis=\"y\" y={state.y} onChange= {({ y }) => setState(state => ({ ...state, y }))} /> </div> </div> );}", "e": 1726, "s": 1100, "text": null }, { "code": null, "e": 1976, "s": 1726, "text": "Explanation: In the above example first, we are importing the Slider component and useState hook from react. Then we are using the useState hook to store the value of the input. After that, we are adding our slider input using the installed package." }, { "code": null, "e": 2060, "s": 1976, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 2070, "s": 2060, "text": "npm start" }, { "code": null, "e": 2086, "s": 2070, "text": "React-Questions" }, { "code": null, "e": 2097, "s": 2086, "text": "JavaScript" }, { "code": null, "e": 2105, "s": 2097, "text": "ReactJS" }, { "code": null, "e": 2122, "s": 2105, "text": "Web Technologies" } ]
Program for Deadlock free condition in Operating System
30 Sep, 2021 Given: A system has R identical resources, P processes competing for them and N is the maximum need of each process. The task is to find the minimum number of Resources required So that deadlock will never occur. Formula: R >= P * (N - 1) + 1 Examples: Input : P = 3, N = 4 Output : R >= 10 Input : P = 7, N = 2 Output : R >= 8 Approach: Consider, 3 process A, B and C. Let, Need of each process is 4 Therefore, The maximum resources require will be 3 * 4 = 12 i.e, Give 4 resources to each Process. And, The minimum resources required will be 3 * (4 – 1) + 1 = 10. i.e, Give 3 Resources to each of the Process, and we are left out with 1 Resource. That 1 resource will be given to any of the Process A, B or C. So that after using that resource by any one of the Process, It left the resources and that resources will be used by any other Process and thus Deadlock will Never Occur. C++ Java Python3 C# // C++ implementation of above program.#include <bits/stdc++.h>using namespace std; // function that calculates// the minimum no. of resourcesint Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver codeint main(){ int process = 3, need = 4; cout << "R >= " << Resources(process, need); return 0;} // Java implementation of above program class GFG{ // function that calculates// the minimum no. of resourcesstatic int Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver Codepublic static void main(String args[]){ int process = 3, need = 4; System.out.print("R >= "); System.out.print(Resources(process, need));}} # Python 3 implementation of# above program # function that calculates# the minimum no. of resourcesdef Resources(process, need): minResources = 0 # Condition so that deadlock # will not occur minResources = process * (need - 1) + 1 return minResources # Driver Codeif __name__ == "__main__" : process, need = 3, 4 print("R >=", Resources(process, need)) # This Code is Contributed# by Naman_Garg // C# implementation of above programusing System; class GFG{ // function that calculates// the minimum no. of resourcesstatic int Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver Codepublic static void Main(){ int process = 3, need = 4; Console.Write("R >= "); Console.Write(Resources(process, need));}} // This code is contributed// by Sanjit_Prasad Output: R >= 10 Naman_Garg Sanjit_Prasad ankita_saini simmytarika5 Operating Systems-Deadlock C++ Programs Computer Subject Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? C++ Program for QuickSort C Program to Swap two Numbers SDE SHEET - A Complete Guide for SDE Preparation What is Algorithm | Introduction to Algorithms Software Engineering | Coupling and Cohesion Type Checking in Compiler Design Difference between NP hard and NP complete problem
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2021" }, { "code": null, "e": 266, "s": 52, "text": "Given: A system has R identical resources, P processes competing for them and N is the maximum need of each process. The task is to find the minimum number of Resources required So that deadlock will never occur. " }, { "code": null, "e": 276, "s": 266, "text": "Formula: " }, { "code": null, "e": 298, "s": 276, "text": "R >= P * (N - 1) + 1 " }, { "code": null, "e": 310, "s": 298, "text": "Examples: " }, { "code": null, "e": 387, "s": 310, "text": "Input : P = 3, N = 4\nOutput : R >= 10\n\nInput : P = 7, N = 2\nOutput : R >= 8 " }, { "code": null, "e": 398, "s": 387, "text": "Approach: " }, { "code": null, "e": 945, "s": 398, "text": "Consider, 3 process A, B and C. Let, Need of each process is 4 Therefore, The maximum resources require will be 3 * 4 = 12 i.e, Give 4 resources to each Process. And, The minimum resources required will be 3 * (4 – 1) + 1 = 10. i.e, Give 3 Resources to each of the Process, and we are left out with 1 Resource. That 1 resource will be given to any of the Process A, B or C. So that after using that resource by any one of the Process, It left the resources and that resources will be used by any other Process and thus Deadlock will Never Occur. " }, { "code": null, "e": 949, "s": 945, "text": "C++" }, { "code": null, "e": 954, "s": 949, "text": "Java" }, { "code": null, "e": 962, "s": 954, "text": "Python3" }, { "code": null, "e": 965, "s": 962, "text": "C#" }, { "code": "// C++ implementation of above program.#include <bits/stdc++.h>using namespace std; // function that calculates// the minimum no. of resourcesint Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver codeint main(){ int process = 3, need = 4; cout << \"R >= \" << Resources(process, need); return 0;}", "e": 1414, "s": 965, "text": null }, { "code": "// Java implementation of above program class GFG{ // function that calculates// the minimum no. of resourcesstatic int Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver Codepublic static void main(String args[]){ int process = 3, need = 4; System.out.print(\"R >= \"); System.out.print(Resources(process, need));}}", "e": 1886, "s": 1414, "text": null }, { "code": "# Python 3 implementation of# above program # function that calculates# the minimum no. of resourcesdef Resources(process, need): minResources = 0 # Condition so that deadlock # will not occur minResources = process * (need - 1) + 1 return minResources # Driver Codeif __name__ == \"__main__\" : process, need = 3, 4 print(\"R >=\", Resources(process, need)) # This Code is Contributed# by Naman_Garg", "e": 2310, "s": 1886, "text": null }, { "code": "// C# implementation of above programusing System; class GFG{ // function that calculates// the minimum no. of resourcesstatic int Resources(int process, int need){ int minResources = 0; // Condition so that deadlock // will not occur minResources = process * (need - 1) + 1; return minResources;} // Driver Codepublic static void Main(){ int process = 3, need = 4; Console.Write(\"R >= \"); Console.Write(Resources(process, need));}} // This code is contributed// by Sanjit_Prasad", "e": 2821, "s": 2310, "text": null }, { "code": null, "e": 2830, "s": 2821, "text": "Output: " }, { "code": null, "e": 2838, "s": 2830, "text": "R >= 10" }, { "code": null, "e": 2851, "s": 2840, "text": "Naman_Garg" }, { "code": null, "e": 2865, "s": 2851, "text": "Sanjit_Prasad" }, { "code": null, "e": 2878, "s": 2865, "text": "ankita_saini" }, { "code": null, "e": 2891, "s": 2878, "text": "simmytarika5" }, { "code": null, "e": 2918, "s": 2891, "text": "Operating Systems-Deadlock" }, { "code": null, "e": 2931, "s": 2918, "text": "C++ Programs" }, { "code": null, "e": 2948, "s": 2931, "text": "Computer Subject" }, { "code": null, "e": 2966, "s": 2948, "text": "Operating Systems" }, { "code": null, "e": 2984, "s": 2966, "text": "Operating Systems" }, { "code": null, "e": 3082, "s": 2984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3116, "s": 3082, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 3176, "s": 3116, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 3250, "s": 3176, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 3276, "s": 3250, "text": "C++ Program for QuickSort" }, { "code": null, "e": 3306, "s": 3276, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 3355, "s": 3306, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 3402, "s": 3355, "text": "What is Algorithm | Introduction to Algorithms" }, { "code": null, "e": 3447, "s": 3402, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 3480, "s": 3447, "text": "Type Checking in Compiler Design" } ]
Sum of consecutive two elements in a array
18 Aug, 2021 Given an array print sum of the pairwise consecutive elements. Examples: Input : 8, 5, 4, 3, 15, 20 Output : 13, 9, 7, 18, 35 Input : 5, 10, 15, 20 Output : 15, 25, 35 The solution is to traverse the array and saving the sum of consecutive numbers in the variable sum. C++ Java Python3 C# PHP Javascript // C++ program to print the// sum of the consecutive elements.#include <stdio.h>#include <stdlib.h> // Function to print pairwise sumvoid pairwiseSum(int arr[], int n){ int sum = 0; for (int i = 0; i < n - 1; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; printf(" %d ", sum); }} // Driver function to test functionint main(){ int arr[] = {4, 10, 15, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); pairwiseSum(arr, n); return 0;} // Java program to print the// sum of the consecutive elements. class Arraysum { // Function to print Alternatesum static void pairwiseSum(int arr[], int n) { int sum = 0; for (int i = 0; i + 1 < n; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; System.out.print(sum + " "); } } /*driver function to test function*/ public static void main(String[] args) { int arr[] = {4, 10, 15, 5, 6}; int n = arr.length; pairwiseSum(arr, n); }} # Python3 program to print the# sum of the consecutive elements. # Function to print alternate sumdef pairwiseSum(lst, n): sum = 0; for i in range(len(lst)-1): # adding the alternate numbers sum = lst[i] + lst[i + 1] print (sum, end = " ") # driver function to test functionarr =[4, 10, 15, 5, 6]size = len(arr)pairwiseSum(arr, size) // C# program to print the// sum of the consecutive elements.using System; class Arraysum { // Function to print Alternatesum static void pairwiseSum(int []arr, int n) { int sum = 0; for (int i = 0; i + 1 < n; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; Console.Write(sum + " "); } } // Driver function public static void Main() { int []arr = {4, 10, 15, 5, 6}; int n = arr.Length; pairwiseSum(arr, n); }} // This code is contributed by vt_m. <?php// PHP program to print the// sum of the consecutive elements. // Function to print pairwise sumfunction pairwiseSum($arr, $n){ $sum = 0; for ($i = 0; $i < $n - 1; $i++) { // adding the alternate numbers $sum = $arr[$i] + $arr[$i + 1]; echo $sum," "; }} // Driver Code $arr = array (4, 10, 15, 5, 6); $n = sizeof($arr) ; pairwiseSum($arr, $n); // This code is contributed by ajit?> <script> // Javascript program to print the// sum of the consecutive elements. // Function to print Alternatesumfunction pairwiseSum(arr, n){ let sum = 0; for(let i = 0; i + 1 < n; i++) { // Adding the alternate numbers sum = arr[i] + arr[i + 1]; document.write(sum + " "); }} // Driver codelet arr = [ 4, 10, 15, 5, 6 ];let n = arr.length; pairwiseSum(arr, n); // This code is contributed by divyesh072019 </script> Output: 14 25 20 11 jit_t divyesh072019 adnanirshad158 Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Aug, 2021" }, { "code": null, "e": 116, "s": 53, "text": "Given an array print sum of the pairwise consecutive elements." }, { "code": null, "e": 127, "s": 116, "text": "Examples: " }, { "code": null, "e": 226, "s": 127, "text": "Input : 8, 5, 4, 3, 15, 20\nOutput : 13, 9, 7, 18, 35\n\nInput : 5, 10, 15, 20\nOutput : 15, 25, 35 " }, { "code": null, "e": 329, "s": 226, "text": "The solution is to traverse the array and saving the sum of consecutive numbers in the variable sum. " }, { "code": null, "e": 333, "s": 329, "text": "C++" }, { "code": null, "e": 338, "s": 333, "text": "Java" }, { "code": null, "e": 346, "s": 338, "text": "Python3" }, { "code": null, "e": 349, "s": 346, "text": "C#" }, { "code": null, "e": 353, "s": 349, "text": "PHP" }, { "code": null, "e": 364, "s": 353, "text": "Javascript" }, { "code": "// C++ program to print the// sum of the consecutive elements.#include <stdio.h>#include <stdlib.h> // Function to print pairwise sumvoid pairwiseSum(int arr[], int n){ int sum = 0; for (int i = 0; i < n - 1; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; printf(\" %d \", sum); }} // Driver function to test functionint main(){ int arr[] = {4, 10, 15, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); pairwiseSum(arr, n); return 0;}", "e": 863, "s": 364, "text": null }, { "code": "// Java program to print the// sum of the consecutive elements. class Arraysum { // Function to print Alternatesum static void pairwiseSum(int arr[], int n) { int sum = 0; for (int i = 0; i + 1 < n; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; System.out.print(sum + \" \"); } } /*driver function to test function*/ public static void main(String[] args) { int arr[] = {4, 10, 15, 5, 6}; int n = arr.length; pairwiseSum(arr, n); }}", "e": 1435, "s": 863, "text": null }, { "code": "# Python3 program to print the# sum of the consecutive elements. # Function to print alternate sumdef pairwiseSum(lst, n): sum = 0; for i in range(len(lst)-1): # adding the alternate numbers sum = lst[i] + lst[i + 1] print (sum, end = \" \") # driver function to test functionarr =[4, 10, 15, 5, 6]size = len(arr)pairwiseSum(arr, size)", "e": 1809, "s": 1435, "text": null }, { "code": "// C# program to print the// sum of the consecutive elements.using System; class Arraysum { // Function to print Alternatesum static void pairwiseSum(int []arr, int n) { int sum = 0; for (int i = 0; i + 1 < n; i++) { // adding the alternate numbers sum = arr[i] + arr[i + 1]; Console.Write(sum + \" \"); } } // Driver function public static void Main() { int []arr = {4, 10, 15, 5, 6}; int n = arr.Length; pairwiseSum(arr, n); }} // This code is contributed by vt_m.", "e": 2395, "s": 1809, "text": null }, { "code": "<?php// PHP program to print the// sum of the consecutive elements. // Function to print pairwise sumfunction pairwiseSum($arr, $n){ $sum = 0; for ($i = 0; $i < $n - 1; $i++) { // adding the alternate numbers $sum = $arr[$i] + $arr[$i + 1]; echo $sum,\" \"; }} // Driver Code $arr = array (4, 10, 15, 5, 6); $n = sizeof($arr) ; pairwiseSum($arr, $n); // This code is contributed by ajit?>", "e": 2841, "s": 2395, "text": null }, { "code": "<script> // Javascript program to print the// sum of the consecutive elements. // Function to print Alternatesumfunction pairwiseSum(arr, n){ let sum = 0; for(let i = 0; i + 1 < n; i++) { // Adding the alternate numbers sum = arr[i] + arr[i + 1]; document.write(sum + \" \"); }} // Driver codelet arr = [ 4, 10, 15, 5, 6 ];let n = arr.length; pairwiseSum(arr, n); // This code is contributed by divyesh072019 </script>", "e": 3300, "s": 2841, "text": null }, { "code": null, "e": 3309, "s": 3300, "text": "Output: " }, { "code": null, "e": 3321, "s": 3309, "text": "14 25 20 11" }, { "code": null, "e": 3329, "s": 3323, "text": "jit_t" }, { "code": null, "e": 3343, "s": 3329, "text": "divyesh072019" }, { "code": null, "e": 3358, "s": 3343, "text": "adnanirshad158" }, { "code": null, "e": 3365, "s": 3358, "text": "Arrays" }, { "code": null, "e": 3384, "s": 3365, "text": "School Programming" }, { "code": null, "e": 3391, "s": 3384, "text": "Arrays" } ]
How to Make Entire Custom Checkbox/Div Clickable ?
29 Jun, 2021 It is always a good option to use custom checkboxes in your websites instead of old-school HTML checkboxes. This article provides a step-by-step implementation for the same. Approach: Use the input type checkbox and link a label with it in HTML. Hide the input checkbox and style the label as per your requirement. Change the styling as the checkbox state changes. HTML code: HTML <!DOCTYPE html><html> <head> <style> label { display:block; border:solid 2px green; width: 200px; height:40px; margin-top:10px; color:green; text-align:center; line-height: 40px; } <!-- hide input --> input[type=checkbox] { display: none; } <!-- Add ✓ on checked before label --> input:checked + label:before { content: "✓ "; } <!--Add styling on check --> input:checked + label { border: solid 2px purple; color: purple; } </style> </head> <body> <input id="apple" type="checkbox" name="apple" /> <label for="apple">Apple</label> </body></html> Output: Result Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 CSS-Basics CSS-Properties Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a webpage for online food delivery system using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2021" }, { "code": null, "e": 136, "s": 28, "text": "It is always a good option to use custom checkboxes in your websites instead of old-school HTML checkboxes." }, { "code": null, "e": 202, "s": 136, "text": "This article provides a step-by-step implementation for the same." }, { "code": null, "e": 213, "s": 202, "text": "Approach: " }, { "code": null, "e": 275, "s": 213, "text": "Use the input type checkbox and link a label with it in HTML." }, { "code": null, "e": 344, "s": 275, "text": "Hide the input checkbox and style the label as per your requirement." }, { "code": null, "e": 394, "s": 344, "text": "Change the styling as the checkbox state changes." }, { "code": null, "e": 405, "s": 394, "text": "HTML code:" }, { "code": null, "e": 410, "s": 405, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> label { display:block; border:solid 2px green; width: 200px; height:40px; margin-top:10px; color:green; text-align:center; line-height: 40px; } <!-- hide input --> input[type=checkbox] { display: none; } <!-- Add ✓ on checked before label --> input:checked + label:before { content: \"✓ \"; } <!--Add styling on check --> input:checked + label { border: solid 2px purple; color: purple; } </style> </head> <body> <input id=\"apple\" type=\"checkbox\" name=\"apple\" /> <label for=\"apple\">Apple</label> </body></html>", "e": 1173, "s": 410, "text": null }, { "code": null, "e": 1182, "s": 1173, "text": "Output: " }, { "code": null, "e": 1189, "s": 1182, "text": "Result" }, { "code": null, "e": 1209, "s": 1189, "text": "Supported Browser: " }, { "code": null, "e": 1223, "s": 1209, "text": "Google Chrome" }, { "code": null, "e": 1241, "s": 1223, "text": "Internet Explorer" }, { "code": null, "e": 1249, "s": 1241, "text": "Firefox" }, { "code": null, "e": 1255, "s": 1249, "text": "Opera" }, { "code": null, "e": 1262, "s": 1255, "text": "Safari" }, { "code": null, "e": 1274, "s": 1262, "text": "ysachin2314" }, { "code": null, "e": 1285, "s": 1274, "text": "CSS-Basics" }, { "code": null, "e": 1300, "s": 1285, "text": "CSS-Properties" }, { "code": null, "e": 1307, "s": 1300, "text": "Picked" }, { "code": null, "e": 1311, "s": 1307, "text": "CSS" }, { "code": null, "e": 1316, "s": 1311, "text": "HTML" }, { "code": null, "e": 1333, "s": 1316, "text": "Web Technologies" }, { "code": null, "e": 1338, "s": 1333, "text": "HTML" }, { "code": null, "e": 1436, "s": 1338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1475, "s": 1436, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1514, "s": 1475, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1553, "s": 1514, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1621, "s": 1553, "text": "Design a webpage for online food delivery system using HTML and CSS" }, { "code": null, "e": 1650, "s": 1621, "text": "Form validation using jQuery" }, { "code": null, "e": 1674, "s": 1650, "text": "REST API (Introduction)" }, { "code": null, "e": 1727, "s": 1674, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1787, "s": 1727, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1848, "s": 1787, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python | Perform append at beginning of list
30 Nov, 2018 The usual append operation of Python list adds the new element at the end of the list. But in certain situations, we need to append each element we add in front of list. If we perform brute force techniques, we need to perform unnecessary shifts of elements and hence, having shorthands for it is useful. Let’s discuss certain ways to perform append at beginning of the list. Method #1 : Using insert() This method generally inserts the element at any position in the list and also performs the necessary shifts required internally and hence can also be used to perform this very task. # Python3 code to demonstrate # to add element at beginning# using insert() # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print ("Original list : " + str(test_list)) # using insert() to append# at beginning. append 6test_list.insert(0, 6) # printing resultant list print ("Resultant list is : " + str(test_list)) Original list : [1, 3, 4, 5, 7] Resultant list is : [6, 1, 3, 4, 5, 7] Method #2 : Using [] and + These both operators can be combined to perform this task. We convert the element to list and then perform the list addition. # Python3 code to demonstrate # to add element at beginning# using [] and + # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print ("Original list : " + str(test_list)) # using [] and + to append# at beginning append 6test_list = [6] + test_list # printing resultant list print ("Resultant list is : " + str(test_list)) Original list : [1, 3, 4, 5, 7] Resultant list is : [6, 1, 3, 4, 5, 7] Method #3 : Using Slicing Slicing of list is also another method to perform this particular task. we just assign to the 0 sliced list to the list converted from the element. This does the trick and is quite elegant. # Python3 code to demonstrate # to add element at beginning# using slicing # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print ("Original list : " + str(test_list)) # using slicing to append # at beginning. append 6test_list[:0] = [6] # printing resultant list print ("Resultant list is : " + str(test_list)) Original list : [1, 3, 4, 5, 7] Resultant list is : [6, 1, 3, 4, 5, 7] Method #4 : Using collections.deque.appendleft() The list can be converted to deque and then the appendleft() can be used to perform the push like operation from the front of the doubly ended queue. # Python3 code to demonstrate # to add element at beginning# using collections.deque.pushleft()from collections import deque # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print ("Original list : " + str(test_list)) # using collections.deque.pushleft()# to append at beginning# append 6test_list = deque(test_list)test_list.appendleft(6)test_list = list(test_list) # printing resultant list print ("Resultant list is : " + str(test_list)) Original list : [1, 3, 4, 5, 7] Resultant list is : [6, 1, 3, 4, 5, 7] Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Nov, 2018" }, { "code": null, "e": 357, "s": 52, "text": "The usual append operation of Python list adds the new element at the end of the list. But in certain situations, we need to append each element we add in front of list. If we perform brute force techniques, we need to perform unnecessary shifts of elements and hence, having shorthands for it is useful." }, { "code": null, "e": 428, "s": 357, "text": "Let’s discuss certain ways to perform append at beginning of the list." }, { "code": null, "e": 455, "s": 428, "text": "Method #1 : Using insert()" }, { "code": null, "e": 638, "s": 455, "text": "This method generally inserts the element at any position in the list and also performs the necessary shifts required internally and hence can also be used to perform this very task." }, { "code": "# Python3 code to demonstrate # to add element at beginning# using insert() # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using insert() to append# at beginning. append 6test_list.insert(0, 6) # printing resultant list print (\"Resultant list is : \" + str(test_list))", "e": 990, "s": 638, "text": null }, { "code": null, "e": 1062, "s": 990, "text": "Original list : [1, 3, 4, 5, 7]\nResultant list is : [6, 1, 3, 4, 5, 7]\n" }, { "code": null, "e": 1090, "s": 1062, "text": " Method #2 : Using [] and +" }, { "code": null, "e": 1216, "s": 1090, "text": "These both operators can be combined to perform this task. We convert the element to list and then perform the list addition." }, { "code": "# Python3 code to demonstrate # to add element at beginning# using [] and + # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using [] and + to append# at beginning append 6test_list = [6] + test_list # printing resultant list print (\"Resultant list is : \" + str(test_list))", "e": 1572, "s": 1216, "text": null }, { "code": null, "e": 1644, "s": 1572, "text": "Original list : [1, 3, 4, 5, 7]\nResultant list is : [6, 1, 3, 4, 5, 7]\n" }, { "code": null, "e": 1671, "s": 1644, "text": " Method #3 : Using Slicing" }, { "code": null, "e": 1861, "s": 1671, "text": "Slicing of list is also another method to perform this particular task. we just assign to the 0 sliced list to the list converted from the element. This does the trick and is quite elegant." }, { "code": "# Python3 code to demonstrate # to add element at beginning# using slicing # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using slicing to append # at beginning. append 6test_list[:0] = [6] # printing resultant list print (\"Resultant list is : \" + str(test_list))", "e": 2210, "s": 1861, "text": null }, { "code": null, "e": 2282, "s": 2210, "text": "Original list : [1, 3, 4, 5, 7]\nResultant list is : [6, 1, 3, 4, 5, 7]\n" }, { "code": null, "e": 2332, "s": 2282, "text": " Method #4 : Using collections.deque.appendleft()" }, { "code": null, "e": 2482, "s": 2332, "text": "The list can be converted to deque and then the appendleft() can be used to perform the push like operation from the front of the doubly ended queue." }, { "code": "# Python3 code to demonstrate # to add element at beginning# using collections.deque.pushleft()from collections import deque # initializing list test_list = [1, 3, 4, 5, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using collections.deque.pushleft()# to append at beginning# append 6test_list = deque(test_list)test_list.appendleft(6)test_list = list(test_list) # printing resultant list print (\"Resultant list is : \" + str(test_list))", "e": 2959, "s": 2482, "text": null }, { "code": null, "e": 3031, "s": 2959, "text": "Original list : [1, 3, 4, 5, 7]\nResultant list is : [6, 1, 3, 4, 5, 7]\n" }, { "code": null, "e": 3052, "s": 3031, "text": "Python list-programs" }, { "code": null, "e": 3064, "s": 3052, "text": "python-list" }, { "code": null, "e": 3071, "s": 3064, "text": "Python" }, { "code": null, "e": 3083, "s": 3071, "text": "python-list" }, { "code": null, "e": 3181, "s": 3083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3199, "s": 3181, "text": "Python Dictionary" }, { "code": null, "e": 3241, "s": 3199, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3276, "s": 3241, "text": "Read a file line by line in Python" }, { "code": null, "e": 3302, "s": 3276, "text": "Python String | replace()" }, { "code": null, "e": 3334, "s": 3302, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3363, "s": 3334, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3390, "s": 3363, "text": "Python Classes and Objects" }, { "code": null, "e": 3411, "s": 3390, "text": "Python OOPs Concepts" }, { "code": null, "e": 3434, "s": 3411, "text": "Introduction To PYTHON" } ]
How to remove indentation from an unordered list item using CSS?
22 Apr, 2019 While designing web pages we used to add some list of items sometimes they are numbered (in various style) and sometimes they are bulleted (in various style). It might happen when we are trying to design a navigation bar or any kind list in which items are neither numbered nor bulleted we don’t need numbers or bullets and also no margin. To remove that indentation from an unordered list (a list having bullets) there needs styling to be done using CSS. The style will be implemented only on the list. So the selector would be ul. Syntax: ul { // CSS Property } Example: This example creates a page with a list with zero(0) indent . <!DOCTYPE html><html> <head> <title> Remove indentation from an unordered list of items </title> <!-- CSS style to remove indentation from list of items --> <style> ul { list-style:none; padding-left:0; } </style></head> <body> <h3>Computer science subjects:</h3> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>Operating System</li> <li>Computer Network</li> <li>DBMS</li> <li>Web Technology</li> </ul></body> </html> Output: In the above example, padding-left property is used to set the indentation from left. The padding-left:0 is used to remove indentation (space) from left. The list-style: none property is used to remove list-style property from the list of items. CSS-Misc Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2019" }, { "code": null, "e": 561, "s": 28, "text": "While designing web pages we used to add some list of items sometimes they are numbered (in various style) and sometimes they are bulleted (in various style). It might happen when we are trying to design a navigation bar or any kind list in which items are neither numbered nor bulleted we don’t need numbers or bullets and also no margin. To remove that indentation from an unordered list (a list having bullets) there needs styling to be done using CSS. The style will be implemented only on the list. So the selector would be ul." }, { "code": null, "e": 569, "s": 561, "text": "Syntax:" }, { "code": null, "e": 596, "s": 569, "text": "ul {\n // CSS Property\n}" }, { "code": null, "e": 667, "s": 596, "text": "Example: This example creates a page with a list with zero(0) indent ." }, { "code": "<!DOCTYPE html><html> <head> <title> Remove indentation from an unordered list of items </title> <!-- CSS style to remove indentation from list of items --> <style> ul { list-style:none; padding-left:0; } </style></head> <body> <h3>Computer science subjects:</h3> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>Operating System</li> <li>Computer Network</li> <li>DBMS</li> <li>Web Technology</li> </ul></body> </html> ", "e": 1240, "s": 667, "text": null }, { "code": null, "e": 1248, "s": 1240, "text": "Output:" }, { "code": null, "e": 1494, "s": 1248, "text": "In the above example, padding-left property is used to set the indentation from left. The padding-left:0 is used to remove indentation (space) from left. The list-style: none property is used to remove list-style property from the list of items." }, { "code": null, "e": 1503, "s": 1494, "text": "CSS-Misc" }, { "code": null, "e": 1510, "s": 1503, "text": "Picked" }, { "code": null, "e": 1514, "s": 1510, "text": "CSS" }, { "code": null, "e": 1531, "s": 1514, "text": "Web Technologies" }, { "code": null, "e": 1558, "s": 1531, "text": "Web technologies Questions" }, { "code": null, "e": 1656, "s": 1558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1693, "s": 1656, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1732, "s": 1693, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1771, "s": 1732, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1835, "s": 1771, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 1896, "s": 1835, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1929, "s": 1896, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1990, "s": 1929, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2033, "s": 1990, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2105, "s": 2033, "text": "Differences between Functional Components and Class Components in React" } ]
Perl | Useful Array functions
04 Aug, 2021 In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Array in Perl provides various inbuilt functions to perform operations like adding and removing elements from a pre-defined array.Example: Perl #!/usr/bin/perl # Initializing the array@x = ('Java', 'C', 'C++'); # Print the Initial arrayprint "Original array: @x \n"; # Using push() function# Pushing multiple values in the arraypush(@x, 'Python', 'Perl');print("Pushing new values...\n"); # Printing the arrayprint "Updated array: @x\n"; # Using pop() functionprint("\nPopping the last element...\n"); # Prints the value returned by popprint "Value returned by pop: ", pop(@x); # Prints the array after pop operationprint "\nUpdated array: @x"; Original array: Java C C++ Pushing new values... Updated array: Java C C++ Python Perl Popping the last element... Value returned by pop: Perl Updated array: Java C C++ Python Some useful array functions are listed below: gabaa406 Perl-Array-Functions Perl-Arrays Perl-function Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays Perl Tutorial - Learn Perl With Examples Perl | Boolean Values Perl | length() Function Perl | Subroutines or Functions Use of print() and say() in Perl Hello World Program in Perl Perl | ne operator Perl | Basic Syntax of a Perl Program Perl | eq operator
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2021" }, { "code": null, "e": 410, "s": 28, "text": "In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Array in Perl provides various inbuilt functions to perform operations like adding and removing elements from a pre-defined array.Example: " }, { "code": null, "e": 415, "s": 410, "text": "Perl" }, { "code": "#!/usr/bin/perl # Initializing the array@x = ('Java', 'C', 'C++'); # Print the Initial arrayprint \"Original array: @x \\n\"; # Using push() function# Pushing multiple values in the arraypush(@x, 'Python', 'Perl');print(\"Pushing new values...\\n\"); # Printing the arrayprint \"Updated array: @x\\n\"; # Using pop() functionprint(\"\\nPopping the last element...\\n\"); # Prints the value returned by popprint \"Value returned by pop: \", pop(@x); # Prints the array after pop operationprint \"\\nUpdated array: @x\";", "e": 924, "s": 415, "text": null }, { "code": null, "e": 1102, "s": 924, "text": "Original array: Java C C++ \nPushing new values...\nUpdated array: Java C C++ Python Perl\n\nPopping the last element...\nValue returned by pop: Perl\nUpdated array: Java C C++ Python" }, { "code": null, "e": 1151, "s": 1104, "text": " Some useful array functions are listed below:" }, { "code": null, "e": 1164, "s": 1155, "text": "gabaa406" }, { "code": null, "e": 1185, "s": 1164, "text": "Perl-Array-Functions" }, { "code": null, "e": 1197, "s": 1185, "text": "Perl-Arrays" }, { "code": null, "e": 1211, "s": 1197, "text": "Perl-function" }, { "code": null, "e": 1216, "s": 1211, "text": "Perl" }, { "code": null, "e": 1221, "s": 1216, "text": "Perl" }, { "code": null, "e": 1319, "s": 1221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1333, "s": 1319, "text": "Perl | Arrays" }, { "code": null, "e": 1374, "s": 1333, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 1396, "s": 1374, "text": "Perl | Boolean Values" }, { "code": null, "e": 1421, "s": 1396, "text": "Perl | length() Function" }, { "code": null, "e": 1453, "s": 1421, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 1486, "s": 1453, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 1514, "s": 1486, "text": "Hello World Program in Perl" }, { "code": null, "e": 1533, "s": 1514, "text": "Perl | ne operator" }, { "code": null, "e": 1571, "s": 1533, "text": "Perl | Basic Syntax of a Perl Program" } ]
Program for Fahrenheit to Kelvin conversion
24 May, 2022 Given a Temperature in Fahrenheit scale, our task is to convert it into Kelvin scale.Examples : Input : F = 100 Output : K = 311.278 Input : F = 110 Output : K = 316.833 The temperature conversion from Fahrenheit ( F ) to Kelvin ( K ) is given by the formula : K = 273.5 + ((F - 32.0) * (5.0/9.0)) C++ Java Python C# PHP Javascript // CPP program to convert temperature from// Fahrenheit to Kelvin#include<iostream>using namespace std ; // Function to convert temperature from degree// Fahrenheit to Kelvinfloat Fahrenheit_to_Kelvin( float F ){ return 273.5 + ((F - 32.0) * (5.0/9.0));} // Driver functionint main(){ float F = 100; cout << "Temperature in Kelvin ( K ) = " << Fahrenheit_to_Kelvin( F ) ; return 0;} // Java program to convert temperature// from Fahrenheit to Kelvinclass GFG{ // Function to convert temperature // from degree Fahrenheit to Kelvinstatic float Fahrenheit_to_Kelvin( float F ){ return 273.5f + ((F - 32.0f) * (5.0f/9.0f));} // Driver codepublic static void main(String arg[]){ float F = 100; System.out.print("Temperature in Kelvin ( K ) = " + (Math.round(Fahrenheit_to_Kelvin( F ) *1000.0)/1000.0)) ;}}// This code is contributed by Anant Agarwal. # Python program to convert temperature from# Fahrenheit to Kelvin # Function to convert temperaturedef Fahrenheit_to_Kelvin(F): return 273.5 + ((F - 32.0) * (5.0/9.0)) # Driver functionF = 100print("Temperature in Kelvin ( K ) = {:.3f}" .format(Fahrenheit_to_Kelvin( F ))) // C# program to convert temperature// from Fahrenheit to Kelvinusing System; class GFG{ // Function to convert temperature// from degree Fahrenheit to Kelvinstatic float Fahrenheit_to_Kelvin( float F ){ return 273.5f + ((F - 32.0f) * (5.0f/9.0f));} // Driver codepublic static void Main(){ float F = 100; Console.WriteLine("Temperature in Kelvin (K) = " + (Math.Round(Fahrenheit_to_Kelvin(F) *1000.0)/1000.0)) ;}} // This code is contributed by vt_m. <?php// PHP program to convert temperature// from Fahrenheit to Kelvin // Function to convert temperature// from degree Fahrenheit to Kelvinfunction Fahrenheit_to_Kelvin( $F ){ return 273.5 + (($F - 32.0) * (5.0 / 9.0));} // Driver Code $F = 100; $x = number_format(Fahrenheit_to_Kelvin($F), 3); echo "Temperature in Kelvin ( K ) = ".$x; // This code is contributed by Sam007?> <script> // Javascript program to convert temperature from// Fahrenheit to Kelvin // Function to convert temperature from degree// Fahrenheit to Kelvinfunction Fahrenheit_to_Kelvin( F ){ return 273.5 + ((F - 32.0) * (5.0/9.0));} // Driver function let F = 100; document.write("Temperature in Kelvin ( K ) = " + Fahrenheit_to_Kelvin( F )) ; // This code is contributed Mayank Tyagi </script> Output : Temperature in Kelvin ( K ) = 311.278 Time Complexity: O(1), as we are not using any loops. Auxiliary Space: O(1), as we are not using any extra space. vt_m Sam007 mayanktyagi1709 rohitsingh07052 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 150, "s": 52, "text": "Given a Temperature in Fahrenheit scale, our task is to convert it into Kelvin scale.Examples : " }, { "code": null, "e": 225, "s": 150, "text": "Input : F = 100\nOutput : K = 311.278\n\nInput : F = 110\nOutput : K = 316.833" }, { "code": null, "e": 320, "s": 227, "text": "The temperature conversion from Fahrenheit ( F ) to Kelvin ( K ) is given by the formula : " }, { "code": null, "e": 357, "s": 320, "text": "K = 273.5 + ((F - 32.0) * (5.0/9.0))" }, { "code": null, "e": 363, "s": 359, "text": "C++" }, { "code": null, "e": 368, "s": 363, "text": "Java" }, { "code": null, "e": 375, "s": 368, "text": "Python" }, { "code": null, "e": 378, "s": 375, "text": "C#" }, { "code": null, "e": 382, "s": 378, "text": "PHP" }, { "code": null, "e": 393, "s": 382, "text": "Javascript" }, { "code": "// CPP program to convert temperature from// Fahrenheit to Kelvin#include<iostream>using namespace std ; // Function to convert temperature from degree// Fahrenheit to Kelvinfloat Fahrenheit_to_Kelvin( float F ){ return 273.5 + ((F - 32.0) * (5.0/9.0));} // Driver functionint main(){ float F = 100; cout << \"Temperature in Kelvin ( K ) = \" << Fahrenheit_to_Kelvin( F ) ; return 0;}", "e": 797, "s": 393, "text": null }, { "code": "// Java program to convert temperature// from Fahrenheit to Kelvinclass GFG{ // Function to convert temperature // from degree Fahrenheit to Kelvinstatic float Fahrenheit_to_Kelvin( float F ){ return 273.5f + ((F - 32.0f) * (5.0f/9.0f));} // Driver codepublic static void main(String arg[]){ float F = 100; System.out.print(\"Temperature in Kelvin ( K ) = \" + (Math.round(Fahrenheit_to_Kelvin( F ) *1000.0)/1000.0)) ;}}// This code is contributed by Anant Agarwal.", "e": 1328, "s": 797, "text": null }, { "code": "# Python program to convert temperature from# Fahrenheit to Kelvin # Function to convert temperaturedef Fahrenheit_to_Kelvin(F): return 273.5 + ((F - 32.0) * (5.0/9.0)) # Driver functionF = 100print(\"Temperature in Kelvin ( K ) = {:.3f}\" .format(Fahrenheit_to_Kelvin( F )))", "e": 1616, "s": 1328, "text": null }, { "code": "// C# program to convert temperature// from Fahrenheit to Kelvinusing System; class GFG{ // Function to convert temperature// from degree Fahrenheit to Kelvinstatic float Fahrenheit_to_Kelvin( float F ){ return 273.5f + ((F - 32.0f) * (5.0f/9.0f));} // Driver codepublic static void Main(){ float F = 100; Console.WriteLine(\"Temperature in Kelvin (K) = \" + (Math.Round(Fahrenheit_to_Kelvin(F) *1000.0)/1000.0)) ;}} // This code is contributed by vt_m.", "e": 2154, "s": 1616, "text": null }, { "code": "<?php// PHP program to convert temperature// from Fahrenheit to Kelvin // Function to convert temperature// from degree Fahrenheit to Kelvinfunction Fahrenheit_to_Kelvin( $F ){ return 273.5 + (($F - 32.0) * (5.0 / 9.0));} // Driver Code $F = 100; $x = number_format(Fahrenheit_to_Kelvin($F), 3); echo \"Temperature in Kelvin ( K ) = \".$x; // This code is contributed by Sam007?>", "e": 2572, "s": 2154, "text": null }, { "code": "<script> // Javascript program to convert temperature from// Fahrenheit to Kelvin // Function to convert temperature from degree// Fahrenheit to Kelvinfunction Fahrenheit_to_Kelvin( F ){ return 273.5 + ((F - 32.0) * (5.0/9.0));} // Driver function let F = 100; document.write(\"Temperature in Kelvin ( K ) = \" + Fahrenheit_to_Kelvin( F )) ; // This code is contributed Mayank Tyagi </script>", "e": 2980, "s": 2572, "text": null }, { "code": null, "e": 2990, "s": 2980, "text": "Output : " }, { "code": null, "e": 3028, "s": 2990, "text": "Temperature in Kelvin ( K ) = 311.278" }, { "code": null, "e": 3082, "s": 3028, "text": "Time Complexity: O(1), as we are not using any loops." }, { "code": null, "e": 3143, "s": 3082, "text": "Auxiliary Space: O(1), as we are not using any extra space. " }, { "code": null, "e": 3148, "s": 3143, "text": "vt_m" }, { "code": null, "e": 3155, "s": 3148, "text": "Sam007" }, { "code": null, "e": 3171, "s": 3155, "text": "mayanktyagi1709" }, { "code": null, "e": 3187, "s": 3171, "text": "rohitsingh07052" }, { "code": null, "e": 3206, "s": 3187, "text": "School Programming" } ]
Check if a string is Isogram or not
27 Jan, 2022 Given a word or phrase, check if it is isogram or not. An Isogram is a word in which no letter occurs more than once.Examples: Input : Machine Output : True "Machine" does not have any character repeating, it is an Isogram Input : Geek Output : False "Geek" has 'e' as repeating character, it is not an Isogram C++ Java Python3 C# Javascript // C++ program to check// if a given string is isogram or not#include <bits/stdc++.h>using namespace std; // Function to check// if a given string is isogram or notstring is_isogram(string str){ int len = str.length(); // Convert the string in lower case letters for (int i = 0; i < len; i++) str[i] = tolower(str[i]); sort(str.begin(), str.end()); for (int i = 0; i < len; i++) { if (str[i] == str[i + 1]) return "False"; } return "True";} // driver programint main(){ string str1 = "Machine"; cout << is_isogram(str1) << endl; string str2 = "isogram"; cout << is_isogram(str2) << endl; string str3 = "GeeksforGeeks"; cout << is_isogram(str3) << endl; string str4 = "Alphabet"; cout << is_isogram(str4) << endl; return 0;} // Contributed by nuclode // Java program to check// if a given string is isogram or notimport java.io.*;import java.util.*; class GFG { // Function to check // if a given string is isogram or not static boolean is_isogram(String str) { // Convert the string in lower case letters str = str.toLowerCase(); int len = str.length(); char arr[] = str.toCharArray(); Arrays.sort(arr); for (int i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } // driver program public static void main(String[] args) { String str1 = "Machine"; System.out.println(is_isogram(str1)); String str2 = "isogram"; System.out.println(is_isogram(str2)); String str3 = "GeeksforGeeks"; System.out.println(is_isogram(str3)); String str4 = "Alphabet"; System.out.println(is_isogram(str4)); }} // Contributed by Pramod Kumar # Python program to check# if a word is isogram or notdef is_isogram(word): # Convert the word or sentence in lower case letters. clean_word = word.lower() # Make an empty list to append unique letters letter_list = [] for letter in clean_word: # If letter is an alphabet then only check if letter.isalpha(): if letter in letter_list: return False letter_list.append(letter) return True if __name__ == '__main__': print(is_isogram("Machine")) print(is_isogram("isogram")) print(is_isogram("GeeksforGeeks")) print(is_isogram("Alphabet ")) // C# program to check if a given// string is isogram or notusing System; public class GFG { // Function to check if a given // string is isogram or not static bool is_isogram(string str) { // Convert the string in lower case letters str = str.ToLower(); int len = str.Length; char[] arr = str.ToCharArray(); Array.Sort(arr); for (int i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } // driver program public static void Main() { string str1 = "Machine"; Console.WriteLine(is_isogram(str1)); string str2 = "isogram"; Console.WriteLine(is_isogram(str2)); string str3 = "GeeksforGeeks"; Console.WriteLine(is_isogram(str3)); string str4 = "Alphabet"; Console.WriteLine(is_isogram(str4)); }} // This code is contributed by Sam007 <script> // Javascript program to check if a given // string is isogram or not // Function to check if a given // string is isogram or not function is_isogram(str) { // Convert the string in lower case letters str = str.toLowerCase(); let len = str.length; let arr = str.split(''); arr.sort(); for (let i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } let str1 = "Machine"; if(is_isogram(str1)) { document.write("True" + "</br>"); } else{ document.write("False" + "</br>"); } let str2 = "isogram"; if(is_isogram(str2)) { document.write("True" + "</br>"); } else{ document.write("False" + "</br>"); } let str3 = "GeeksforGeeks"; if(is_isogram(str3)) { document.write("True" + "</br>"); } else{ document.write("False" + "</br>"); } let str4 = "Alphabet"; if(is_isogram(str4)) { document.write("True" + "</br>"); } else{ document.write("False" + "</br>"); } // This code is contributed by suresh07.</script> Output: True True False False Another approach : In this, count of characters of string are stored in hashmap, and wherever it is found to be greater than 1 for any char, return false else return true. C++ Java Python3 C# Javascript // CPP code to check string is isogram or not#include <bits/stdc++.h> using namespace std; // function to check isogrambool check_isogram(string str){ int length = str.length(); int mapHash[26] = { 0 }; // loop to store count of chars and check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str[i] - 'a']++; // if count > 1, return false if (mapHash[str[i]-'a'] > 1) { return false; } } return true;} // Driver codeint main(){ string str = "geeks"; string str2 = "computer"; // checking str as isogram if (check_isogram(str)) { cout << "True" << endl; } else { cout << "False" << endl; } // checking str2 as isogram if (check_isogram(str2)) { cout << "True" << endl; } else { cout << "False" << endl; } return 0;} // Java code to check string is isogram or notclass GFG{ // function to check isogramstatic boolean check_isogram(String str){ int length = str.length(); int mapHash[] = new int[26]; // loop to store count of chars and // check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str.charAt(i) - 'a']++; // if count > 1, return false if (mapHash[str[i]-'a'] > 1) { return false; } } return true;} // Driver codepublic static void main(String[] args){ String str = "geeks"; String str2 = "computer"; // checking str as isogram if (check_isogram(str)) System.out.println("True"); else System.out.println("False"); // checking str2 as isogram if (check_isogram(str2)) System.out.println("True"); else System.out.println("False"); }} // This code contributed by Rajput-Ji # Python3 code to check string is isogram or not # function to check isogramdef check_isogram(string) : length = len(string); mapHash = [0] * 26; # loop to store count of chars # and check if it is greater than 1 for i in range(length) : mapHash[ord(string[i]) - ord('a')] += 1; # if count > 1, return false if (mapHash[ord(string[i]) - ord('a')] > 1) : return False; return True; # Driver codeif __name__ == "__main__" : string = "geeks"; string2 = "computer"; # checking str as isogram if (check_isogram(string)) : print("True"); else : print("False"); # checking str2 as isogram if (check_isogram(string2)) : print("True") else : print("False"); # This code is contributed by AnkitRai01 // C# code to check string is isogram or notusing System;public class GFG{ // function to check isogramstatic bool check_isogram(String str){ int length = str.Length; int []mapHash = new int[26]; // loop to store count of chars and // check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str[i] - 'a']++; // if count > 1, return false if (mapHash[str[i] - 'a'] > 1) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ String str = "geeks"; String str2 = "computer"; // checking str as isogram if (check_isogram(str)) Console.WriteLine("True"); else Console.WriteLine("False"); // checking str2 as isogram if (check_isogram(str2)) Console.WriteLine("True"); else Console.WriteLine("False"); }} // This code has been contributed by 29AjayKumar <script> // Javascript code to check string is isogram or not // function to check isogram function check_isogram(str) { let length = str.length; let mapHash = new Array(26); mapHash.fill(0); // loop to store count of chars and // check if it is greater than 1 for (let i = 0; i < length; i++) { mapHash[str[i].charCodeAt() - 'a'.charCodeAt()]++; // if count > 1, return false if (mapHash[str[i].charCodeAt() - 'a'.charCodeAt()] > 1) { return false; } } return true; } let str = "geeks"; let str2 = "computer"; // checking str as isogram if (check_isogram(str)) document.write("True" + "</br>"); else document.write("False" + "</br>"); // checking str2 as isogram if (check_isogram(str2)) document.write("True" + "</br>"); else document.write("False" + "</br>"); // This code is contributed by divyeshrabadiya07.</script> Output : False True // Thanks Sahil Bansal for suggesting the above method. Check if String is Isogram | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCheck if String is Isogram | Data Structures & Algorithms | Programming Tutorials | 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 / 10:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Y3T03b8cQ2k" 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 Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) 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. Sam007 Rajput-Ji 29AjayKumar letsrock ankthon divyeshrabadiya07 suresh07 gargr0109 amartyaghoshgfg Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Jan, 2022" }, { "code": null, "e": 182, "s": 53, "text": "Given a word or phrase, check if it is isogram or not. An Isogram is a word in which no letter occurs more than once.Examples: " }, { "code": null, "e": 369, "s": 182, "text": "Input : Machine\nOutput : True\n\"Machine\" does not have any character repeating, \nit is an Isogram\n\nInput : Geek\nOutput : False\n\"Geek\" has 'e' as repeating character, \nit is not an Isogram" }, { "code": null, "e": 377, "s": 373, "text": "C++" }, { "code": null, "e": 382, "s": 377, "text": "Java" }, { "code": null, "e": 390, "s": 382, "text": "Python3" }, { "code": null, "e": 393, "s": 390, "text": "C#" }, { "code": null, "e": 404, "s": 393, "text": "Javascript" }, { "code": "// C++ program to check// if a given string is isogram or not#include <bits/stdc++.h>using namespace std; // Function to check// if a given string is isogram or notstring is_isogram(string str){ int len = str.length(); // Convert the string in lower case letters for (int i = 0; i < len; i++) str[i] = tolower(str[i]); sort(str.begin(), str.end()); for (int i = 0; i < len; i++) { if (str[i] == str[i + 1]) return \"False\"; } return \"True\";} // driver programint main(){ string str1 = \"Machine\"; cout << is_isogram(str1) << endl; string str2 = \"isogram\"; cout << is_isogram(str2) << endl; string str3 = \"GeeksforGeeks\"; cout << is_isogram(str3) << endl; string str4 = \"Alphabet\"; cout << is_isogram(str4) << endl; return 0;} // Contributed by nuclode", "e": 1234, "s": 404, "text": null }, { "code": "// Java program to check// if a given string is isogram or notimport java.io.*;import java.util.*; class GFG { // Function to check // if a given string is isogram or not static boolean is_isogram(String str) { // Convert the string in lower case letters str = str.toLowerCase(); int len = str.length(); char arr[] = str.toCharArray(); Arrays.sort(arr); for (int i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } // driver program public static void main(String[] args) { String str1 = \"Machine\"; System.out.println(is_isogram(str1)); String str2 = \"isogram\"; System.out.println(is_isogram(str2)); String str3 = \"GeeksforGeeks\"; System.out.println(is_isogram(str3)); String str4 = \"Alphabet\"; System.out.println(is_isogram(str4)); }} // Contributed by Pramod Kumar", "e": 2204, "s": 1234, "text": null }, { "code": "# Python program to check# if a word is isogram or notdef is_isogram(word): # Convert the word or sentence in lower case letters. clean_word = word.lower() # Make an empty list to append unique letters letter_list = [] for letter in clean_word: # If letter is an alphabet then only check if letter.isalpha(): if letter in letter_list: return False letter_list.append(letter) return True if __name__ == '__main__': print(is_isogram(\"Machine\")) print(is_isogram(\"isogram\")) print(is_isogram(\"GeeksforGeeks\")) print(is_isogram(\"Alphabet \")) ", "e": 2938, "s": 2204, "text": null }, { "code": "// C# program to check if a given// string is isogram or notusing System; public class GFG { // Function to check if a given // string is isogram or not static bool is_isogram(string str) { // Convert the string in lower case letters str = str.ToLower(); int len = str.Length; char[] arr = str.ToCharArray(); Array.Sort(arr); for (int i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } // driver program public static void Main() { string str1 = \"Machine\"; Console.WriteLine(is_isogram(str1)); string str2 = \"isogram\"; Console.WriteLine(is_isogram(str2)); string str3 = \"GeeksforGeeks\"; Console.WriteLine(is_isogram(str3)); string str4 = \"Alphabet\"; Console.WriteLine(is_isogram(str4)); }} // This code is contributed by Sam007", "e": 3875, "s": 2938, "text": null }, { "code": "<script> // Javascript program to check if a given // string is isogram or not // Function to check if a given // string is isogram or not function is_isogram(str) { // Convert the string in lower case letters str = str.toLowerCase(); let len = str.length; let arr = str.split(''); arr.sort(); for (let i = 0; i < len - 1; i++) { if (arr[i] == arr[i + 1]) return false; } return true; } let str1 = \"Machine\"; if(is_isogram(str1)) { document.write(\"True\" + \"</br>\"); } else{ document.write(\"False\" + \"</br>\"); } let str2 = \"isogram\"; if(is_isogram(str2)) { document.write(\"True\" + \"</br>\"); } else{ document.write(\"False\" + \"</br>\"); } let str3 = \"GeeksforGeeks\"; if(is_isogram(str3)) { document.write(\"True\" + \"</br>\"); } else{ document.write(\"False\" + \"</br>\"); } let str4 = \"Alphabet\"; if(is_isogram(str4)) { document.write(\"True\" + \"</br>\"); } else{ document.write(\"False\" + \"</br>\"); } // This code is contributed by suresh07.</script>", "e": 5071, "s": 3875, "text": null }, { "code": null, "e": 5081, "s": 5071, "text": "Output: " }, { "code": null, "e": 5103, "s": 5081, "text": "True\nTrue\nFalse\nFalse" }, { "code": null, "e": 5277, "s": 5103, "text": "Another approach : In this, count of characters of string are stored in hashmap, and wherever it is found to be greater than 1 for any char, return false else return true. " }, { "code": null, "e": 5281, "s": 5277, "text": "C++" }, { "code": null, "e": 5286, "s": 5281, "text": "Java" }, { "code": null, "e": 5294, "s": 5286, "text": "Python3" }, { "code": null, "e": 5297, "s": 5294, "text": "C#" }, { "code": null, "e": 5308, "s": 5297, "text": "Javascript" }, { "code": "// CPP code to check string is isogram or not#include <bits/stdc++.h> using namespace std; // function to check isogrambool check_isogram(string str){ int length = str.length(); int mapHash[26] = { 0 }; // loop to store count of chars and check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str[i] - 'a']++; // if count > 1, return false if (mapHash[str[i]-'a'] > 1) { return false; } } return true;} // Driver codeint main(){ string str = \"geeks\"; string str2 = \"computer\"; // checking str as isogram if (check_isogram(str)) { cout << \"True\" << endl; } else { cout << \"False\" << endl; } // checking str2 as isogram if (check_isogram(str2)) { cout << \"True\" << endl; } else { cout << \"False\" << endl; } return 0;}", "e": 6184, "s": 5308, "text": null }, { "code": "// Java code to check string is isogram or notclass GFG{ // function to check isogramstatic boolean check_isogram(String str){ int length = str.length(); int mapHash[] = new int[26]; // loop to store count of chars and // check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str.charAt(i) - 'a']++; // if count > 1, return false if (mapHash[str[i]-'a'] > 1) { return false; } } return true;} // Driver codepublic static void main(String[] args){ String str = \"geeks\"; String str2 = \"computer\"; // checking str as isogram if (check_isogram(str)) System.out.println(\"True\"); else System.out.println(\"False\"); // checking str2 as isogram if (check_isogram(str2)) System.out.println(\"True\"); else System.out.println(\"False\"); }} // This code contributed by Rajput-Ji", "e": 7102, "s": 6184, "text": null }, { "code": "# Python3 code to check string is isogram or not # function to check isogramdef check_isogram(string) : length = len(string); mapHash = [0] * 26; # loop to store count of chars # and check if it is greater than 1 for i in range(length) : mapHash[ord(string[i]) - ord('a')] += 1; # if count > 1, return false if (mapHash[ord(string[i]) - ord('a')] > 1) : return False; return True; # Driver codeif __name__ == \"__main__\" : string = \"geeks\"; string2 = \"computer\"; # checking str as isogram if (check_isogram(string)) : print(\"True\"); else : print(\"False\"); # checking str2 as isogram if (check_isogram(string2)) : print(\"True\") else : print(\"False\"); # This code is contributed by AnkitRai01", "e": 7916, "s": 7102, "text": null }, { "code": "// C# code to check string is isogram or notusing System;public class GFG{ // function to check isogramstatic bool check_isogram(String str){ int length = str.Length; int []mapHash = new int[26]; // loop to store count of chars and // check if it is greater than 1 for (int i = 0; i < length; i++) { mapHash[str[i] - 'a']++; // if count > 1, return false if (mapHash[str[i] - 'a'] > 1) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ String str = \"geeks\"; String str2 = \"computer\"; // checking str as isogram if (check_isogram(str)) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\"); // checking str2 as isogram if (check_isogram(str2)) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\"); }} // This code has been contributed by 29AjayKumar", "e": 8857, "s": 7916, "text": null }, { "code": "<script> // Javascript code to check string is isogram or not // function to check isogram function check_isogram(str) { let length = str.length; let mapHash = new Array(26); mapHash.fill(0); // loop to store count of chars and // check if it is greater than 1 for (let i = 0; i < length; i++) { mapHash[str[i].charCodeAt() - 'a'.charCodeAt()]++; // if count > 1, return false if (mapHash[str[i].charCodeAt() - 'a'.charCodeAt()] > 1) { return false; } } return true; } let str = \"geeks\"; let str2 = \"computer\"; // checking str as isogram if (check_isogram(str)) document.write(\"True\" + \"</br>\"); else document.write(\"False\" + \"</br>\"); // checking str2 as isogram if (check_isogram(str2)) document.write(\"True\" + \"</br>\"); else document.write(\"False\" + \"</br>\"); // This code is contributed by divyeshrabadiya07.</script>", "e": 9911, "s": 8857, "text": null }, { "code": null, "e": 9922, "s": 9911, "text": "Output : " }, { "code": null, "e": 9933, "s": 9922, "text": "False\nTrue" }, { "code": null, "e": 9991, "s": 9933, "text": "// Thanks Sahil Bansal for suggesting the above method. " }, { "code": null, "e": 10972, "s": 9991, "text": "Check if String is Isogram | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCheck if String is Isogram | Data Structures & Algorithms | Programming Tutorials | 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 / 10:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Y3T03b8cQ2k\" 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": 11412, "s": 10972, "text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) 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": 11419, "s": 11412, "text": "Sam007" }, { "code": null, "e": 11429, "s": 11419, "text": "Rajput-Ji" }, { "code": null, "e": 11441, "s": 11429, "text": "29AjayKumar" }, { "code": null, "e": 11450, "s": 11441, "text": "letsrock" }, { "code": null, "e": 11458, "s": 11450, "text": "ankthon" }, { "code": null, "e": 11476, "s": 11458, "text": "divyeshrabadiya07" }, { "code": null, "e": 11485, "s": 11476, "text": "suresh07" }, { "code": null, "e": 11495, "s": 11485, "text": "gargr0109" }, { "code": null, "e": 11511, "s": 11495, "text": "amartyaghoshgfg" }, { "code": null, "e": 11516, "s": 11511, "text": "Hash" }, { "code": null, "e": 11524, "s": 11516, "text": "Strings" }, { "code": null, "e": 11529, "s": 11524, "text": "Hash" }, { "code": null, "e": 11537, "s": 11529, "text": "Strings" } ]
Compare two tables and return missing ids using MySQL LEFT OUTER JOIN
To compare two tables and return missing ids, you need to use MySQL LEFT OUTER JOIN. Let us create a table with sample fields and then we will insert records. The query to create the first table − mysql> create table First_Table -> ( -> Id int -> ); Query OK, 0 rows affected (0.88 sec) Now insert some records in the table using insert command. The query is as follows − mysql> insert into First_Table values(1); Query OK, 1 row affected (0.68 sec) mysql> insert into First_Table values(2); Query OK, 1 row affected (0.29 sec) mysql> insert into First_Table values(3); Query OK, 1 row affected (0.20 sec) mysql> insert into First_Table values(4); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from First_Table; The following is the output − +------+ | Id | +------+ | 1 | | 2 | | 3 | | 4 | +------+ 4 rows in set (0.00 sec) Here is the query to create the second table − mysql> create table Second_Table -> ( -> Id int -> ); Query OK, 0 rows affected (0.60 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into Second_Table values(2); Query OK, 1 row affected (0.19 sec) mysql> insert into Second_Table values(4); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from Second_Table; The following is the output − +------+ | Id | +------+ | 2 | | 4 | +------+ 2 rows in set (0.00 sec) The query is as follows to compare two tables and return missing IDs using LEFT OUTER JOIN − mysql> SELECT First_Table.Id FROM First_Table -> LEFT OUTER JOIN Second_Table ON First_Table.Id = Second_Table.Id -> WHERE Second_Table.Id IS NULL; The following is the output − +------+ | Id | +------+ | 1 | | 3 | +------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1147, "s": 1062, "text": "To compare two tables and return missing ids, you need to use MySQL LEFT OUTER JOIN." }, { "code": null, "e": 1259, "s": 1147, "text": "Let us create a table with sample fields and then we will insert records. The query to create the first table −" }, { "code": null, "e": 1358, "s": 1259, "text": "mysql> create table First_Table\n -> (\n -> Id int\n -> );\nQuery OK, 0 rows affected (0.88 sec)" }, { "code": null, "e": 1443, "s": 1358, "text": "Now insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1755, "s": 1443, "text": "mysql> insert into First_Table values(1);\nQuery OK, 1 row affected (0.68 sec)\nmysql> insert into First_Table values(2);\nQuery OK, 1 row affected (0.29 sec)\nmysql> insert into First_Table values(3);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into First_Table values(4);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1840, "s": 1755, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 1873, "s": 1840, "text": "mysql> select *from First_Table;" }, { "code": null, "e": 1903, "s": 1873, "text": "The following is the output −" }, { "code": null, "e": 2000, "s": 1903, "text": "+------+\n| Id |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2047, "s": 2000, "text": "Here is the query to create the second table −" }, { "code": null, "e": 2147, "s": 2047, "text": "mysql> create table Second_Table\n -> (\n -> Id int\n -> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 2240, "s": 2147, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2398, "s": 2240, "text": "mysql> insert into Second_Table values(2);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into Second_Table values(4);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2458, "s": 2398, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2492, "s": 2458, "text": "mysql> select *from Second_Table;" }, { "code": null, "e": 2522, "s": 2492, "text": "The following is the output −" }, { "code": null, "e": 2601, "s": 2522, "text": "+------+\n| Id |\n+------+\n| 2 |\n| 4 |\n+------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2694, "s": 2601, "text": "The query is as follows to compare two tables and return missing IDs using LEFT OUTER JOIN −" }, { "code": null, "e": 2848, "s": 2694, "text": "mysql> SELECT First_Table.Id FROM First_Table\n -> LEFT OUTER JOIN Second_Table ON First_Table.Id = Second_Table.Id\n -> WHERE Second_Table.Id IS NULL;" }, { "code": null, "e": 2878, "s": 2848, "text": "The following is the output −" }, { "code": null, "e": 2957, "s": 2878, "text": "+------+\n| Id |\n+------+\n| 1 |\n| 3 |\n+------+\n2 rows in set (0.00 sec)" } ]
Parsing XML with DOM APIs in Python
The Document Object Model ("DOM") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another. Here is the easiest way to quickly load an XML document and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file. The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object. #!/usr/bin/python from xml.dom.minidom import parse import xml.dom.minidom # Open XML document using minidom parser DOMTree = xml.dom.minidom.parse("movies.xml") collection = DOMTree.documentElement if collection.hasAttribute("shelf"): print "Root element : %s" % collection.getAttribute("shelf") # Get all the movies in the collection movies = collection.getElementsByTagName("movie") # Print detail of each movie. for movie in movies: print "*****Movie*****" if movie.hasAttribute("title"): print "Title: %s" % movie.getAttribute("title") type = movie.getElementsByTagName('type')[0] print "Type: %s" % type.childNodes[0].data format = movie.getElementsByTagName('format')[0] print "Format: %s" % format.childNodes[0].data rating = movie.getElementsByTagName('rating')[0] print "Rating: %s" % rating.childNodes[0].data description = movie.getElementsByTagName('description')[0] print "Description: %s" % description.childNodes[0].data This would produce the following result − Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Rating: R Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Description: Viewable boredom For a complete detail on DOM API documentation, please refer to standard Python APIs.
[ { "code": null, "e": 1204, "s": 1062, "text": "The Document Object Model (\"DOM\") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents." }, { "code": null, "e": 1399, "s": 1204, "text": "The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another." }, { "code": null, "e": 1614, "s": 1399, "text": "Here is the easiest way to quickly load an XML document and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file." }, { "code": null, "e": 1762, "s": 1614, "text": "The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object." }, { "code": null, "e": 2735, "s": 1762, "text": "#!/usr/bin/python\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\n# Open XML document using minidom parser\nDOMTree = xml.dom.minidom.parse(\"movies.xml\")\ncollection = DOMTree.documentElement\nif collection.hasAttribute(\"shelf\"):\n print \"Root element : %s\" % collection.getAttribute(\"shelf\")\n# Get all the movies in the collection\nmovies = collection.getElementsByTagName(\"movie\")\n# Print detail of each movie.\nfor movie in movies:\nprint \"*****Movie*****\"\n if movie.hasAttribute(\"title\"):\n print \"Title: %s\" % movie.getAttribute(\"title\")\n type = movie.getElementsByTagName('type')[0]\n print \"Type: %s\" % type.childNodes[0].data\n format = movie.getElementsByTagName('format')[0]\n print \"Format: %s\" % format.childNodes[0].data\n rating = movie.getElementsByTagName('rating')[0]\n print \"Rating: %s\" % rating.childNodes[0].data\n description = movie.getElementsByTagName('description')[0]\n print \"Description: %s\" % description.childNodes[0].data" }, { "code": null, "e": 2777, "s": 2735, "text": "This would produce the following result −" }, { "code": null, "e": 3246, "s": 2777, "text": "Root element : New Arrivals\n*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nRating: PG\nDescription: Talk about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nRating: R\nDescription: A schientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nFormat: DVD\nRating: PG\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nDescription: Viewable boredom" }, { "code": null, "e": 3332, "s": 3246, "text": "For a complete detail on DOM API documentation, please refer to standard Python APIs." } ]
How to use Lambda Function in Python?
These are basically anonymous one-line functions created at runtime which are not bound to the name of the functions. They return the definition of the function on the fly. Lambda functions don't contain a return statement, they always return an expression. You can always put a lambda definition anywhere a function is expected. Suppose we have a function which is to be used only once and called from only one place, then we can use lambda functions. So you don't need to give it a name and you can define the functionality there itself. Hence, we eliminate the use of a function and use Lambda expression. lambda argument: manipulate(argument) The given code defines a lambda function that gives the following output add = lambda x, y: x + y print(add(4, 6)) 10
[ { "code": null, "e": 1180, "s": 1062, "text": "These are basically anonymous one-line functions created at runtime which are not bound to the name of the functions." }, { "code": null, "e": 1235, "s": 1180, "text": "They return the definition of the function on the fly." }, { "code": null, "e": 1320, "s": 1235, "text": "Lambda functions don't contain a return statement, they always return an expression." }, { "code": null, "e": 1392, "s": 1320, "text": "You can always put a lambda definition anywhere a function is expected." }, { "code": null, "e": 1515, "s": 1392, "text": "Suppose we have a function which is to be used only once and called from only one place, then we can use lambda functions." }, { "code": null, "e": 1671, "s": 1515, "text": "So you don't need to give it a name and you can define the functionality there itself. Hence, we eliminate the use of a function and use Lambda expression." }, { "code": null, "e": 1709, "s": 1671, "text": "lambda argument: manipulate(argument)" }, { "code": null, "e": 1782, "s": 1709, "text": "The given code defines a lambda function that gives the following output" }, { "code": null, "e": 1824, "s": 1782, "text": "add = lambda x, y: x + y\nprint(add(4, 6))" }, { "code": null, "e": 1827, "s": 1824, "text": "10" } ]
How to convert Hex to RGBA value using JavaScript ? - GeeksforGeeks
31 Dec, 2019 Given a color hex code and the task is to convert Hex Value to RGBA value. Here are few of the mostly techniques discussed with the help of JavaScript. Approach 1: First check the passed Hex value is valid or not through a Regular Expression. Then get the hex value content after ‘#’ by using .slice() method and use .split() method to get the every character of the hex value in the array. If the length of array is 3(eg. #fff, #aaa) then store them as(eg. #ffffff, #aaaaaa respectively) to make the length 6. Transform the code to Hexadecimal as first 2 character belongs to Red Value, mid 2 character belongs to Green value and so on. Example: This example uses the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> How to convert Hex value to RGBA value using JavaScript </title></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 20px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 26px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var hexValue = '#fbafff'; el_up.innerHTML = "Click on the button to" + " get the RGBA value of Hex " + "Value.<br>HexValue = '" + hexValue + "'"; function convertHexToRgbA(hexVal) { var ret; // If the hex value is valid. if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hexVal)) { // Getting the content after '#', // eg. 'ffffff' in case of '#ffffff' ret = hexVal.slice(1); // Splitting each character ret = ret.split(''); // Checking if the length is 3 // then make that 6 if(ret.length == 3) { var ar = []; ar.push(ret[0]); ar.push(ret[0]); ar.push(ret[1]); ar.push(ret[1]); ar.push(ret[2]); ar.push(ret[2]); ret = ar; } // Starts with '0x'(in hexadecimal) ret = '0x'+ ret.join(''); // Converting the first 2 characters // from hexadecimal to r value var r = (ret>>16)&255; // Converting the second 2 characters // to hexadecimal to g value var g = (ret>>8)&255; // Converting the last 2 characters // to hexadecimal to b value var b = ret&255; // Appending all of them to make // the RGBA value return 'rgba('+[r, g, b].join(',')+',1)'; } } function gfg_Run() { el_down.innerHTML = "The RGBA value of '" + hexValue + "' is '" + convertHexToRgbA(hexValue) + "'"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Use .slice() method to get the first 2 characters and convert them to Hexadecimal. Repeat the step 1 for every 2 characters for rest of the code. Append them together and return the final value. Example: This example uses the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> How to convert Hex value to RGBA value using JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 20px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 26px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var hexValue = '#fbafff'; el_up.innerHTML = "Click on the button to get" + " the RGBA value of Hex Value." + "<br>HexValue = '" + hexValue + "'"; function convertHexToRgbA(hex, a) { // Convert the first 2 characters to hexadecimal var r = parseInt(hex.substring(1, 3), 16), // Convert the middle 2 characters to hexadecimal g = parseInt(hex.substring(3, 5), 16), // Convert the last 2 characters to hexadecimal b = parseInt(hex.substring(5, 7), 16); // append them all return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; } function gfg_Run() { el_down.innerHTML = "The RGBA value of '" + hexValue + "' is '" + convertHexToRgbA(hexValue, 1) + "'"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25300, "s": 25272, "text": "\n31 Dec, 2019" }, { "code": null, "e": 25452, "s": 25300, "text": "Given a color hex code and the task is to convert Hex Value to RGBA value. Here are few of the mostly techniques discussed with the help of JavaScript." }, { "code": null, "e": 25464, "s": 25452, "text": "Approach 1:" }, { "code": null, "e": 25543, "s": 25464, "text": "First check the passed Hex value is valid or not through a Regular Expression." }, { "code": null, "e": 25691, "s": 25543, "text": "Then get the hex value content after ‘#’ by using .slice() method and use .split() method to get the every character of the hex value in the array." }, { "code": null, "e": 25811, "s": 25691, "text": "If the length of array is 3(eg. #fff, #aaa) then store them as(eg. #ffffff, #aaaaaa respectively) to make the length 6." }, { "code": null, "e": 25938, "s": 25811, "text": "Transform the code to Hexadecimal as first 2 character belongs to Red Value, mid 2 character belongs to Green value and so on." }, { "code": null, "e": 25995, "s": 25938, "text": "Example: This example uses the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert Hex value to RGBA value using JavaScript </title></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 20px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 26px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var hexValue = '#fbafff'; el_up.innerHTML = \"Click on the button to\" + \" get the RGBA value of Hex \" + \"Value.<br>HexValue = '\" + hexValue + \"'\"; function convertHexToRgbA(hexVal) { var ret; // If the hex value is valid. if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hexVal)) { // Getting the content after '#', // eg. 'ffffff' in case of '#ffffff' ret = hexVal.slice(1); // Splitting each character ret = ret.split(''); // Checking if the length is 3 // then make that 6 if(ret.length == 3) { var ar = []; ar.push(ret[0]); ar.push(ret[0]); ar.push(ret[1]); ar.push(ret[1]); ar.push(ret[2]); ar.push(ret[2]); ret = ar; } // Starts with '0x'(in hexadecimal) ret = '0x'+ ret.join(''); // Converting the first 2 characters // from hexadecimal to r value var r = (ret>>16)&255; // Converting the second 2 characters // to hexadecimal to g value var g = (ret>>8)&255; // Converting the last 2 characters // to hexadecimal to b value var b = ret&255; // Appending all of them to make // the RGBA value return 'rgba('+[r, g, b].join(',')+',1)'; } } function gfg_Run() { el_down.innerHTML = \"The RGBA value of '\" + hexValue + \"' is '\" + convertHexToRgbA(hexValue) + \"'\"; } </script> </body> </html>", "e": 28666, "s": 25995, "text": null }, { "code": null, "e": 28674, "s": 28666, "text": "Output:" }, { "code": null, "e": 28705, "s": 28674, "text": "Before clicking on the button:" }, { "code": null, "e": 28735, "s": 28705, "text": "After clicking on the button:" }, { "code": null, "e": 28747, "s": 28735, "text": "Approach 2:" }, { "code": null, "e": 28830, "s": 28747, "text": "Use .slice() method to get the first 2 characters and convert them to Hexadecimal." }, { "code": null, "e": 28893, "s": 28830, "text": "Repeat the step 1 for every 2 characters for rest of the code." }, { "code": null, "e": 28942, "s": 28893, "text": "Append them together and return the final value." }, { "code": null, "e": 28999, "s": 28942, "text": "Example: This example uses the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert Hex value to RGBA value using JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 20px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 26px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var hexValue = '#fbafff'; el_up.innerHTML = \"Click on the button to get\" + \" the RGBA value of Hex Value.\" + \"<br>HexValue = '\" + hexValue + \"'\"; function convertHexToRgbA(hex, a) { // Convert the first 2 characters to hexadecimal var r = parseInt(hex.substring(1, 3), 16), // Convert the middle 2 characters to hexadecimal g = parseInt(hex.substring(3, 5), 16), // Convert the last 2 characters to hexadecimal b = parseInt(hex.substring(5, 7), 16); // append them all return \"rgba(\" + r + \", \" + g + \", \" + b + \", \" + a + \")\"; } function gfg_Run() { el_down.innerHTML = \"The RGBA value of '\" + hexValue + \"' is '\" + convertHexToRgbA(hexValue, 1) + \"'\"; } </script> </body> </html>", "e": 30750, "s": 28999, "text": null }, { "code": null, "e": 30758, "s": 30750, "text": "Output:" }, { "code": null, "e": 30789, "s": 30758, "text": "Before clicking on the button:" }, { "code": null, "e": 30819, "s": 30789, "text": "After clicking on the button:" }, { "code": null, "e": 30835, "s": 30819, "text": "JavaScript-Misc" }, { "code": null, "e": 30846, "s": 30835, "text": "JavaScript" }, { "code": null, "e": 30863, "s": 30846, "text": "Web Technologies" }, { "code": null, "e": 30890, "s": 30863, "text": "Web technologies Questions" }, { "code": null, "e": 30988, "s": 30890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31049, "s": 30988, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31090, "s": 31049, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31144, "s": 31090, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31184, "s": 31144, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31232, "s": 31184, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 31274, "s": 31232, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31307, "s": 31274, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31350, "s": 31307, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31400, "s": 31350, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Pure.CSS - Quick Guide
Pure is a Cascading Style Sheet (CSS) developed by YAHOO. It helps in creating faster, beautiful, and responsive websites. Some of its salient features are as follows − In-built responsive design Standard CSS with minimal footprint Set of small, responsive CSS modules Free to use Pure has an in-built responsive design such that the website created using Pure will redesign itself as per the device size. Pure has a 12 column mobile-first fluid grid that supports responsive classes for small, large, and medium screen sizes. Pure classes are created in such a way that the website can fit any screen size. The websites created using Pure are fully compatible with PC, tablets, and mobile devices. Pure uses standard CSS only and it is very easy to learn. There is no dependency on any external JavaScript library such as jQuery. Pure is by design very minimal and flat. It is designed considering the fact that it is much easier to add new CSS rules than to overwrite existing CSS rules. By adding a few lines of CSS, Pure's appearance can be customized to work with an existing web project. It supports shadows and bold colors. The colors and shades remain uniform across various platforms and devices. And most important of all, it is absolutely free to use. There are two ways to use Pure − Local Installation − You can download the pure.css file on your local machine and include it in your HTML code. Local Installation − You can download the pure.css file on your local machine and include it in your HTML code. CDN Based Version − You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN). CDN Based Version − You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN). Go to https://purecss.io/start/ to download the latest version available. Go to https://purecss.io/start/ to download the latest version available. Place the downloaded pure-min.css file in a directory of your website, e.g. /css. Place the downloaded pure-min.css file in a directory of your website, e.g. /css. You can include the css file in your HTML file as follows − <html> <head> <title>The PURE.CSS Example</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel="stylesheet" href="pure-min.css"> <style> .grids-example { background: rgb(250, 250, 250); margin: 2em auto; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; font-family: Consolas, 'Liberation Mono', Courier, monospace; text-align: center; } </style> </head> <body> <div class="grids-example"> <div class="pure-g"> <div class="pure-u-1-3"><p>First Column</p></div> <div class="pure-u-1-3"><p>Second Column</p></div> <div class="pure-u-1-3"><p>Third Column</p></div> </div> </div> </body> </html> It will produce the following result − You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN). yui.yahooapis.com provides content for the latest version. We are using yui.yahooapis.com CDN version of the library throughout this tutorial. Now let us rewrite the above example using pure.css from PureCSS.io CDN. <html> <head> <title>The PURE.CSS Example</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <style> .grids-example { background: rgb(250, 250, 250); margin: 2em auto; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; font-family: Consolas, 'Liberation Mono', Courier, monospace; text-align: center; } </style> </head> <body> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-1-3"><p>First Column</p></div> <div class = "pure-u-1-3"><p>Second Column</p></div> <div class = "pure-u-1-3"><p>Third Column</p></div> </div> </div> </body> </html> It will produce the following result − First Column Second Column Third Column Pure.CSS has several special classes to create a responsive design. .pure-u-* Sets the container to occupy required space on any device. .pure-u-sm-* Sets the container to occupy required space on a device with width ≥ 568px. .pure-u-md-* Sets the container to occupy required space on a device with width ≥ 768px. .pure-u-lg-* Sets the container to occupy required space on a device with width ≥ 1024px. .pure-u-xl-* Sets the container to occupy required space on a device with width ≥ 1280px. In the following example, we're going to create a responsive grid with a row having four columns. The columns should stack on small screens, should take up width: 50% on medium-sized screens, and should take up width: 25% on large screens. This is done by adding .pure-u-1 class for small screens, .pure-u-md-1-2 for mediumsized screens, and .pure-u-lg-1-4 for large screens. Resize the page to see the grid response to the screen size. purecss_responsive_design.htm <html> <head> <title>The PURE.CSS Containers</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css"> <style> .grids-example { background: rgb(250, 250, 250); margin: 2em auto; font-family: Consolas, 'Liberation Mono', Courier, monospace; text-align: center; } .graybox { background: rgb(240, 240, 240); border: 1px solid #ddd; } </style> </head> <body> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-1-1"> <div class = "graybox"> <p>These four columns should stack on small screens, should take up width: 50% on medium-sized screens, and should take up width: 25% on large screens.</p> </div> </div> <div class = "pure-u-1 pure-u-md-1-2 pure-u-lg-1-4"> <div class = "graybox"> <p>First Column</p> </div> </div> <div class = "pure-u-1 pure-u-md-1-2 pure-u-lg-1-4"> <div class="graybox"> <p>Second Column</p> </div> </div> <div class = "pure-u-1 pure-u-md-1-2 pure-u-lg-1-4"> <div class="graybox"> <p>Third Column</p> </div> </div> <div class = "pure-u-1 pure-u-md-1-2 pure-u-lg-1-4"> <div class = "graybox"> <p>Fourth Column</p> </div> </div> </div> </div> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-1"> <div class = "graybox"> <p>This column is to occupy the complete space of a row.</p> </div> </div> </div> </div> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-2-5"> <div class = "graybox"> <p>This column is to occupy the two-fifth of the space of a row.</p> </div> </div> </div> </div> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-3-5"> <div class = "graybox"> <p>This column is to occupy the three-fifth of the space of a row.</p> </div> </div> </div> </div> <div class = "grids-example"> <div class = "pure-g"> <div class = "pure-u-1-3"> <div class = "graybox"> <p>Column 1: This column is to occupy the one-third of the space of a row on all devices.</p> </div> </div> <div class = "pure-u-1-3"> <div class = "graybox"> <p>Column 2: This column is to occupy the one-third of the space of a row on all devices.</p> </div> </div> <div class = "pure-u-1-3"> <div class = "graybox"> <p>Column 3: This column is to occupy the one-third of the space of a row on all devices.</p> </div> </div> </div> </div> </body> </html> Verify the result. These four columns should stack on small screens, should take up width: 50% on medium-sized screens, and should take up width: 25% on large screens. First Column Second Column Third Column Fourth Column This column is to occupy the complete space of a row. This column is to occupy the two-fifth of the space of a row. This column is to occupy the three-fifth of the space of a row. Column 1: This column is to occupy the one-third of the space of a row on all devices. Column 2: This column is to occupy the one-third of the space of a row on all devices. Column 3: This column is to occupy the one-third of the space of a row on all devices. Pure.CSS provides the concept of Pure Grid with two types of classes, pure-g, a grid class and unit classes, pure-u-*. Following are the rules to use Pure Grids. Widths of Units are in fractions. For example, pure-u-1-2 represents 1/2 or 50% width, pure-u-2-5 represents 2/5 or 40% width and so on. Widths of Units are in fractions. For example, pure-u-1-2 represents 1/2 or 50% width, pure-u-2-5 represents 2/5 or 40% width and so on. Children of Pure Grid (element with pure-g class) must be using pure-u or pure-u-* classnames. Children of Pure Grid (element with pure-g class) must be using pure-u or pure-u-* classnames. All content should to be a part of a grid unit to be rendered properly. All content should to be a part of a grid unit to be rendered properly. Pure Grid comes with 5th and 24th unit sizes. Following illustrations show the examples of some of the available units, which can be appended to pure-ui-. For example, to create a cell of 50% width, you can use a css style pure-ui-1-2. purecss_5th_based.htm <html> <head> <title>The PURE.CSS Grid</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel="stylesheet" href="https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css"> <style> .grids-example { background: rgb(250, 250, 250); margin: 2em auto; font-family: Consolas, 'Liberation Mono', Courier, monospace; text-align: center; } .grid-unit { margin: 0.25em 0; padding-left: 4.5em; } .grid-unit .grid-unit-width { font-family: Consolas, 'Liberation Mono', Courier, monospace; } .grid-unit-bar { height: 2em; background: #eee; } </style> </head> <body> <div class="grids-example"> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">1-5</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-1-5"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">2-5</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-2-5"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">3-5</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-3-5"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">4-5</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-4-5"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">1</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-1"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">1-1</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-1-1"></div> </div> </div> </div> </div> </body> </html> Verify the result. purecss_24th_based.htm <html> <head> <title>The PURE.CSS Grid</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css"> <style> .grids-example { background: rgb(250, 250, 250); margin: 2em auto; font-family: Consolas, 'Liberation Mono', Courier, monospace; text-align: center; } .grid-unit { margin: 0.25em 0; padding-left: 4.5em; } .grid-unit .grid-unit-width { font-family: Consolas, 'Liberation Mono', Courier, monospace; } .grid-unit-bar { height: 2em; background: #eee; } </style> </head> <body> <div class = "grids-example"> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-12</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-12"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">2-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-2-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">3-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-3-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-8</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-8"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">4-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-4-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-6</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-6"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">5-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-5-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-4</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-4"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">6-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-6-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">7-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-7-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1-3</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-1-3"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">22-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-22-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">23-24</div> <div class = "grid-unit-details pure-u-1"> <div class = "pure-g"> <div class = "grid-unit-bar pure-u-23-24"></div> </div> </div> </div> <div class = "grid-unit pure-g"> <div class = "grid-unit-width pure-u">1</div> <div class ="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-1"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">1-1</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-1-1"></div> </div> </div> </div> <div class="grid-unit pure-g"> <div class="grid-unit-width pure-u">24-24</div> <div class="grid-unit-details pure-u-1"> <div class="pure-g"> <div class="grid-unit-bar pure-u-24-24"></div> </div> </div> </div> </div> </body> </html> Verify the result. Pure.CSS has a very beautiful and responsive CSS for form designs. The following CSS are used − pure-form Represents a compact inline form. pure-form-stacked Represents a stacked form with input elements below the labels. To be used with pure-form. pure-form-aligned Represents an aligned form with input elements below the labels. To be used with pure-form. pure-input-rounded Displays a form control with rounded corners pure-button Beautifies a button. pure-checkbox Beautifies a checkbox. pure-radio Beautifies a radio. purecss_forms.htm <html> <head> <title>The PURE.CSS Forms</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> </head> <body> <form class = "pure-form pure-form-aligned"> <fieldset> <div class = "pure-control-group"> <label for = "name">Username</label> <input id = "name" type = "text" placeholder = "Username" required> </div> <div class = "pure-control-group"> <label for = "email">Email</label> <input id = "email" type = "text" placeholder = "Email Address" required> </div> <div class = "pure-control-group"> <label for = "comments">Comments</label> <input id = "comments" type="text" placeholder = "Comments"> </div> <div class = "pure-controls"> <label for = "married" class = "pure-checkbox"> <input id = "married" type = "checkbox" checked = "checked"> Married </label> <br> <label for = "single" class = "pure-checkbox"> <input id = "single" type = "checkbox"> Single </label> <br> <label for = "dontknow" class = "pure-checkbox"> <input id = "dontknow" type = "checkbox" disabled> Don't know (Disabled) </label> <br> <br> </div> <div class = "pure-controls"> <label for = "male" class = "pure-radio"> <input id = "male" type = "radio" name = "gender" value = "male" checked> Male </label> <br> <label for = "female" class= "pure-radio"> <input id = "female" type = "radio" name = "gender" value = "female"> Female </label> <br> <label for = "dontknow1" class = "pure-radio"> <input id = "dontknow1" type = "radio" name = "gender" value = "female" disabled> Don't know (Disabled) </label> <button type = "submit" class = "pure-button pure-button-primary">Submit</button> </div> </fieldset> </form> </body> </html> Verify the result. Pure.CSS has a very beautiful and responsive CSS for customizing the look of a button. The following CSS are used − pure-button Represents a standard button. Can be used to style a link and button as well. pure-button-disabled Represents a disabled button. To be used along with pure-button. pure-button-active Represents a pressed button. To be used along with pure-button. purecss_buttons.htm <html> <head> <title>The PURE.CSS Forms</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <style> .success, .error, .warning, .secondary { color: white; border-radius: 4px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); } .success { background: rgb(28, 184, 65); /* green */ } .error { background: rgb(202, 60, 60); /* maroon */ } .warning { background: rgb(223, 117, 20); /* orange */ } .secondary { background: rgb(66, 184, 221); /* light blue */ } .xsmall { font-size: 70%; } .small { font-size: 85%; } .large { font-size: 110%; } .xlarge { font-size: 125%; } </style> </head> <body> <h2>Standard Buttons</h2> <button class = "pure-button">Click Me</button> <button class = "pure-button pure-button-active">Click Me</button> <button class = "pure-button pure-button-disabled">I am disabled</button> <h2>Links as Buttons</h2> <a class = "pure-button">Link</a> <a class = "pure-button pure-button-active">Link</a> <a class = "pure-button pure-button-disabled">Disabled Link</a> <h2>Primary Button</h2> <a class = "pure-button pure-button-primary">Submit</a> <h2>Customized button</h2> <button class = "pure-button success">Success</button> <button class = "pure-button error">Error</button> <button class = "pure-button warning">Warning</button> <button class = "pure-button secondary">Secondary</button> <h2>Different Sized button</h2> <button class = "pure-button xsmall">Extra Small</button> <button class = "pure-button small">Small</button> <button class = "pure-button large">Large</button> <button class = "pure-button xlarge">Extra Large</button> </body> </html> Verify the result. Pure.CSS can be used to display different types of tables using various styles over pure-table pure-table Represents a basic table with any a default padding, border and an emphasized header. pure-table-bordered Draws a table with a border across rows. pure-table-horizontal Draws a table with horizontal lines. pure-table-striped Displays a stripped table. pure-table-odd If applied on every other tr,changes the background of the row and creates a zebra-styled effect. purecss_tables.htm <html> <head> <title>The PURE.CSS Tables</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> </head> <body> <h2>Tables Demo</h2> <hr/> <h3>Simple Table</h3> <table class = "pure-table"> <thead> <tr> <th>Student</th> <th>Class</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Mahesh Parashar</td> <td>VI</td> <td>A</td> </tr> <tr> <td>Rahul Sharma</td> <td>VI</td> <td>B</td> </tr> <tr> <td>Mohan Sood</td> <td>VI</td> <td>A</td> </tr> </tbody> </table> <h3>Bordered Table</h3> <table class="pure-table pure-table-bordered"> <thead> <tr>< th>Student</th> <th>Class</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Mahesh Parashar</td> <td>VI</td> <td>A</td> </tr> <tr> <td>Rahul Sharma</td> <td>VI</td> <td>B</td> </tr> <tr> <td>Mohan Sood</td> <td>VI</td> <td>A</td> </tr> </tbody> </table> <h3>Table with Horizontal Borders</h3> <table class="pure-table pure-table-horizontal"> <thead> <tr> <th>Student</th> <th>Class</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Mahesh Parashar</td> <td>VI</td> <td>A</td> </tr> <tr> <td>Rahul Sharma</td> <td>VI</td> <td>B</td> </tr> <tr> <td>Mohan Sood</td> <td>VI</td> <td>A</td> </tr> </tbody> </table> <h3>Stripped Table</h3> <table class = "pure-table pure-table-striped"> <thead> <tr> <th>Student</th> <th>Class</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Mahesh Parashar</td> <td>VI</td> <td>A</td> </tr> <tr> <td>Rahul Sharma</td> <td>VI</td> <td>B</td> </tr> <tr> <td>Mohan Sood</td> <td>VI</td> <td>A</td> </tr> </tbody> </table> </body> </html> Verify the result. Pure.CSS provides options to display the images in a responsive way using pure-image as the main class. pure-img Represents a basic styled image without any border. Image grows and shrinks with the content maintaining the correct ratio. purecss_images.htm <html> <head> <title>The W3.CSS Images</title> <meta name = "viewport" content = "width=device-width, initial-scale=1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> </head> <body> <h2>Images Demo</h2> <hr/> <div class = "pure-g"> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt="html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt = "html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt="html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt = "html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt = "html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt = "html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt="html5"> </div> <div class = "pure-u-1-4 pure-u-lg-1-8"> <img class = "pure-img" src = "html5-mini-logo.jpg" alt = "html5"> </div> </div> </body> </html> Verify the result. Pure.CSS supports the following popular icon libraries − Font Awesome Icons Google Material Icons Bootstrap Icons To use an icon, place the name of the icon in the class of an HTML <i> element. purecss_icons.htm <html> <head> <title>The PURE.CSS Icons</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel = "stylesheet" href="https://fonts.googleapis.com/icon?family = Material+Icons"> <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <style> .xsmall { font-size: 70%; } .small { font-size: 85%; } .large { font-size: 110%; } .xlarge { font-size: 125%; } </style> </head> <body> <h2>Icons Demo</h2> <hr/> <h3>Font Awesome Icon Demo</h3> <i class = "fa fa-cloud xsmall"></i> <i class = "fa fa-cloud small"></i> <i class = "fa fa-cloud"></i> <i class = "fa fa-cloud large"></i> <i class = "fa fa-cloud xlarge"></i> <h3>Google Material Design Icon Demo</h3> <i class = "material-icons xsmall">cloud</i> <i class = "material-icons small">cloud</i> <i class = "material-icons large">cloud</i> <i class = "material-icons xlarge">cloud</i> <i class = "material-icons">cloud</i> <h3>Bootstrap Icon Demo</h3> <i class = "glyphicon glyphicon-cloud xsmall"></i> <i class = "glyphicon glyphicon-cloud small"></i> <i class = "glyphicon glyphicon-cloud"></i> <i class = "glyphicon glyphicon-cloud large"></i> <i class = "glyphicon glyphicon-cloud xlarge"></i> <h3>Button with Icon Demo</h3> <button class = "pure-button"><i class = "fa fa-cog"></i> Settings</button> <a class = "pure-button" href = "#"><i class = "fa fa-shopping-cart fa-lg"></i> Checkout</a> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 1894, "s": 1771, "text": "Pure is a Cascading Style Sheet (CSS) developed by YAHOO. It helps in creating faster, beautiful, and responsive websites." }, { "code": null, "e": 1940, "s": 1894, "text": "Some of its salient features are as follows −" }, { "code": null, "e": 1967, "s": 1940, "text": "In-built responsive design" }, { "code": null, "e": 2003, "s": 1967, "text": "Standard CSS with minimal footprint" }, { "code": null, "e": 2040, "s": 2003, "text": "Set of small, responsive CSS modules" }, { "code": null, "e": 2052, "s": 2040, "text": "Free to use" }, { "code": null, "e": 2298, "s": 2052, "text": "Pure has an in-built responsive design such that the website created using Pure will redesign itself as per the device size. Pure has a 12 column mobile-first fluid grid that supports responsive classes for small, large, and medium screen sizes." }, { "code": null, "e": 2470, "s": 2298, "text": "Pure classes are created in such a way that the website can fit any screen size. The websites created using Pure are fully compatible with PC, tablets, and mobile devices." }, { "code": null, "e": 2602, "s": 2470, "text": "Pure uses standard CSS only and it is very easy to learn. There is no dependency on any external JavaScript library such as jQuery." }, { "code": null, "e": 2865, "s": 2602, "text": "Pure is by design very minimal and flat. It is designed considering the fact that it is much easier to add new CSS rules than to overwrite existing CSS rules. By adding a few lines of CSS, Pure's appearance can be customized to work with an existing web project." }, { "code": null, "e": 3034, "s": 2865, "text": "It supports shadows and bold colors. The colors and shades remain uniform across various platforms and devices. And most important of all, it is absolutely free to use." }, { "code": null, "e": 3067, "s": 3034, "text": "There are two ways to use Pure −" }, { "code": null, "e": 3179, "s": 3067, "text": "Local Installation − You can download the pure.css file on your local machine and include it in your HTML code." }, { "code": null, "e": 3291, "s": 3179, "text": "Local Installation − You can download the pure.css file on your local machine and include it in your HTML code." }, { "code": null, "e": 3415, "s": 3291, "text": "CDN Based Version − You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN)." }, { "code": null, "e": 3539, "s": 3415, "text": "CDN Based Version − You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN)." }, { "code": null, "e": 3613, "s": 3539, "text": "Go to https://purecss.io/start/ to download the latest version available." }, { "code": null, "e": 3687, "s": 3613, "text": "Go to https://purecss.io/start/ to download the latest version available." }, { "code": null, "e": 3769, "s": 3687, "text": "Place the downloaded pure-min.css file in a directory of your website, e.g. /css." }, { "code": null, "e": 3851, "s": 3769, "text": "Place the downloaded pure-min.css file in a directory of your website, e.g. /css." }, { "code": null, "e": 3911, "s": 3851, "text": "You can include the css file in your HTML file as follows −" }, { "code": null, "e": 4773, "s": 3911, "text": "<html>\n <head>\n <title>The PURE.CSS Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel=\"stylesheet\" href=\"pure-min.css\">\n\t \n <style>\n .grids-example {\n background: rgb(250, 250, 250);\n margin: 2em auto;\n border-top: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\t\t\t\n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n text-align: center;\t\t\t\t\t\n }\n </style>\n\t \n </head>\n \n \n <body>\n <div class=\"grids-example\">\n <div class=\"pure-g\">\n <div class=\"pure-u-1-3\"><p>First Column</p></div>\n <div class=\"pure-u-1-3\"><p>Second Column</p></div>\n <div class=\"pure-u-1-3\"><p>Third Column</p></div>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4812, "s": 4773, "text": "It will produce the following result −" }, { "code": null, "e": 4975, "s": 4812, "text": "You can include the pure.css file into your HTML code directly from the Content Delivery Network (CDN). yui.yahooapis.com provides content for the latest version." }, { "code": null, "e": 5059, "s": 4975, "text": "We are using yui.yahooapis.com CDN version of the library throughout this tutorial." }, { "code": null, "e": 5132, "s": 5059, "text": "Now let us rewrite the above example using pure.css from PureCSS.io CDN." }, { "code": null, "e": 6039, "s": 5132, "text": "<html>\n <head>\n <title>The PURE.CSS Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n\t \n <style>\n .grids-example {\n background: rgb(250, 250, 250);\n margin: 2em auto;\n border-top: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\t\t\t\n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n text-align: center;\t\t\t\t\t\n }\n </style>\n </head>\n \n <body>\n <div class = \"grids-example\">\n <div class = \"pure-g\">\n <div class = \"pure-u-1-3\"><p>First Column</p></div>\n <div class = \"pure-u-1-3\"><p>Second Column</p></div>\n <div class = \"pure-u-1-3\"><p>Third Column</p></div>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 6078, "s": 6039, "text": "It will produce the following result −" }, { "code": null, "e": 6091, "s": 6078, "text": "First Column" }, { "code": null, "e": 6105, "s": 6091, "text": "Second Column" }, { "code": null, "e": 6118, "s": 6105, "text": "Third Column" }, { "code": null, "e": 6186, "s": 6118, "text": "Pure.CSS has several special classes to create a responsive design." }, { "code": null, "e": 6196, "s": 6186, "text": ".pure-u-*" }, { "code": null, "e": 6255, "s": 6196, "text": "Sets the container to occupy required space on any device." }, { "code": null, "e": 6268, "s": 6255, "text": ".pure-u-sm-*" }, { "code": null, "e": 6344, "s": 6268, "text": "Sets the container to occupy required space on a device with width ≥ 568px." }, { "code": null, "e": 6357, "s": 6344, "text": ".pure-u-md-*" }, { "code": null, "e": 6433, "s": 6357, "text": "Sets the container to occupy required space on a device with width ≥ 768px." }, { "code": null, "e": 6446, "s": 6433, "text": ".pure-u-lg-*" }, { "code": null, "e": 6523, "s": 6446, "text": "Sets the container to occupy required space on a device with width ≥ 1024px." }, { "code": null, "e": 6536, "s": 6523, "text": ".pure-u-xl-*" }, { "code": null, "e": 6613, "s": 6536, "text": "Sets the container to occupy required space on a device with width ≥ 1280px." }, { "code": null, "e": 6853, "s": 6613, "text": "In the following example, we're going to create a responsive grid with a row having four columns. The columns should stack on small screens, should take up width: 50% on medium-sized screens, and should take up width: 25% on large screens." }, { "code": null, "e": 7050, "s": 6853, "text": "This is done by adding .pure-u-1 class for small screens, .pure-u-md-1-2 for mediumsized screens, and .pure-u-lg-1-4 for large screens. Resize the page to see the grid response to the screen size." }, { "code": null, "e": 7080, "s": 7050, "text": "purecss_responsive_design.htm" }, { "code": null, "e": 10818, "s": 7080, "text": "<html>\n <head>\n <title>The PURE.CSS Containers</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css\">\n\n <style>\n .grids-example {\n background: rgb(250, 250, 250);\n margin: 2em auto; \n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n text-align: center;\t\t\t\t\t\n }\t\n\n .graybox {\n background: rgb(240, 240, 240);\n border: 1px solid #ddd;\t\t\t\n }\t \n </style>\n </head>\n <body> \n \n <div class = \"grids-example\"> \t \n <div class = \"pure-g\">\n <div class = \"pure-u-1-1\">\n <div class = \"graybox\">\n <p>These four columns should stack on small screens, \n should take up width: 50% on medium-sized screens, and should \n take up width: 25% on large screens.</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1 pure-u-md-1-2 pure-u-lg-1-4\">\n <div class = \"graybox\">\n <p>First Column</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1 pure-u-md-1-2 pure-u-lg-1-4\">\n <div class=\"graybox\">\n <p>Second Column</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1 pure-u-md-1-2 pure-u-lg-1-4\">\n <div class=\"graybox\">\n <p>Third Column</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1 pure-u-md-1-2 pure-u-lg-1-4\">\n <div class = \"graybox\">\n <p>Fourth Column</p>\n </div>\n </div>\n </div>\n </div>\n\t \n <div class = \"grids-example\">\n <div class = \"pure-g\">\n <div class = \"pure-u-1\">\n <div class = \"graybox\">\n <p>This column is to occupy the complete space of a row.</p>\n </div>\n </div>\n </div>\n </div>\n\t \n <div class = \"grids-example\">\n <div class = \"pure-g\">\n <div class = \"pure-u-2-5\">\n <div class = \"graybox\">\n <p>This column is to occupy the two-fifth of the space of a row.</p>\n </div>\n </div>\n </div>\n </div>\n \n <div class = \"grids-example\">\n <div class = \"pure-g\">\n <div class = \"pure-u-3-5\">\n <div class = \"graybox\">\n <p>This column is to occupy the three-fifth of the space of a row.</p>\n </div>\n </div>\n </div>\n </div> \n \n <div class = \"grids-example\">\n <div class = \"pure-g\">\n <div class = \"pure-u-1-3\">\n <div class = \"graybox\">\n <p>Column 1: This column is to occupy the one-third of the\n space of a row on all devices.</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1-3\">\n <div class = \"graybox\">\n <p>Column 2: This column is to occupy the one-third of the space \n of a row on all devices.</p>\n </div>\n </div>\n\t\t\t\n <div class = \"pure-u-1-3\">\n <div class = \"graybox\">\n <p>Column 3: This column is to occupy the one-third of the space of a \n row on all devices.</p>\n </div>\n </div>\n </div>\n </div>\t\n </body>\n</html>" }, { "code": null, "e": 10837, "s": 10818, "text": "Verify the result." }, { "code": null, "e": 10986, "s": 10837, "text": "These four columns should stack on small screens, should take up width: 50% on medium-sized screens, and should take up width: 25% on large screens." }, { "code": null, "e": 10999, "s": 10986, "text": "First Column" }, { "code": null, "e": 11013, "s": 10999, "text": "Second Column" }, { "code": null, "e": 11026, "s": 11013, "text": "Third Column" }, { "code": null, "e": 11040, "s": 11026, "text": "Fourth Column" }, { "code": null, "e": 11094, "s": 11040, "text": "This column is to occupy the complete space of a row." }, { "code": null, "e": 11156, "s": 11094, "text": "This column is to occupy the two-fifth of the space of a row." }, { "code": null, "e": 11220, "s": 11156, "text": "This column is to occupy the three-fifth of the space of a row." }, { "code": null, "e": 11307, "s": 11220, "text": "Column 1: This column is to occupy the one-third of the space of a row on all devices." }, { "code": null, "e": 11394, "s": 11307, "text": "Column 2: This column is to occupy the one-third of the space of a row on all devices." }, { "code": null, "e": 11481, "s": 11394, "text": "Column 3: This column is to occupy the one-third of the space of a row on all devices." }, { "code": null, "e": 11643, "s": 11481, "text": "Pure.CSS provides the concept of Pure Grid with two types of classes, pure-g, a grid class and unit classes, pure-u-*. Following are the rules to use Pure Grids." }, { "code": null, "e": 11780, "s": 11643, "text": "Widths of Units are in fractions. For example, pure-u-1-2 represents 1/2 or 50% width, pure-u-2-5 represents 2/5 or 40% width and so on." }, { "code": null, "e": 11917, "s": 11780, "text": "Widths of Units are in fractions. For example, pure-u-1-2 represents 1/2 or 50% width, pure-u-2-5 represents 2/5 or 40% width and so on." }, { "code": null, "e": 12012, "s": 11917, "text": "Children of Pure Grid (element with pure-g class) must be using pure-u or pure-u-* classnames." }, { "code": null, "e": 12107, "s": 12012, "text": "Children of Pure Grid (element with pure-g class) must be using pure-u or pure-u-* classnames." }, { "code": null, "e": 12179, "s": 12107, "text": "All content should to be a part of a grid unit to be rendered properly." }, { "code": null, "e": 12251, "s": 12179, "text": "All content should to be a part of a grid unit to be rendered properly." }, { "code": null, "e": 12487, "s": 12251, "text": "Pure Grid comes with 5th and 24th unit sizes. Following illustrations show the examples of some of the available units, which can be appended to pure-ui-. For example, to create a cell of 50% width, you can use a css style pure-ui-1-2." }, { "code": null, "e": 12509, "s": 12487, "text": "purecss_5th_based.htm" }, { "code": null, "e": 15396, "s": 12509, "text": "<html>\n <head>\n <title>The PURE.CSS Grid</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n <link rel=\"stylesheet\" href=\"https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css\">\n <style>\n .grids-example {\n background: rgb(250, 250, 250);\n margin: 2em auto; \n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n text-align: center;\t\t\t\t\t\n }\t\n .grid-unit {\n margin: 0.25em 0;\n padding-left: 4.5em;\n }\n .grid-unit .grid-unit-width {\n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n }\n .grid-unit-bar {\n height: 2em;\n background: #eee;\n }\n </style>\n </head>\n\t\n <body> \n\t\n <div class=\"grids-example\"> \t \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">1-5</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-1-5\"></div>\n </div>\n </div>\n </div>\n \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">2-5</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-2-5\"></div>\n </div>\n </div>\n </div>\n \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">3-5</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-3-5\"></div>\n </div>\n </div>\n </div>\n \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">4-5</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-4-5\"></div>\n </div>\n </div>\n </div>\n \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">1</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-1\"></div>\n </div>\n </div>\n </div>\n \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">1-1</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-1-1\"></div>\n </div>\n </div>\n </div>\n </div>\t\n </body>\n</html>" }, { "code": null, "e": 15415, "s": 15396, "text": "Verify the result." }, { "code": null, "e": 15438, "s": 15415, "text": "purecss_24th_based.htm" }, { "code": null, "e": 21915, "s": 15438, "text": "<html>\n <head>\n <title>The PURE.CSS Grid</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css\">\n <style>\n .grids-example {\n background: rgb(250, 250, 250);\n margin: 2em auto; \n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n text-align: center;\t\t\t\t\t\n }\t\n .grid-unit {\n margin: 0.25em 0;\n padding-left: 4.5em;\n }\n .grid-unit .grid-unit-width {\n font-family: Consolas, 'Liberation Mono', Courier, monospace;\n }\n .grid-unit-bar {\n height: 2em;\n background: #eee;\n }\n </style>\n </head>\n\t\n <body> \n\t\n <div class = \"grids-example\"> \t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n\t\t\t <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-12</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-12\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">2-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-2-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">3-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-3-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-8</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-8\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">4-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-4-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-6</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-6\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">5-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-5-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-4</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-4\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">6-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-6-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">7-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-7-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1-3</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-1-3\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">22-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-22-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">23-24</div>\n <div class = \"grid-unit-details pure-u-1\">\n <div class = \"pure-g\">\n <div class = \"grid-unit-bar pure-u-23-24\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class = \"grid-unit pure-g\">\n <div class = \"grid-unit-width pure-u\">1</div>\n <div class =\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-1\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">1-1</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-1-1\"></div>\n </div>\n </div>\n </div>\n\t\t \n <div class=\"grid-unit pure-g\">\n <div class=\"grid-unit-width pure-u\">24-24</div>\n <div class=\"grid-unit-details pure-u-1\">\n <div class=\"pure-g\">\n <div class=\"grid-unit-bar pure-u-24-24\"></div>\n </div>\n </div>\n </div>\n </div>\t\n </body>\n</html>" }, { "code": null, "e": 21934, "s": 21915, "text": "Verify the result." }, { "code": null, "e": 22030, "s": 21934, "text": "Pure.CSS has a very beautiful and responsive CSS for form designs. The following CSS are\nused −" }, { "code": null, "e": 22040, "s": 22030, "text": "pure-form" }, { "code": null, "e": 22074, "s": 22040, "text": "Represents a compact inline form." }, { "code": null, "e": 22092, "s": 22074, "text": "pure-form-stacked" }, { "code": null, "e": 22183, "s": 22092, "text": "Represents a stacked form with input elements below the labels. To be used with pure-form." }, { "code": null, "e": 22201, "s": 22183, "text": "pure-form-aligned" }, { "code": null, "e": 22293, "s": 22201, "text": "Represents an aligned form with input elements below the labels. To be used with pure-form." }, { "code": null, "e": 22312, "s": 22293, "text": "pure-input-rounded" }, { "code": null, "e": 22357, "s": 22312, "text": "Displays a form control with rounded corners" }, { "code": null, "e": 22369, "s": 22357, "text": "pure-button" }, { "code": null, "e": 22390, "s": 22369, "text": "Beautifies a button." }, { "code": null, "e": 22404, "s": 22390, "text": "pure-checkbox" }, { "code": null, "e": 22427, "s": 22404, "text": "Beautifies a checkbox." }, { "code": null, "e": 22438, "s": 22427, "text": "pure-radio" }, { "code": null, "e": 22458, "s": 22438, "text": "Beautifies a radio." }, { "code": null, "e": 22476, "s": 22458, "text": "purecss_forms.htm" }, { "code": null, "e": 25075, "s": 22476, "text": "<html>\n <head>\n <title>The PURE.CSS Forms</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n </head>\n \n <body> \n <form class = \"pure-form pure-form-aligned\">\n <fieldset>\n <div class = \"pure-control-group\"> \n <label for = \"name\">Username</label>\n <input id = \"name\" type = \"text\" placeholder = \"Username\" required>\n </div>\n\t\t\t\n <div class = \"pure-control-group\"> \n <label for = \"email\">Email</label>\n <input id = \"email\" type = \"text\" placeholder = \"Email Address\" required> \n </div>\n\t\t\t\n <div class = \"pure-control-group\"> \n <label for = \"comments\">Comments</label>\n <input id = \"comments\" type=\"text\" placeholder = \"Comments\"> \n </div>\n\t\t\t\n <div class = \"pure-controls\">\n <label for = \"married\" class = \"pure-checkbox\">\n <input id = \"married\" type = \"checkbox\" checked = \"checked\">\n Married\n </label>\n <br>\n\t\t\t \n <label for = \"single\" class = \"pure-checkbox\">\n <input id = \"single\" type = \"checkbox\">\n Single\n </label>\n <br>\n\t\t\t \n <label for = \"dontknow\" class = \"pure-checkbox\">\n <input id = \"dontknow\" type = \"checkbox\" disabled>\n Don't know (Disabled)\n </label> \n <br>\n <br>\n </div>\n\t\t\t\n <div class = \"pure-controls\">\n <label for = \"male\" class = \"pure-radio\">\n <input id = \"male\" type = \"radio\" name = \"gender\" value = \"male\" checked>\n Male\n </label>\n <br>\n\t\t\t \n <label for = \"female\" class= \"pure-radio\">\n <input id = \"female\" type = \"radio\" name = \"gender\" value = \"female\">\n Female\n </label>\n <br>\n\t\t\t \n <label for = \"dontknow1\" class = \"pure-radio\">\n <input id = \"dontknow1\" type = \"radio\" name = \"gender\" value = \"female\" disabled>\n Don't know (Disabled)\n </label>\n <button type = \"submit\" class = \"pure-button pure-button-primary\">Submit</button>\n\t\t\t \n </div>\n </fieldset>\n </form> \n </body>\n</html>" }, { "code": null, "e": 25094, "s": 25075, "text": "Verify the result." }, { "code": null, "e": 25210, "s": 25094, "text": "Pure.CSS has a very beautiful and responsive CSS for customizing the look of a button.\nThe following CSS are used −" }, { "code": null, "e": 25222, "s": 25210, "text": "pure-button" }, { "code": null, "e": 25300, "s": 25222, "text": "Represents a standard button. Can be used to style a link and button as well." }, { "code": null, "e": 25321, "s": 25300, "text": "pure-button-disabled" }, { "code": null, "e": 25386, "s": 25321, "text": "Represents a disabled button. To be used along with pure-button." }, { "code": null, "e": 25405, "s": 25386, "text": "pure-button-active" }, { "code": null, "e": 25469, "s": 25405, "text": "Represents a pressed button. To be used along with pure-button." }, { "code": null, "e": 25489, "s": 25469, "text": "purecss_buttons.htm" }, { "code": null, "e": 27697, "s": 25489, "text": "<html>\n <head>\n <title>The PURE.CSS Forms</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n <style>\n .success,\n .error,\n .warning,\n .secondary {\n color: white;\n border-radius: 4px;\n text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);\n }\n \n .success {\n background: rgb(28, 184, 65); /* green */\n }\n\n .error {\n background: rgb(202, 60, 60); /* maroon */\n }\n\n .warning {\n background: rgb(223, 117, 20); /* orange */\n }\n\n .secondary {\n background: rgb(66, 184, 221); /* light blue */\n }\n\n .xsmall {\n font-size: 70%;\n }\n\n .small {\n font-size: 85%;\n }\n\n .large {\n font-size: 110%;\n }\n\n .xlarge {\n font-size: 125%;\n }\n </style>\t \t \n </head>\n\t\n <body> \n <h2>Standard Buttons</h2>\n <button class = \"pure-button\">Click Me</button>\n <button class = \"pure-button pure-button-active\">Click Me</button>\n <button class = \"pure-button pure-button-disabled\">I am disabled</button>\n\n <h2>Links as Buttons</h2>\n <a class = \"pure-button\">Link</a>\n <a class = \"pure-button pure-button-active\">Link</a>\n <a class = \"pure-button pure-button-disabled\">Disabled Link</a>\n\n <h2>Primary Button</h2>\n <a class = \"pure-button pure-button-primary\">Submit</a> \n\n <h2>Customized button</h2>\n <button class = \"pure-button success\">Success</button>\n <button class = \"pure-button error\">Error</button>\n <button class = \"pure-button warning\">Warning</button>\n <button class = \"pure-button secondary\">Secondary</button>\n\t \n <h2>Different Sized button</h2>\n <button class = \"pure-button xsmall\">Extra Small</button>\n <button class = \"pure-button small\">Small</button>\n <button class = \"pure-button large\">Large</button>\n <button class = \"pure-button xlarge\">Extra Large</button>\n </body>\n</html>" }, { "code": null, "e": 27716, "s": 27697, "text": "Verify the result." }, { "code": null, "e": 27811, "s": 27716, "text": "Pure.CSS can be used to display different types of tables using various styles over pure-table" }, { "code": null, "e": 27822, "s": 27811, "text": "pure-table" }, { "code": null, "e": 27908, "s": 27822, "text": "Represents a basic table with any a default padding, border and an emphasized header." }, { "code": null, "e": 27928, "s": 27908, "text": "pure-table-bordered" }, { "code": null, "e": 27969, "s": 27928, "text": "Draws a table with a border across rows." }, { "code": null, "e": 27991, "s": 27969, "text": "pure-table-horizontal" }, { "code": null, "e": 28028, "s": 27991, "text": "Draws a table with horizontal lines." }, { "code": null, "e": 28047, "s": 28028, "text": "pure-table-striped" }, { "code": null, "e": 28074, "s": 28047, "text": "Displays a stripped table." }, { "code": null, "e": 28089, "s": 28074, "text": "pure-table-odd" }, { "code": null, "e": 28187, "s": 28089, "text": "If applied on every other tr,changes the background of the row and creates a zebra-styled effect." }, { "code": null, "e": 28206, "s": 28187, "text": "purecss_tables.htm" }, { "code": null, "e": 31240, "s": 28206, "text": "<html>\n <head>\n <title>The PURE.CSS Tables</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n </head>\n \n <body> \n <h2>Tables Demo</h2>\n <hr/>\n <h3>Simple Table</h3>\n\t \n <table class = \"pure-table\">\n <thead>\n <tr>\n <th>Student</th>\n <th>Class</th>\n <th>Grade</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Mahesh Parashar</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n <tr>\n <td>Rahul Sharma</td>\n <td>VI</td>\n <td>B</td>\n </tr>\n <tr>\n <td>Mohan Sood</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n </tbody>\n </table>\n\t \n <h3>Bordered Table</h3>\n <table class=\"pure-table pure-table-bordered\">\n <thead>\n <tr><\n th>Student</th>\n <th>Class</th>\n <th>Grade</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Mahesh Parashar</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n <tr>\n <td>Rahul Sharma</td>\n <td>VI</td>\n <td>B</td>\n </tr>\n <tr>\n <td>Mohan Sood</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n </tbody>\n </table>\n\t \n <h3>Table with Horizontal Borders</h3>\n <table class=\"pure-table pure-table-horizontal\">\n <thead>\n <tr>\n <th>Student</th>\n <th>Class</th>\n <th>Grade</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Mahesh Parashar</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n <tr>\n <td>Rahul Sharma</td>\n <td>VI</td>\n <td>B</td>\n </tr>\n <tr>\n <td>Mohan Sood</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n </tbody>\n </table>\n\t \n <h3>Stripped Table</h3>\n <table class = \"pure-table pure-table-striped\">\n <thead>\n <tr>\n <th>Student</th>\n <th>Class</th>\n <th>Grade</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Mahesh Parashar</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n <tr>\n <td>Rahul Sharma</td>\n <td>VI</td>\n <td>B</td>\n </tr>\n <tr>\n <td>Mohan Sood</td>\n <td>VI</td>\n <td>A</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>" }, { "code": null, "e": 31259, "s": 31240, "text": "Verify the result." }, { "code": null, "e": 31363, "s": 31259, "text": "Pure.CSS provides options to display the images in a responsive way using pure-image as the main class." }, { "code": null, "e": 31372, "s": 31363, "text": "pure-img" }, { "code": null, "e": 31496, "s": 31372, "text": "Represents a basic styled image without any border. Image grows and shrinks with the content maintaining the correct ratio." }, { "code": null, "e": 31515, "s": 31496, "text": "purecss_images.htm" }, { "code": null, "e": 33059, "s": 31515, "text": "<html>\n <head>\n <title>The W3.CSS Images</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale=1\">\n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n </head>\n \n <body> \n <h2>Images Demo</h2>\n <hr/> \n <div class = \"pure-g\">\t\n\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt=\"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt = \"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt=\"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt = \"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt = \"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt = \"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt=\"html5\">\n </div>\n\t\t \n <div class = \"pure-u-1-4 pure-u-lg-1-8\">\n <img class = \"pure-img\" src = \"html5-mini-logo.jpg\" alt = \"html5\">\n </div>\n\t\t \n </div>\n </body>\n</html>" }, { "code": null, "e": 33078, "s": 33059, "text": "Verify the result." }, { "code": null, "e": 33135, "s": 33078, "text": "Pure.CSS supports the following popular icon libraries −" }, { "code": null, "e": 33154, "s": 33135, "text": "Font Awesome Icons" }, { "code": null, "e": 33176, "s": 33154, "text": "Google Material Icons" }, { "code": null, "e": 33192, "s": 33176, "text": "Bootstrap Icons" }, { "code": null, "e": 33272, "s": 33192, "text": "To use an icon, place the name of the icon in the class of an HTML <i> element." }, { "code": null, "e": 33290, "s": 33272, "text": "purecss_icons.htm" }, { "code": null, "e": 35316, "s": 33290, "text": "<html>\n <head>\n \n <title>The PURE.CSS Icons</title>\n\t \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n\t \n <link rel = \"stylesheet\" href = \"https://yui.yahooapis.com/pure/0.6.0/pure-min.css\">\n\t \n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css\">\n\t \n <link rel = \"stylesheet\" href=\"https://fonts.googleapis.com/icon?family = Material+Icons\">\n\t \n <link rel = \"stylesheet\" href = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">\n\t \n <style> \n .xsmall {\n font-size: 70%;\n }\n .small {\n font-size: 85%;\n }\n .large {\n font-size: 110%;\n }\n .xlarge {\n font-size: 125%;\n }\n </style>\n\t \n </head>\n \n <body> \n <h2>Icons Demo</h2>\n <hr/>\n <h3>Font Awesome Icon Demo</h3>\n <i class = \"fa fa-cloud xsmall\"></i>\n <i class = \"fa fa-cloud small\"></i>\n <i class = \"fa fa-cloud\"></i>\n <i class = \"fa fa-cloud large\"></i>\n <i class = \"fa fa-cloud xlarge\"></i>\n\t \n <h3>Google Material Design Icon Demo</h3> \n <i class = \"material-icons xsmall\">cloud</i>\t\n <i class = \"material-icons small\">cloud</i>\n <i class = \"material-icons large\">cloud</i>\n <i class = \"material-icons xlarge\">cloud</i>\n <i class = \"material-icons\">cloud</i>\n\t \n <h3>Bootstrap Icon Demo</h3>\n <i class = \"glyphicon glyphicon-cloud xsmall\"></i>\n <i class = \"glyphicon glyphicon-cloud small\"></i>\n <i class = \"glyphicon glyphicon-cloud\"></i>\n <i class = \"glyphicon glyphicon-cloud large\"></i>\n <i class = \"glyphicon glyphicon-cloud xlarge\"></i>\n\t \n <h3>Button with Icon Demo</h3>\n <button class = \"pure-button\"><i class = \"fa fa-cog\"></i> Settings</button>\n <a class = \"pure-button\" href = \"#\"><i class = \"fa fa-shopping-cart fa-lg\"></i> Checkout</a>\n </body>\n</html>" }, { "code": null, "e": 35335, "s": 35316, "text": "Verify the result." }, { "code": null, "e": 35342, "s": 35335, "text": " Print" }, { "code": null, "e": 35353, "s": 35342, "text": " Add Notes" } ]
Framework7 - Tap Hold Event
The Tap hold event is used to trigger (enable) after a sustained and complete the touch event so only, it is called tap hold event. The Tab Hold is a built-in Fast Clicks library. The following parameters are used to disable or enable and configured by default − tapHold To enable tap hold events when it is set to true. tapHoldDelay It specifies the duration of holding the tap before triggering taphold event on the target element. tapHoldPreventClicks The tap hold event will not be fired after clicking the event. The following code is used for enable tap hold events − var myApp = new Framework7 ({ tapHold: true //enable tap hold events }); var $$ = Dom7; $$('.some-link').on('taphold', function () { myApp.alert('Tap hold fired!'); }); 7 Lectures 1 hours Anadi Sharma 22 Lectures 6 hours Malhar Lathkar 102 Lectures 8 hours Karthikeya T 19 Lectures 5 hours Trevoir Williams 20 Lectures 1 hours John Elder 13 Lectures 3 hours Darwish Print Add Notes Bookmark this page
[ { "code": null, "e": 2831, "s": 2651, "text": "The Tap hold event is used to trigger (enable) after a sustained and complete the touch event so only, it is called tap hold event. The Tab Hold is a built-in Fast Clicks library." }, { "code": null, "e": 2914, "s": 2831, "text": "The following parameters are used to disable or enable and configured by default −" }, { "code": null, "e": 2922, "s": 2914, "text": "tapHold" }, { "code": null, "e": 2972, "s": 2922, "text": "To enable tap hold events when it is set to true." }, { "code": null, "e": 2985, "s": 2972, "text": "tapHoldDelay" }, { "code": null, "e": 3085, "s": 2985, "text": "It specifies the duration of holding the tap before triggering taphold event on the target element." }, { "code": null, "e": 3106, "s": 3085, "text": "tapHoldPreventClicks" }, { "code": null, "e": 3169, "s": 3106, "text": "The tap hold event will not be fired after clicking the event." }, { "code": null, "e": 3225, "s": 3169, "text": "The following code is used for enable tap hold events −" }, { "code": null, "e": 3404, "s": 3225, "text": "var myApp = new Framework7 ({\n tapHold: true //enable tap hold events\n});\n \nvar $$ = Dom7;\n \n$$('.some-link').on('taphold', function () {\n myApp.alert('Tap hold fired!');\n});" }, { "code": null, "e": 3436, "s": 3404, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3450, "s": 3436, "text": " Anadi Sharma" }, { "code": null, "e": 3483, "s": 3450, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 3499, "s": 3483, "text": " Malhar Lathkar" }, { "code": null, "e": 3533, "s": 3499, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 3547, "s": 3533, "text": " Karthikeya T" }, { "code": null, "e": 3580, "s": 3547, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3598, "s": 3580, "text": " Trevoir Williams" }, { "code": null, "e": 3631, "s": 3598, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 3643, "s": 3631, "text": " John Elder" }, { "code": null, "e": 3676, "s": 3643, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 3685, "s": 3676, "text": " Darwish" }, { "code": null, "e": 3692, "s": 3685, "text": " Print" }, { "code": null, "e": 3703, "s": 3692, "text": " Add Notes" } ]
Angular FormsModule Directive - GeeksforGeeks
04 Jun, 2021 In this article, we are going to see what is FormsModule in Angular 10 and how to use it. The FormsModule is used to make all the necessary imports for form implementation. Syntax: import { FormsModule } from '@angular/forms'; Approach: Create an Angular app to be used. In app.component.ts import forms from FormsModules. In app.component.html, make a form using FormsModule. Serve the angular app using ng serve to see the output. Example 1: app.component.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { } app.component.html <form #gfgform = "ngForm"> {{ gfgform.value | json }} <br> <br> Name: <input type="text" name = 'name' ngModel> Roll: <input type="text" name = 'roll' ngModel></form> Output: Reference: https://angular.io/api/forms/FormsModule Angular10 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Dropdown Component Angular 10 (blur) Event Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25029, "s": 25001, "text": "\n04 Jun, 2021" }, { "code": null, "e": 25119, "s": 25029, "text": "In this article, we are going to see what is FormsModule in Angular 10 and how to use it." }, { "code": null, "e": 25202, "s": 25119, "text": "The FormsModule is used to make all the necessary imports for form implementation." }, { "code": null, "e": 25210, "s": 25202, "text": "Syntax:" }, { "code": null, "e": 25256, "s": 25210, "text": "import { FormsModule } from '@angular/forms';" }, { "code": null, "e": 25267, "s": 25256, "text": "Approach: " }, { "code": null, "e": 25301, "s": 25267, "text": "Create an Angular app to be used." }, { "code": null, "e": 25353, "s": 25301, "text": "In app.component.ts import forms from FormsModules." }, { "code": null, "e": 25407, "s": 25353, "text": "In app.component.html, make a form using FormsModule." }, { "code": null, "e": 25463, "s": 25407, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 25476, "s": 25465, "text": "Example 1:" }, { "code": null, "e": 25493, "s": 25476, "text": "app.component.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { }", "e": 25990, "s": 25493, "text": null }, { "code": null, "e": 26009, "s": 25990, "text": "app.component.html" }, { "code": "<form #gfgform = \"ngForm\"> {{ gfgform.value | json }} <br> <br> Name: <input type=\"text\" name = 'name' ngModel> Roll: <input type=\"text\" name = 'roll' ngModel></form>", "e": 26181, "s": 26009, "text": null }, { "code": null, "e": 26189, "s": 26181, "text": "Output:" }, { "code": null, "e": 26241, "s": 26189, "text": "Reference: https://angular.io/api/forms/FormsModule" }, { "code": null, "e": 26251, "s": 26241, "text": "Angular10" }, { "code": null, "e": 26272, "s": 26251, "text": "AngularJS-Directives" }, { "code": null, "e": 26282, "s": 26272, "text": "AngularJS" }, { "code": null, "e": 26299, "s": 26282, "text": "Web Technologies" }, { "code": null, "e": 26397, "s": 26299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26406, "s": 26397, "text": "Comments" }, { "code": null, "e": 26419, "s": 26406, "text": "Old Comments" }, { "code": null, "e": 26463, "s": 26419, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26527, "s": 26463, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 26580, "s": 26527, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 26615, "s": 26580, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26639, "s": 26615, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 26672, "s": 26639, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26714, "s": 26672, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26757, "s": 26714, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26819, "s": 26757, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Hibernate Left Join Example | Left Join Hibernate | Hibernate Join Online Tutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, I am going to show you how to work with Hibernate Left Join. The Left Join is a keyword in SQL, which returns all data from the left-hand side table and matching records from the right-hand side table. We can see the NULL values from the right side if there is no match. We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table’s primary key as a child table’s foreign key. For this tutorial, I am going to take the two tables like Customer and Items; these two are having one to many relationship. That means one Customer can have multiple Items. Create customer and item tables with data to apply left join. package com.otp.hibernate.pojo; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "customer") public class Customer { @Id @Column(name = "cid") private int customerId; @Column(name = "cname", length = 15) private String customerName; @Column(name = "ccity", length = 20) private String customerCity; @OneToMany(targetEntity = Item.class, cascade = CascadeType.ALL) @JoinColumn(name = "cid",referencedColumnName="cid") private List items; public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerCity() { return customerCity; } public void setCustomerCity(String customerCity) { this.customerCity = customerCity; } public List getItems() { return items; } public void setItems(List items) { this.items = items; } } Create Item Class package com.otp.hibernate.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="item") public class Item { @Id @Column(name="iid") private int itemId; @Column(name="iname") private String itemName; @Column(name="price") private int price; public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } Create Hibernate Configuration File : <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples</groupId> <artifactId>Hibernate-LeftJoin-Example</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> </dependencies> </project> Create Hibernate Utility Class package com.otp.hibernate.pojo; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtility{ private static SessionFactory factory; private HibernateUtility() { } public synchronized static SessionFactory getSessionFactory() { if (factory == null) { factory = new Configuration().configure("hibernate.cfg.xml") .buildSessionFactory(); } return factory; } @Override protected Object clone() throws CloneNotSupportedException { return new RuntimeException("Clone not Supported"); } } Query For Hibernate Left Join on the above tables, the same will be implemented in below class as hql select query. select c.customerName, c.customerCity, i.itemName,i.price from Customer c left join c.items i; Main.java import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.otp.hibernate.pojo.HibernateUtility; public class Main { public static void main(String[] args) { SessionFactory factory = HibernateUtility.getSessionFactory(); Session session = factory.openSession(); Query qry= session.createQuery("select c.customerName, c.customerCity, i.itemName,i.price from Customer c " + "left join c.items i"); List l = qry.list(); Iterator it=l.iterator(); while(it.hasNext()) { Object rows[] = (Object[])it.next(); System.out.println(rows[0]+ " -- " +rows[1] + "--"+rows[2]+"--"+rows[3]); } session.clear(); session.close(); } } Happy Learning 🙂 Hibernate-LeftJoin-Example File size: 14 KB Downloads: 1169 Hibernate One To Many Using Annotations Basic Hibernate Example with XML Configuration Many to One Mapping in Hibernate Example Hibernate 4 Example with Annotations Mysql Hibernate Table per Class strategy Annotations Example Custom Generator Class in Hibernate Calling Stored Procedures in Hibernate Hibernate Filter Example Xml Configuration Hibernate groupby criteria HQL query Example Hibernate Right Join Example Thread join Example in Java Fork and Join in Java 7 Example What is Hibernate Top 10 Advantages of Hibernate Hibernate session differences between load() and get() Hibernate One To Many Using Annotations Basic Hibernate Example with XML Configuration Many to One Mapping in Hibernate Example Hibernate 4 Example with Annotations Mysql Hibernate Table per Class strategy Annotations Example Custom Generator Class in Hibernate Calling Stored Procedures in Hibernate Hibernate Filter Example Xml Configuration Hibernate groupby criteria HQL query Example Hibernate Right Join Example Thread join Example in Java Fork and Join in Java 7 Example What is Hibernate Top 10 Advantages of Hibernate Hibernate session differences between load() and get() Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 477, "s": 398, "text": "In this tutorial, I am going to show you how to work with Hibernate Left Join." }, { "code": null, "e": 687, "s": 477, "text": "The Left Join is a keyword in SQL, which returns all data from the left-hand side table and matching records from the right-hand side table. We can see the NULL values from the right side if there is no match." }, { "code": null, "e": 982, "s": 687, "text": "We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table’s primary key as a child table’s foreign key." }, { "code": null, "e": 1156, "s": 982, "text": "For this tutorial, I am going to take the two tables like Customer and Items; these two are having one to many relationship. That means one Customer can have multiple Items." }, { "code": null, "e": 1219, "s": 1156, "text": " Create customer and item tables with data to apply left join." }, { "code": null, "e": 2586, "s": 1219, "text": "package com.otp.hibernate.pojo;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"customer\")\npublic class Customer {\n @Id\n @Column(name = \"cid\")\n private int customerId;\n @Column(name = \"cname\", length = 15)\n private String customerName;\n @Column(name = \"ccity\", length = 20)\n private String customerCity;\n\n @OneToMany(targetEntity = Item.class, cascade = CascadeType.ALL)\n @JoinColumn(name = \"cid\",referencedColumnName=\"cid\")\n private List items;\n\n public int getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(int customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public String getCustomerCity() {\n return customerCity;\n }\n\n public void setCustomerCity(String customerCity) {\n this.customerCity = customerCity;\n }\n\n public List getItems() {\n return items;\n }\n\n public void setItems(List items) {\n this.items = items;\n }\n\n}\n" }, { "code": null, "e": 2604, "s": 2586, "text": "Create Item Class" }, { "code": null, "e": 3397, "s": 2604, "text": "package com.otp.hibernate.pojo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name=\"item\")\npublic class Item {\n @Id\n @Column(name=\"iid\")\n private int itemId;\n @Column(name=\"iname\")\n private String itemName;\n @Column(name=\"price\")\n private int price;\n\n public int getItemId() {\n return itemId;\n }\n\n public void setItemId(int itemId) {\n this.itemId = itemId;\n }\n\n public String getItemName() {\n return itemName;\n }\n\n public void setItemName(String itemName) {\n this.itemName = itemName;\n }\n\n public int getPrice() {\n return price;\n }\n\n public void setPrice(int price) {\n this.price = price;\n }\n\n}\n" }, { "code": null, "e": 3435, "s": 3397, "text": "Create Hibernate Configuration File :" }, { "code": null, "e": 4170, "s": 3435, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>org.springframework.samples</groupId>\n <artifactId>Hibernate-LeftJoin-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <dependencies>\n <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-core</artifactId>\n <version>4.3.0.Final</version>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.1.34</version>\n </dependency>\n </dependencies>\n</project>\n" }, { "code": null, "e": 4201, "s": 4170, "text": "Create Hibernate Utility Class" }, { "code": null, "e": 4834, "s": 4201, "text": "package com.otp.hibernate.pojo;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateUtility{\n private static SessionFactory factory;\n\n private HibernateUtility() {\n }\n\n public synchronized static SessionFactory getSessionFactory() {\n if (factory == null) {\n factory = new Configuration().configure(\"hibernate.cfg.xml\")\n .buildSessionFactory();\n }\n return factory;\n }\n\n @Override\n protected Object clone() throws CloneNotSupportedException {\n return new RuntimeException(\"Clone not Supported\");\n }\n\n}\n\n" }, { "code": null, "e": 4950, "s": 4834, "text": "Query For Hibernate Left Join on the above tables, the same will be implemented in below class as hql select query." }, { "code": null, "e": 5046, "s": 4950, "text": " select c.customerName, c.customerCity, i.itemName,i.price from Customer c left join c.items i;" }, { "code": null, "e": 5056, "s": 5046, "text": "Main.java" }, { "code": null, "e": 5902, "s": 5056, "text": "import java.util.Iterator;\nimport java.util.List;\n\nimport org.hibernate.Query;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\n\nimport com.otp.hibernate.pojo.HibernateUtility;\n\npublic class Main {\n\n public static void main(String[] args) {\n SessionFactory factory = HibernateUtility.getSessionFactory();\n Session session = factory.openSession();\n Query qry= session.createQuery(\"select c.customerName, c.customerCity, i.itemName,i.price from Customer c \"\n + \"left join c.items i\");\n List l = qry.list();\n Iterator it=l.iterator();\n while(it.hasNext())\n {\n Object rows[] = (Object[])it.next();\n System.out.println(rows[0]+ \" -- \" +rows[1] + \"--\"+rows[2]+\"--\"+rows[3]);\n }\n session.clear();\n session.close();\n }\n\n}\n" }, { "code": null, "e": 5919, "s": 5902, "text": "Happy Learning 🙂" }, { "code": null, "e": 5983, "s": 5919, "text": "\n\nHibernate-LeftJoin-Example\n\nFile size: 14 KB\nDownloads: 1169\n" }, { "code": null, "e": 6568, "s": 5983, "text": "\nHibernate One To Many Using Annotations\nBasic Hibernate Example with XML Configuration\nMany to One Mapping in Hibernate Example\nHibernate 4 Example with Annotations Mysql\nHibernate Table per Class strategy Annotations Example\nCustom Generator Class in Hibernate\nCalling Stored Procedures in Hibernate\nHibernate Filter Example Xml Configuration\nHibernate groupby criteria HQL query Example\nHibernate Right Join Example\nThread join Example in Java\nFork and Join in Java 7 Example\nWhat is Hibernate\nTop 10 Advantages of Hibernate\nHibernate session differences between load() and get()\n" }, { "code": null, "e": 6608, "s": 6568, "text": "Hibernate One To Many Using Annotations" }, { "code": null, "e": 6655, "s": 6608, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 6696, "s": 6655, "text": "Many to One Mapping in Hibernate Example" }, { "code": null, "e": 6739, "s": 6696, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 6794, "s": 6739, "text": "Hibernate Table per Class strategy Annotations Example" }, { "code": null, "e": 6830, "s": 6794, "text": "Custom Generator Class in Hibernate" }, { "code": null, "e": 6869, "s": 6830, "text": "Calling Stored Procedures in Hibernate" }, { "code": null, "e": 6912, "s": 6869, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 6957, "s": 6912, "text": "Hibernate groupby criteria HQL query Example" }, { "code": null, "e": 6986, "s": 6957, "text": "Hibernate Right Join Example" }, { "code": null, "e": 7015, "s": 6986, "text": "Thread join Example in Java" }, { "code": null, "e": 7047, "s": 7015, "text": "Fork and Join in Java 7 Example" }, { "code": null, "e": 7065, "s": 7047, "text": "What is Hibernate" }, { "code": null, "e": 7096, "s": 7065, "text": "Top 10 Advantages of Hibernate" }, { "code": null, "e": 7151, "s": 7096, "text": "Hibernate session differences between load() and get()" }, { "code": null, "e": 7157, "s": 7155, "text": "Δ" }, { "code": null, "e": 7183, "s": 7157, "text": " Hibernate – Introduction" }, { "code": null, "e": 7207, "s": 7183, "text": " Hibernate – Advantages" }, { "code": null, "e": 7239, "s": 7207, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 7269, "s": 7239, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 7299, "s": 7269, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 7337, "s": 7299, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 7364, "s": 7337, "text": " Hibernate – Object States" }, { "code": null, "e": 7402, "s": 7364, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 7440, "s": 7402, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 7490, "s": 7440, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 7520, "s": 7490, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 7559, "s": 7520, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 7599, "s": 7559, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 7630, "s": 7599, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 7665, "s": 7630, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 7690, "s": 7665, "text": " Hibernate – Named Query" }, { "code": null, "e": 7720, "s": 7690, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 7749, "s": 7720, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 7786, "s": 7749, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 7812, "s": 7786, "text": " Hibernate – Restrictions" }, { "code": null, "e": 7836, "s": 7812, "text": " Hibernate – Projection" }, { "code": null, "e": 7870, "s": 7836, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 7904, "s": 7870, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 7934, "s": 7904, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 7967, "s": 7934, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 7999, "s": 7967, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 8025, "s": 7999, "text": " Hibernate – Update Query" }, { "code": null, "e": 8054, "s": 8025, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 8078, "s": 8054, "text": " Hibernate – Right Join" }, { "code": null, "e": 8101, "s": 8078, "text": " Hibernate – Left Join" }, { "code": null, "e": 8125, "s": 8101, "text": " Hibernate – Pagination" }, { "code": null, "e": 8156, "s": 8125, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 8186, "s": 8156, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 8220, "s": 8186, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 8249, "s": 8220, "text": " Hibernate – Table per Class" }, { "code": null, "e": 8282, "s": 8249, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 8320, "s": 8282, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 8362, "s": 8320, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 8393, "s": 8362, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 8426, "s": 8393, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 8464, "s": 8426, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 8489, "s": 8464, "text": " Hibernate – Interceptor" }, { "code": null, "e": 8535, "s": 8489, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
JavaScript Date setTime() Function - GeeksforGeeks
04 Mar, 2021 The setTime() Function is a BuiltIn Function in Javascript Which is used to get a date object by adding given milliseconds to date 01/01/1970 Syntax: date.setTime(milliseconds) Parameters: setTime() Function takes parameters as follows. milliseconds : Number of milliseconds to add to given date Return Value: The setTime() Function returns milliseconds that you passed in parameter. Example 1: Adding 30000 milliseconds to 01/01/1970 Javascript <!DOCTYPE html><html lang="en"><body> <script> // Initialization let date = new Date(); // Execution let output = date.setTime(30000); // Display Output console.log(`setTime() Output:`, output, date); </script></body></html> Output: Example 2: Adding 2000 milliseconds to 01/01/1970 Javascript <!DOCTYPE html><html lang="en"><body> <script> // Initialization let date = new Date('6-29-2000 03:15:10:50'); // Execution let output = date.setTime(2000); // Display Output console.log(`setTime() Output:`, output, date); </script></body></html> Output: javascript-date javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? 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": 24935, "s": 24907, "text": "\n04 Mar, 2021" }, { "code": null, "e": 25077, "s": 24935, "text": "The setTime() Function is a BuiltIn Function in Javascript Which is used to get a date object by adding given milliseconds to date 01/01/1970" }, { "code": null, "e": 25085, "s": 25077, "text": "Syntax:" }, { "code": null, "e": 25112, "s": 25085, "text": "date.setTime(milliseconds)" }, { "code": null, "e": 25172, "s": 25112, "text": "Parameters: setTime() Function takes parameters as follows." }, { "code": null, "e": 25231, "s": 25172, "text": "milliseconds : Number of milliseconds to add to given date" }, { "code": null, "e": 25319, "s": 25231, "text": "Return Value: The setTime() Function returns milliseconds that you passed in parameter." }, { "code": null, "e": 25370, "s": 25319, "text": "Example 1: Adding 30000 milliseconds to 01/01/1970" }, { "code": null, "e": 25381, "s": 25370, "text": "Javascript" }, { "code": "<!DOCTYPE html><html lang=\"en\"><body> <script> // Initialization let date = new Date(); // Execution let output = date.setTime(30000); // Display Output console.log(`setTime() Output:`, output, date); </script></body></html>", "e": 25658, "s": 25381, "text": null }, { "code": null, "e": 25666, "s": 25658, "text": "Output:" }, { "code": null, "e": 25716, "s": 25666, "text": "Example 2: Adding 2000 milliseconds to 01/01/1970" }, { "code": null, "e": 25727, "s": 25716, "text": "Javascript" }, { "code": "<!DOCTYPE html><html lang=\"en\"><body> <script> // Initialization let date = new Date('6-29-2000 03:15:10:50'); // Execution let output = date.setTime(2000); // Display Output console.log(`setTime() Output:`, output, date); </script></body></html>", "e": 26026, "s": 25727, "text": null }, { "code": null, "e": 26034, "s": 26026, "text": "Output:" }, { "code": null, "e": 26050, "s": 26034, "text": "javascript-date" }, { "code": null, "e": 26071, "s": 26050, "text": "javascript-functions" }, { "code": null, "e": 26082, "s": 26071, "text": "JavaScript" }, { "code": null, "e": 26099, "s": 26082, "text": "Web Technologies" }, { "code": null, "e": 26197, "s": 26099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26206, "s": 26197, "text": "Comments" }, { "code": null, "e": 26219, "s": 26206, "text": "Old Comments" }, { "code": null, "e": 26280, "s": 26219, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26321, "s": 26280, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26375, "s": 26321, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26415, "s": 26375, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26477, "s": 26415, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 26533, "s": 26477, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26566, "s": 26533, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26628, "s": 26566, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26671, "s": 26628, "text": "How to fetch data from an API in ReactJS ?" } ]
How I used Natural Language Processing to extract context from news headlines | by Gunnvant Saini | Towards Data Science
Recently I came across a really amazing dataset at Kaggle (https://www.kaggle.com/therohk/india-headlines-news-dataset). This is one of the rare times, when you get to see data in Indian context. This data is about 2.5 million news headlines published in a national Indian daily called ‘Times of India’. I thought, it would be really nice if I could analyse this data and extract some insights from this data set. Hence one fine evening, I decided to pull out an all nighter gleaning out anything interesting from over 2.5 million news headlines So, I began exploring this dataset. What do you do if you have a lots of text and you want to see what general trends exist in the data? You start with simple word frequencies!!! I ended up counting most common unigrams, bigrams and trigrams and discovering some insights. Below is an instance of very simple frequency of tokens - From this visualization, I could easily figure out that Shah Rukh Khan grabs a lots of headlines and BJP as a political outfit manages to maintain its presence quite prominently along with bollywood stars!!!!! So far so good. This was when I was going to hit a brick wall with my analysis. So, I thought, why not continue creating frequency plots of tokens from different points of view? Hence I posited it would be a good idea if I could create a frequency plot of common bigram tokens across the years? Essentially I wanted to find out most frequent bigram tokens in the year 2001 (This was the first year of data available), then also find the most frequent bigram tokens in the year 2002 and eventually find out the common frequent tokens for years 2001 and 2002. And continue to accumulate these tokens across years. This is the plot I ended with: Here you can see that the most frequent and common bigram over the years is ‘year old’. But what does it mean? In what context was it used? Sadly, frequency plots can only take us thus far. They mostly fail to inform about the context. This was my brick wall! For a moment, I thought, its 2 O’ Clock in the morning let me go to sleep!!!! But then I remembered Randy Pausch : So, I slogged on... And finally it dawned on me.... I won’t lie, I think I dosed off a bit and dreamt of my grammar classes at high school. What kind of information does a Noun or a Verb or an Adjective convey in a given sentence? Are newspaper headlines not sentences? All I then needed to do was filter out all the headlines where the token “year old” occurred and then find out what nouns and verbs co-occur with this token. But how do you do that? The way you accomplish this is by creating a POS (Parts of Speech) tree for each sentence. POS tagging is a standard Natural Language Processing technique. All NLP implementations have this feature. I chose spacy and this is the small code snippet I had to write: index=data['headline_text'].str.match(r'(?=.*\byear\b)(?=.*\bold\b).*$')texts=data['headline_text'].loc[index].tolist()noun=[]verb=[]for doc in nlp.pipe(texts,n_threads=16,batch_size=10000): try: for c in doc: if c.pos_=="NOUN": noun.append(c.text) elif c.pos_=="VERB": verb.append(c.text) except: noun.append("") verb.append("")plt.subplot(1,2,1)pd.Series(noun).value_counts().head(10).plot(kind="bar",figsize=(20,5))plt.title("Top 10 Nouns in context of 'Year Old'",fontsize=30)plt.xticks(size=20,rotation=80)plt.yticks([])plt.subplot(1,2,2)pd.Series(verb).value_counts().head(10).plot(kind="bar",figsize=(20,5))plt.title("Top 10 Verbs in context of 'Year Old'",fontsize=30)plt.xticks(size=20,rotation=80)plt.yticks([] To create this plot: And lo behold!!! I had the context associated with token “Year Old” with me. This token was used in news headlines reporting violent acts/crimes, that too mostly against women. Just to be sure that I was right about my conclusions I looked at the actual news headlines where ‘Year Old’ was mentioned and this is what I saw - ['10-year-old girl missing', 'Relative kills 9-year-old', '59-year-old widow murdered', 'Spunky 60-year-old woman prevents burglary', "75-year-old woman done to death in B'lore", 'Encroachments threaten 900-year-old temple', '3 nabbed for 5-year-old robbery', '25-year-old man electrocuted', '5-year-old boy run over', 'Killers of 88-year-old woman arrested', '21-year-old held in theft case', "60-year-old gets two years' RI for rape attempt", 'STRAIGHT ANSWERSBRSwati Aneja 13 year old schoolgirl on what I Day means to her', 'Robbers stab 9-year-old', "Eight year old's brush with 'commissions'", 'By Ganesha; what 81-year-old Deryck does BEST', 'Six-year-old girl raped; murdered', 'FBI woos 16-year-old indian author', 'Six-year old raped murdered in Patiala cantonment', 'FBI woos 16-year-old Indian author'] Phew!!! That was some work. I continued working on this data set, looking for more such stories. You can view my work in progress on this Kaggle Kernel https://www.kaggle.com/gunnvant/what-india-talks-about-a-visual-essay Don’t forget to clap if you liked this post. Also, if you are on Kaggle, it would be great if you could upvote for my kernel
[ { "code": null, "e": 718, "s": 172, "text": "Recently I came across a really amazing dataset at Kaggle (https://www.kaggle.com/therohk/india-headlines-news-dataset). This is one of the rare times, when you get to see data in Indian context. This data is about 2.5 million news headlines published in a national Indian daily called ‘Times of India’. I thought, it would be really nice if I could analyse this data and extract some insights from this data set. Hence one fine evening, I decided to pull out an all nighter gleaning out anything interesting from over 2.5 million news headlines" }, { "code": null, "e": 1049, "s": 718, "text": "So, I began exploring this dataset. What do you do if you have a lots of text and you want to see what general trends exist in the data? You start with simple word frequencies!!! I ended up counting most common unigrams, bigrams and trigrams and discovering some insights. Below is an instance of very simple frequency of tokens -" }, { "code": null, "e": 1339, "s": 1049, "text": "From this visualization, I could easily figure out that Shah Rukh Khan grabs a lots of headlines and BJP as a political outfit manages to maintain its presence quite prominently along with bollywood stars!!!!! So far so good. This was when I was going to hit a brick wall with my analysis." }, { "code": null, "e": 1902, "s": 1339, "text": "So, I thought, why not continue creating frequency plots of tokens from different points of view? Hence I posited it would be a good idea if I could create a frequency plot of common bigram tokens across the years? Essentially I wanted to find out most frequent bigram tokens in the year 2001 (This was the first year of data available), then also find the most frequent bigram tokens in the year 2002 and eventually find out the common frequent tokens for years 2001 and 2002. And continue to accumulate these tokens across years. This is the plot I ended with:" }, { "code": null, "e": 2240, "s": 1902, "text": "Here you can see that the most frequent and common bigram over the years is ‘year old’. But what does it mean? In what context was it used? Sadly, frequency plots can only take us thus far. They mostly fail to inform about the context. This was my brick wall! For a moment, I thought, its 2 O’ Clock in the morning let me go to sleep!!!!" }, { "code": null, "e": 2277, "s": 2240, "text": "But then I remembered Randy Pausch :" }, { "code": null, "e": 2329, "s": 2277, "text": "So, I slogged on... And finally it dawned on me...." }, { "code": null, "e": 2547, "s": 2329, "text": "I won’t lie, I think I dosed off a bit and dreamt of my grammar classes at high school. What kind of information does a Noun or a Verb or an Adjective convey in a given sentence? Are newspaper headlines not sentences?" }, { "code": null, "e": 2993, "s": 2547, "text": "All I then needed to do was filter out all the headlines where the token “year old” occurred and then find out what nouns and verbs co-occur with this token. But how do you do that? The way you accomplish this is by creating a POS (Parts of Speech) tree for each sentence. POS tagging is a standard Natural Language Processing technique. All NLP implementations have this feature. I chose spacy and this is the small code snippet I had to write:" }, { "code": null, "e": 3805, "s": 2993, "text": "index=data['headline_text'].str.match(r'(?=.*\\byear\\b)(?=.*\\bold\\b).*$')texts=data['headline_text'].loc[index].tolist()noun=[]verb=[]for doc in nlp.pipe(texts,n_threads=16,batch_size=10000): try: for c in doc: if c.pos_==\"NOUN\": noun.append(c.text) elif c.pos_==\"VERB\": verb.append(c.text) except: noun.append(\"\") verb.append(\"\")plt.subplot(1,2,1)pd.Series(noun).value_counts().head(10).plot(kind=\"bar\",figsize=(20,5))plt.title(\"Top 10 Nouns in context of 'Year Old'\",fontsize=30)plt.xticks(size=20,rotation=80)plt.yticks([])plt.subplot(1,2,2)pd.Series(verb).value_counts().head(10).plot(kind=\"bar\",figsize=(20,5))plt.title(\"Top 10 Verbs in context of 'Year Old'\",fontsize=30)plt.xticks(size=20,rotation=80)plt.yticks([]" }, { "code": null, "e": 3826, "s": 3805, "text": "To create this plot:" }, { "code": null, "e": 4003, "s": 3826, "text": "And lo behold!!! I had the context associated with token “Year Old” with me. This token was used in news headlines reporting violent acts/crimes, that too mostly against women." }, { "code": null, "e": 4151, "s": 4003, "text": "Just to be sure that I was right about my conclusions I looked at the actual news headlines where ‘Year Old’ was mentioned and this is what I saw -" }, { "code": null, "e": 4966, "s": 4151, "text": "['10-year-old girl missing', 'Relative kills 9-year-old', '59-year-old widow murdered', 'Spunky 60-year-old woman prevents burglary', \"75-year-old woman done to death in B'lore\", 'Encroachments threaten 900-year-old temple', '3 nabbed for 5-year-old robbery', '25-year-old man electrocuted', '5-year-old boy run over', 'Killers of 88-year-old woman arrested', '21-year-old held in theft case', \"60-year-old gets two years' RI for rape attempt\", 'STRAIGHT ANSWERSBRSwati Aneja 13 year old schoolgirl on what I Day means to her', 'Robbers stab 9-year-old', \"Eight year old's brush with 'commissions'\", 'By Ganesha; what 81-year-old Deryck does BEST', 'Six-year-old girl raped; murdered', 'FBI woos 16-year-old indian author', 'Six-year old raped murdered in Patiala cantonment', 'FBI woos 16-year-old Indian author']" }, { "code": null, "e": 5188, "s": 4966, "text": "Phew!!! That was some work. I continued working on this data set, looking for more such stories. You can view my work in progress on this Kaggle Kernel https://www.kaggle.com/gunnvant/what-india-talks-about-a-visual-essay" } ]
Converting any case to camelCase in JavaScript
We are required to write a JavaScript function that takes in a string, str, which can be any case (normal, snake case, pascal case or any other). Our function should convert this string into camelCase string. For example, if the input to the function is − Input const str = 'New STRING'; Output const output = 'newString'; Following is the code − Live Demo const str = 'New STRING'; const toCamelCase = (str = '') => { return str .replace(/[^a-z0-9]/gi, ' ') .toLowerCase() .split(' ') .map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length)) .join(''); }; console.log(toCamelCase(str)); newString
[ { "code": null, "e": 1208, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string, str, which can be any case\n(normal, snake case, pascal case or any other)." }, { "code": null, "e": 1271, "s": 1208, "text": "Our function should convert this string into camelCase string." }, { "code": null, "e": 1318, "s": 1271, "text": "For example, if the input to the function is −" }, { "code": null, "e": 1324, "s": 1318, "text": "Input" }, { "code": null, "e": 1350, "s": 1324, "text": "const str = 'New STRING';" }, { "code": null, "e": 1357, "s": 1350, "text": "Output" }, { "code": null, "e": 1385, "s": 1357, "text": "const output = 'newString';" }, { "code": null, "e": 1409, "s": 1385, "text": "Following is the code −" }, { "code": null, "e": 1420, "s": 1409, "text": " Live Demo" }, { "code": null, "e": 1712, "s": 1420, "text": "const str = 'New STRING';\nconst toCamelCase = (str = '') => {\n return str\n .replace(/[^a-z0-9]/gi, ' ')\n .toLowerCase()\n .split(' ')\n .map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length))\n .join('');\n};\nconsole.log(toCamelCase(str));" }, { "code": null, "e": 1722, "s": 1712, "text": "newString" } ]
Find the longest common prefix between two strings after performing swaps on second string - GeeksforGeeks
21 May, 2021 Given two strings and . Find the longest common prefix between them after performing zero or more operations on string . In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefix is of length 4. Input : a = "you", b = "me" Output : 0 Given that we are only allowed to performs swaps in the string and the length of prefix should be maximized. So the idea is to traverse string and check if the frequency of current character in string is same or less of that in string . If yes then move forward in string an otherwise break and print the length of the part of string an up to which a character is matched in string .Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the longest// common prefix between two strings// after performing swaps on the second string#include <bits/stdc++.h>using namespace std; void LengthLCP(string x, string y){ int fr[26]={0}; int a = x.length(); // length of x int b = y.length(); // length of y for (int i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y[i] - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i=0 ;i<a ; i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if (fr[x[i] - 97] > 0){ c += 1; fr[x[i] - 97] -= 1; } else break; } cout<<(c)<<endl;}// Driver Codeint main(){string x="here", y = "there"; LengthLCP(x, y); return 0;}//contributed by Arnab Kundu // Java program to find the longest// common prefix between two strings// after performing swaps on the second string public class GFG { static void LengthLCP(String x, String y) { int fr[]=new int [26]; int a = x.length(); // length of x int b = y.length(); // length of y for (int i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y.charAt(i) - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i=0 ;i<a ; i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if (fr[x.charAt(i) - 97] > 0){ c += 1; fr[x.charAt(i) - 97] -= 1; } else break; } System.out.println((c)) ; } public static void main(String args[]) { String x="here", y = "there"; LengthLCP(x, y); } // This code is contributed by ANKITRAI1} # Python program to find the longest# common prefix between two strings# after performing swaps on the second string def LengthLCP(x, y): fr = [0] * 26 a = len(x) # length of x b = len(y) # length of y for i in range(b): # creating frequency array of # characters of y fr[ord(y[i]) - 97] += 1 # storing the length of # longest common prefix c = 0 for i in range(a): # checking if the frequency of the character at # position i in x in b is greater than zero or not # if zero we increase the prefix count by 1 if (fr[ord(x[i]) - 97] > 0): c += 1 fr[ord(x[i]) - 97] -= 1 else: break print(c) # Driver Code x, y = "here", "there" LengthLCP(x, y) // C# program to find the longest// common prefix between two strings// after performing swaps on the// second stringusing System; class GFG{ static void LengthLCP(String x, String y){ int []fr = new int [26]; int a = x.Length; // length of x int b = y.Length; // length of y for (int i = 0 ; i < b; i++) { // creating frequency array // of characters of y fr[y[i] - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i = 0 ; i < a; i++) { // checking if the frequency of // the character at position i // in x in b is greater than zero // or not if zero we increase the // prefix count by 1 if (fr[x[i] - 97] > 0) { c += 1; fr[x[i] - 97] -= 1; } else break; } Console.Write((c)) ;} // Driver Codepublic static void Main(){ String x = "here", y = "there"; LengthLCP(x, y);}} // This code is contributed by 29AjayKumar <?php// PHP program to find the longest// common prefix between two strings// after performing swaps on the second string function LengthLCP($x, $y){ $fr = array_fill(0,26,NULL); $a = strlen($x); // length of x $b = strlen($y); // length of y for ($i = 0 ;$i < $b ; $i++) { // creating frequency array of // characters of y $fr[ord($y[$i]) - 97] += 1; } // storing the length of // longest common prefix $c = 0; for ($i = 0 ;$i < $a ; $i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if ($fr[ord($x[$i]) - 97] > 0) { $c += 1; $fr[ord($x[$i]) - 97] -= 1; } else break; } echo $c;} // Driver Code$x="here";$y = "there"; LengthLCP($x, $y); return 0; // This code is contributed by ChitraNayal?> <script> // JavaScript program to find the long// common prefix between two strings// after performing swaps on the second string function LengthLCP(x, y) { let fr = Array(26).fill(0); let a = x.length; // length of x let b = y.length; // length of y for (let i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y[i].charCodeAt() - 97] += 1; } // storing the length of // longest common prefix let c = 0; for (let i=0 ;i<a ; i++) { // checking if the // frequency of the character at // position i in x in b is greater // than zero or not // if zero we increase the // prefix count by 1 if (fr[x[i].charCodeAt() - 97] > 0){ c += 1; fr[x[i].charCodeAt() - 97] -= 1; } else break; } document.write((c)) ; } // driver code let x="here", y = "there"; LengthLCP(x, y); </script> 4 andrew1234 ankthon 29AjayKumar ukasp target_2 frequency-counting Longest Common Prefix prefix Greedy Python Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum Program for First Fit algorithm in Memory Management Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24903, "s": 24875, "text": "\n21 May, 2021" }, { "code": null, "e": 25084, "s": 24903, "text": "Given two strings and . Find the longest common prefix between them after performing zero or more operations on string . In each operation, you can swap any two letters.Examples: " }, { "code": null, "e": 25275, "s": 25084, "text": "Input : a = \"here\", b = \"there\"\nOutput : 4\nThe 2nd string can be made \"heret\" by just \nswapping characters and thus the longest\nprefix is of length 4.\n\nInput : a = \"you\", b = \"me\"\nOutput : 0" }, { "code": null, "e": 25713, "s": 25277, "text": "Given that we are only allowed to performs swaps in the string and the length of prefix should be maximized. So the idea is to traverse string and check if the frequency of current character in string is same or less of that in string . If yes then move forward in string an otherwise break and print the length of the part of string an up to which a character is matched in string .Below is the implementation of the above approach: " }, { "code": null, "e": 25717, "s": 25713, "text": "C++" }, { "code": null, "e": 25722, "s": 25717, "text": "Java" }, { "code": null, "e": 25730, "s": 25722, "text": "Python3" }, { "code": null, "e": 25733, "s": 25730, "text": "C#" }, { "code": null, "e": 25737, "s": 25733, "text": "PHP" }, { "code": null, "e": 25748, "s": 25737, "text": "Javascript" }, { "code": "// C++ program to find the longest// common prefix between two strings// after performing swaps on the second string#include <bits/stdc++.h>using namespace std; void LengthLCP(string x, string y){ int fr[26]={0}; int a = x.length(); // length of x int b = y.length(); // length of y for (int i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y[i] - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i=0 ;i<a ; i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if (fr[x[i] - 97] > 0){ c += 1; fr[x[i] - 97] -= 1; } else break; } cout<<(c)<<endl;}// Driver Codeint main(){string x=\"here\", y = \"there\"; LengthLCP(x, y); return 0;}//contributed by Arnab Kundu", "e": 26723, "s": 25748, "text": null }, { "code": "// Java program to find the longest// common prefix between two strings// after performing swaps on the second string public class GFG { static void LengthLCP(String x, String y) { int fr[]=new int [26]; int a = x.length(); // length of x int b = y.length(); // length of y for (int i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y.charAt(i) - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i=0 ;i<a ; i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if (fr[x.charAt(i) - 97] > 0){ c += 1; fr[x.charAt(i) - 97] -= 1; } else break; } System.out.println((c)) ; } public static void main(String args[]) { String x=\"here\", y = \"there\"; LengthLCP(x, y); } // This code is contributed by ANKITRAI1} ", "e": 27907, "s": 26723, "text": null }, { "code": "# Python program to find the longest# common prefix between two strings# after performing swaps on the second string def LengthLCP(x, y): fr = [0] * 26 a = len(x) # length of x b = len(y) # length of y for i in range(b): # creating frequency array of # characters of y fr[ord(y[i]) - 97] += 1 # storing the length of # longest common prefix c = 0 for i in range(a): # checking if the frequency of the character at # position i in x in b is greater than zero or not # if zero we increase the prefix count by 1 if (fr[ord(x[i]) - 97] > 0): c += 1 fr[ord(x[i]) - 97] -= 1 else: break print(c) # Driver Code x, y = \"here\", \"there\" LengthLCP(x, y)", "e": 28686, "s": 27907, "text": null }, { "code": "// C# program to find the longest// common prefix between two strings// after performing swaps on the// second stringusing System; class GFG{ static void LengthLCP(String x, String y){ int []fr = new int [26]; int a = x.Length; // length of x int b = y.Length; // length of y for (int i = 0 ; i < b; i++) { // creating frequency array // of characters of y fr[y[i] - 97] += 1; } // storing the length of // longest common prefix int c = 0; for (int i = 0 ; i < a; i++) { // checking if the frequency of // the character at position i // in x in b is greater than zero // or not if zero we increase the // prefix count by 1 if (fr[x[i] - 97] > 0) { c += 1; fr[x[i] - 97] -= 1; } else break; } Console.Write((c)) ;} // Driver Codepublic static void Main(){ String x = \"here\", y = \"there\"; LengthLCP(x, y);}} // This code is contributed by 29AjayKumar", "e": 29722, "s": 28686, "text": null }, { "code": "<?php// PHP program to find the longest// common prefix between two strings// after performing swaps on the second string function LengthLCP($x, $y){ $fr = array_fill(0,26,NULL); $a = strlen($x); // length of x $b = strlen($y); // length of y for ($i = 0 ;$i < $b ; $i++) { // creating frequency array of // characters of y $fr[ord($y[$i]) - 97] += 1; } // storing the length of // longest common prefix $c = 0; for ($i = 0 ;$i < $a ; $i++) { // checking if the frequency of the character at // position i in x in b is greater than zero or not // if zero we increase the prefix count by 1 if ($fr[ord($x[$i]) - 97] > 0) { $c += 1; $fr[ord($x[$i]) - 97] -= 1; } else break; } echo $c;} // Driver Code$x=\"here\";$y = \"there\"; LengthLCP($x, $y); return 0; // This code is contributed by ChitraNayal?>", "e": 30687, "s": 29722, "text": null }, { "code": "<script> // JavaScript program to find the long// common prefix between two strings// after performing swaps on the second string function LengthLCP(x, y) { let fr = Array(26).fill(0); let a = x.length; // length of x let b = y.length; // length of y for (let i=0 ;i<b ; i++) { // creating frequency array of // characters of y fr[y[i].charCodeAt() - 97] += 1; } // storing the length of // longest common prefix let c = 0; for (let i=0 ;i<a ; i++) { // checking if the // frequency of the character at // position i in x in b is greater // than zero or not // if zero we increase the // prefix count by 1 if (fr[x[i].charCodeAt() - 97] > 0){ c += 1; fr[x[i].charCodeAt() - 97] -= 1; } else break; } document.write((c)) ; } // driver code let x=\"here\", y = \"there\"; LengthLCP(x, y); </script>", "e": 31835, "s": 30687, "text": null }, { "code": null, "e": 31837, "s": 31835, "text": "4" }, { "code": null, "e": 31850, "s": 31839, "text": "andrew1234" }, { "code": null, "e": 31858, "s": 31850, "text": "ankthon" }, { "code": null, "e": 31870, "s": 31858, "text": "29AjayKumar" }, { "code": null, "e": 31876, "s": 31870, "text": "ukasp" }, { "code": null, "e": 31885, "s": 31876, "text": "target_2" }, { "code": null, "e": 31904, "s": 31885, "text": "frequency-counting" }, { "code": null, "e": 31926, "s": 31904, "text": "Longest Common Prefix" }, { "code": null, "e": 31933, "s": 31926, "text": "prefix" }, { "code": null, "e": 31940, "s": 31933, "text": "Greedy" }, { "code": null, "e": 31947, "s": 31940, "text": "Python" }, { "code": null, "e": 31954, "s": 31947, "text": "Greedy" }, { "code": null, "e": 32052, "s": 31954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32061, "s": 32052, "text": "Comments" }, { "code": null, "e": 32074, "s": 32061, "text": "Old Comments" }, { "code": null, "e": 32165, "s": 32074, "text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum" }, { "code": null, "e": 32218, "s": 32165, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 32253, "s": 32218, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 32305, "s": 32253, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 32356, "s": 32305, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 32384, "s": 32356, "text": "Read JSON file using Python" }, { "code": null, "e": 32434, "s": 32384, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 32456, "s": 32434, "text": "Python map() function" } ]
Remove Half Nodes | Practice | GeeksforGeeks
Given A binary Tree. Your task is to remove all the half nodes (which has only one child). Example 1: Input: 7 / \ 7 8 / 2 Output: 2 7 8 Example 2: Input: 2 / \ 7 5 \ \ 9 1 / \ 11 4 Output: 11 9 4 2 1 Your Task: You don't need to read input or print anything. Your task is to complete the function RemoveHalfNodes() which takes the root node of the tree as input and returns the root node of the modified tree after removing all the half nodes, ie the ones having just a single child node. (The inorder traversal of the returned tree is printed by the driver's code.) For example consider the below tree. Nodes 7, 5 and 9 are half nodes as one of their child is Null. We need to remove all such half nodes and return the root pointer of following new tree. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Binary Tree). Constraints: 1<=Number of nodes<=104 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 vrajeshmodi991 month ago Accuracy 100% Time Taken 0.2/1.6 void helper(Node*root,Node*prev,string dir){ if(!root)return; if(!root->left && !root->right)return; if(!root->left){ if(dir == "left"){ prev->left = root->right; helper(root->right,prev,"left"); } else if(dir=="right"){ prev->right = root->right; helper(root->right,prev,"right"); } } else if(!root->right){ if(dir == "left"){ prev->left = root->left; helper(root->left,prev,"left"); } else if(dir=="right"){ prev->right = root->left; helper(root->left,prev,"right"); } } if(root->left)helper(root->left,root,"left"); if(root->right)helper(root->right,root,"right"); } Node *RemoveHalfNodes(Node *root) { helper(root->left,root,"left"); helper(root->right,root,"right"); return root; } 0 forcer2 months ago //C++ Node * solve(Node *root) { if(!root) return root; root->left=solve(root->left); root->right=solve(root->right); if(!root->left&&root->right) return root->right; if(root->left&&!root->right) return root->left; return root; } Node *RemoveHalfNodes(Node *root) { //add code here. solve(root); return root; } +1 dhirunand3 months ago class Tree { public static Node RemoveHalfNodes(Node root) { // Code Here if(root == null) return null; if(root.left==null && root.right ==null) return root; if(root.left==null && root.right !=null) return RemoveHalfNodes(root.right); if(root.left!=null && root.right ==null) return RemoveHalfNodes(root.left); root.left = RemoveHalfNodes(root.left); root.right = RemoveHalfNodes(root.right); return root; } } 0 chanduchandrasekhar23563 months ago Node *RemoveHalfNodes(Node *root){ if(!root){ return root; } if(root->left==NULL&&root->right==NULL){ return root; } root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left==NULL&&root->right!=NULL||root->left!=NULL&&root->right==NULL){ return !root->left?root->right:root->left; } return root;} 0 nekhatperveen3 months ago JAVA {if (root == null || (root.left==null && root.right==null)) return root; if (root.left!=null && root.right==null) { return RemoveHalfNodes(root.left); } else if (root.left==null && root.right!=null) { return RemoveHalfNodes(root.right); } else { Node newLeft = RemoveHalfNodes(root.left); Node newRight = RemoveHalfNodes(root.right); root.left = newLeft; root.right = newRight; return root; } } 0 kake13375 months ago Node *RemoveHalfNodes(Node *root){ if(root==NULL) return NULL; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left!=NULL && root->right==NULL) return root->left; if(root->right!=NULL && root->left==NULL) return root->right; return root;} 0 kake1337 This comment was deleted. +1 ariespratyush5 months ago class Tree { // Return the root of the modified tree after removing all the half nodes. public static Node RemoveHalfNodes(Node root) { if(root==null) return root; root.left=RemoveHalfNodes(root.left); root.right=RemoveHalfNodes(root.right); if(root.left!=null&&root.right==null) return root.left; if(root.left==null&&root.right!=null) return root.right; return root; } } 0 dreamvivek65 months ago if(root==NULL) return root; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left==NULL && root->right!=NULL) return root->right; if(root->left!=NULL && root->right==NULL) return root->left; return root; +2 piyushbisht36 months ago Checking two cases for each node -Root left exists , but no root right -Root right exists ,but no root left For either of the above cases we return the corresponding root→left or root→right. If none of the condition follows, we simply return the root. Node *RemoveHalfNodes(Node *root){ if(root==NULL) return NULL; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left && !root->right) { return root->left; } else if(!root->left && root->right) { return root->right; } return root; } 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": 329, "s": 238, "text": "Given A binary Tree. Your task is to remove all the half nodes (which has only one child)." }, { "code": null, "e": 340, "s": 329, "text": "Example 1:" }, { "code": null, "e": 415, "s": 340, "text": "Input:\n 7\n / \\\n 7 8\n / \n 2\nOutput: 2 7 8 \n" }, { "code": null, "e": 426, "s": 415, "text": "Example 2:" }, { "code": null, "e": 549, "s": 426, "text": "Input:\n 2\n / \\\n 7 5\n \\ \\\n 9 1\n / \\\n 11 4\nOutput: 11 9 4 2 1 " }, { "code": null, "e": 954, "s": 549, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function RemoveHalfNodes() which takes the root node of the tree as input and returns the root node of the modified tree after removing all the half nodes, ie the ones having just a single child node. (The inorder traversal of the returned tree is printed by the driver's code.)\nFor example consider the below tree.\n" }, { "code": null, "e": 1106, "s": 954, "text": "Nodes 7, 5 and 9 are half nodes as one of their child is Null. We need to remove all such half nodes and return the root pointer of following new tree." }, { "code": null, "e": 1194, "s": 1106, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Binary Tree)." }, { "code": null, "e": 1231, "s": 1194, "text": "Constraints:\n1<=Number of nodes<=104" }, { "code": null, "e": 1540, "s": 1231, "text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1542, "s": 1540, "text": "0" }, { "code": null, "e": 1567, "s": 1542, "text": "vrajeshmodi991 month ago" }, { "code": null, "e": 1581, "s": 1567, "text": "Accuracy 100%" }, { "code": null, "e": 1600, "s": 1581, "text": "Time Taken 0.2/1.6" }, { "code": null, "e": 2507, "s": 1600, "text": "void helper(Node*root,Node*prev,string dir){\n if(!root)return;\n if(!root->left && !root->right)return;\n if(!root->left){\n if(dir == \"left\"){\n prev->left = root->right;\n helper(root->right,prev,\"left\");\n }\n else if(dir==\"right\"){\n prev->right = root->right;\n helper(root->right,prev,\"right\");\n }\n \n }\n else if(!root->right){\n if(dir == \"left\"){\n prev->left = root->left;\n helper(root->left,prev,\"left\");\n }\n else if(dir==\"right\"){\n prev->right = root->left;\n helper(root->left,prev,\"right\");\n }\n }\n if(root->left)helper(root->left,root,\"left\");\n if(root->right)helper(root->right,root,\"right\");\n \n}\n\nNode *RemoveHalfNodes(Node *root)\n{\n helper(root->left,root,\"left\");\n helper(root->right,root,\"right\");\n return root;\n}" }, { "code": null, "e": 2509, "s": 2507, "text": "0" }, { "code": null, "e": 2528, "s": 2509, "text": "forcer2 months ago" }, { "code": null, "e": 2885, "s": 2528, "text": "//C++\nNode * solve(Node *root)\n{\n if(!root) return root;\n root->left=solve(root->left);\n root->right=solve(root->right);\n if(!root->left&&root->right)\n return root->right;\n if(root->left&&!root->right)\n return root->left;\n \n return root;\n}\nNode *RemoveHalfNodes(Node *root)\n{\n //add code here.\n solve(root);\n return root;\n}" }, { "code": null, "e": 2888, "s": 2885, "text": "+1" }, { "code": null, "e": 2910, "s": 2888, "text": "dhirunand3 months ago" }, { "code": null, "e": 3489, "s": 2910, "text": "class Tree\n{\n public static Node RemoveHalfNodes(Node root)\n {\n // Code Here\n if(root == null)\n return null;\n \n if(root.left==null && root.right ==null)\n return root;\n \n if(root.left==null && root.right !=null)\n return RemoveHalfNodes(root.right);\n \n if(root.left!=null && root.right ==null)\n return RemoveHalfNodes(root.left);\n \n root.left = RemoveHalfNodes(root.left);\n root.right = RemoveHalfNodes(root.right);\n \n return root;\n }\n}" }, { "code": null, "e": 3491, "s": 3489, "text": "0" }, { "code": null, "e": 3527, "s": 3491, "text": "chanduchandrasekhar23563 months ago" }, { "code": null, "e": 3891, "s": 3527, "text": "Node *RemoveHalfNodes(Node *root){ if(!root){ return root; } if(root->left==NULL&&root->right==NULL){ return root; } root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left==NULL&&root->right!=NULL||root->left!=NULL&&root->right==NULL){ return !root->left?root->right:root->left; } return root;}" }, { "code": null, "e": 3893, "s": 3891, "text": "0" }, { "code": null, "e": 3919, "s": 3893, "text": "nekhatperveen3 months ago" }, { "code": null, "e": 3924, "s": 3919, "text": "JAVA" }, { "code": null, "e": 4219, "s": 3924, "text": "{if (root == null || (root.left==null && root.right==null)) return root; if (root.left!=null && root.right==null) { return RemoveHalfNodes(root.left); } else if (root.left==null && root.right!=null) { return RemoveHalfNodes(root.right); } else " }, { "code": null, "e": 4429, "s": 4219, "text": " { Node newLeft = RemoveHalfNodes(root.left); Node newRight = RemoveHalfNodes(root.right); root.left = newLeft; root.right = newRight; return root; }" }, { "code": null, "e": 4431, "s": 4429, "text": "}" }, { "code": null, "e": 4433, "s": 4431, "text": "0" }, { "code": null, "e": 4454, "s": 4433, "text": "kake13375 months ago" }, { "code": null, "e": 4745, "s": 4454, "text": "Node *RemoveHalfNodes(Node *root){ if(root==NULL) return NULL; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left!=NULL && root->right==NULL) return root->left; if(root->right!=NULL && root->left==NULL) return root->right; return root;}" }, { "code": null, "e": 4747, "s": 4745, "text": "0" }, { "code": null, "e": 4756, "s": 4747, "text": "kake1337" }, { "code": null, "e": 4782, "s": 4756, "text": "This comment was deleted." }, { "code": null, "e": 4785, "s": 4782, "text": "+1" }, { "code": null, "e": 4811, "s": 4785, "text": "ariespratyush5 months ago" }, { "code": null, "e": 5258, "s": 4811, "text": "class Tree\n{\n // Return the root of the modified tree after removing all the half nodes.\n public static Node RemoveHalfNodes(Node root)\n {\n if(root==null)\n return root;\n root.left=RemoveHalfNodes(root.left);\n root.right=RemoveHalfNodes(root.right);\n if(root.left!=null&&root.right==null)\n return root.left;\n if(root.left==null&&root.right!=null)\n return root.right;\n return root;\n }\n}" }, { "code": null, "e": 5260, "s": 5258, "text": "0" }, { "code": null, "e": 5284, "s": 5260, "text": "dreamvivek65 months ago" }, { "code": null, "e": 5540, "s": 5284, "text": " if(root==NULL) return root; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left==NULL && root->right!=NULL) return root->right; if(root->left!=NULL && root->right==NULL) return root->left; return root;" }, { "code": null, "e": 5543, "s": 5540, "text": "+2" }, { "code": null, "e": 5568, "s": 5543, "text": "piyushbisht36 months ago" }, { "code": null, "e": 5601, "s": 5568, "text": "Checking two cases for each node" }, { "code": null, "e": 5639, "s": 5601, "text": "-Root left exists , but no root right" }, { "code": null, "e": 5676, "s": 5639, "text": "-Root right exists ,but no root left" }, { "code": null, "e": 5760, "s": 5676, "text": " For either of the above cases we return the corresponding root→left or root→right." }, { "code": null, "e": 5821, "s": 5760, "text": "If none of the condition follows, we simply return the root." }, { "code": null, "e": 6137, "s": 5823, "text": "Node *RemoveHalfNodes(Node *root){ if(root==NULL) return NULL; root->left=RemoveHalfNodes(root->left); root->right=RemoveHalfNodes(root->right); if(root->left && !root->right) { return root->left; } else if(!root->left && root->right) { return root->right; } return root; }" }, { "code": null, "e": 6283, "s": 6137, "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": 6319, "s": 6283, "text": " Login to access your submissions. " }, { "code": null, "e": 6329, "s": 6319, "text": "\nProblem\n" }, { "code": null, "e": 6339, "s": 6329, "text": "\nContest\n" }, { "code": null, "e": 6402, "s": 6339, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6550, "s": 6402, "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": 6758, "s": 6550, "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": 6864, "s": 6758, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to plot multiple graphs in Matplotlib?
To plot multiple graphs in matplotlib, we will use the following steps − Create x, y1 and y2 data points using numpy. Create x, y1 and y2 data points using numpy. Add a subplot to the current figure at index 1. Add a subplot to the current figure at index 1. Plot curve 1 using x and y1. Plot curve 1 using x and y1. Add a subplot to the current figure at index 2. Add a subplot to the current figure at index 2. Plot curve 2 using x and y2. Plot curve 2 using x and y2. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) y1 = np.sin(x) y2 = np.cos(x) plt.subplot(211) plt.plot(y1) plt.subplot(212) plt.plot(y2) plt.show()
[ { "code": null, "e": 1135, "s": 1062, "text": "To plot multiple graphs in matplotlib, we will use the following steps −" }, { "code": null, "e": 1180, "s": 1135, "text": "Create x, y1 and y2 data points using numpy." }, { "code": null, "e": 1225, "s": 1180, "text": "Create x, y1 and y2 data points using numpy." }, { "code": null, "e": 1273, "s": 1225, "text": "Add a subplot to the current figure at index 1." }, { "code": null, "e": 1321, "s": 1273, "text": "Add a subplot to the current figure at index 1." }, { "code": null, "e": 1350, "s": 1321, "text": "Plot curve 1 using x and y1." }, { "code": null, "e": 1379, "s": 1350, "text": "Plot curve 1 using x and y1." }, { "code": null, "e": 1427, "s": 1379, "text": "Add a subplot to the current figure at index 2." }, { "code": null, "e": 1475, "s": 1427, "text": "Add a subplot to the current figure at index 2." }, { "code": null, "e": 1504, "s": 1475, "text": "Plot curve 2 using x and y2." }, { "code": null, "e": 1533, "s": 1504, "text": "Plot curve 2 using x and y2." }, { "code": null, "e": 1575, "s": 1533, "text": "To display the figure, use show() method." }, { "code": null, "e": 1617, "s": 1575, "text": "To display the figure, use show() method." }, { "code": null, "e": 1888, "s": 1617, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 10)\ny1 = np.sin(x)\ny2 = np.cos(x)\nplt.subplot(211)\nplt.plot(y1)\nplt.subplot(212)\nplt.plot(y2)\nplt.show()" } ]
Python Program to Replace all Occurrences of ‘a’ with $ in a String
04 Dec, 2020 Given a string, the task is to write a Python program to replace all occurrence of ‘a’ with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over The first approach uses splitting of the given specified string into a set of characters. An empty string variable is used to store modified string . We loop over the character array and check if the character at this index is equivalent to ‘a’ , and then append ‘$’ sign, in case the condition is satisfied. Otherwise, the original character is copied into the new string. Python3 # declaring a string variablestr = "Amdani athani kharcha rupaiya." # declaring an empty string variable for storing modified stringmodified_str = '' # iterating over the stringfor char in range(0, len(str)): # checking if the character at char index is equivalent to 'a' if(str[char] == 'a'): # append $ to modified string modified_str += '$' else: # append original string character modified_str += str[char] print("Modified string : ")print(modified_str) Output: Modified string : $md$ni $th$ni kh$rch$ rup$iy$. The second approach uses the inbuilt method replace() to replace all the occurrences of a particular character in the string with the new specified character. The method has the following syntax : replace( oldchar , newchar) This method doesn’t change the original string, and the result has to be explicitly stored in the String variable. Python3 # declaring a string variablestr = "An apple A day keeps doctor Away." # replacing character a with $ signstr = str.replace('a', '$')print("Modified string : ")print(str) Output: Modified string : $n $pple $ d$y keeps doctor $w$y. Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 123, "s": 28, "text": "Given a string, the task is to write a Python program to replace all occurrence of ‘a’ with $." }, { "code": null, "e": 133, "s": 123, "text": "Examples:" }, { "code": null, "e": 236, "s": 133, "text": "Input: Ali has all aces\nOutput: $li h$s $ll $ces\n\nInput: All Exams are over\nOutput: $ll Ex$ms $re Over" }, { "code": null, "e": 612, "s": 236, "text": "The first approach uses splitting of the given specified string into a set of characters. An empty string variable is used to store modified string . We loop over the character array and check if the character at this index is equivalent to ‘a’ , and then append ‘$’ sign, in case the condition is satisfied. Otherwise, the original character is copied into the new string. " }, { "code": null, "e": 620, "s": 612, "text": "Python3" }, { "code": "# declaring a string variablestr = \"Amdani athani kharcha rupaiya.\" # declaring an empty string variable for storing modified stringmodified_str = '' # iterating over the stringfor char in range(0, len(str)): # checking if the character at char index is equivalent to 'a' if(str[char] == 'a'): # append $ to modified string modified_str += '$' else: # append original string character modified_str += str[char] print(\"Modified string : \")print(modified_str)", "e": 1118, "s": 620, "text": null }, { "code": null, "e": 1126, "s": 1118, "text": "Output:" }, { "code": null, "e": 1175, "s": 1126, "text": "Modified string :\n$md$ni $th$ni kh$rch$ rup$iy$." }, { "code": null, "e": 1373, "s": 1175, "text": "The second approach uses the inbuilt method replace() to replace all the occurrences of a particular character in the string with the new specified character. The method has the following syntax : " }, { "code": null, "e": 1401, "s": 1373, "text": "replace( oldchar , newchar)" }, { "code": null, "e": 1517, "s": 1401, "text": "This method doesn’t change the original string, and the result has to be explicitly stored in the String variable. " }, { "code": null, "e": 1525, "s": 1517, "text": "Python3" }, { "code": "# declaring a string variablestr = \"An apple A day keeps doctor Away.\" # replacing character a with $ signstr = str.replace('a', '$')print(\"Modified string : \")print(str)", "e": 1697, "s": 1525, "text": null }, { "code": null, "e": 1705, "s": 1697, "text": "Output:" }, { "code": null, "e": 1757, "s": 1705, "text": "Modified string :\n$n $pple $ d$y keeps doctor $w$y." }, { "code": null, "e": 1780, "s": 1757, "text": "Python string-programs" }, { "code": null, "e": 1787, "s": 1780, "text": "Python" }, { "code": null, "e": 1803, "s": 1787, "text": "Python Programs" }, { "code": null, "e": 1901, "s": 1803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1943, "s": 1901, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1965, "s": 1943, "text": "Enumerate() in Python" }, { "code": null, "e": 1997, "s": 1965, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2026, "s": 1997, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2053, "s": 2026, "text": "Python Classes and Objects" }, { "code": null, "e": 2075, "s": 2053, "text": "Defaultdict in Python" }, { "code": null, "e": 2114, "s": 2075, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2152, "s": 2114, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2201, "s": 2152, "text": "Python | Convert string dictionary to dictionary" } ]
Gobuster – Penetration Testing Tools in Kali Tools
18 Jul, 2021 One of the primary steps in attacking an internet application is enumerating hidden directories and files. Doing so can often yield valuable information that makes it easier to execute a particular attack, leaving less room for errors and wasted time. There are many tools available to try to do this, but not all of them are created equally. Gobuster, a record scanner written in Go Language, is worth searching for. In popular directories, brute-force scanners like DirBuster and DIRB work just elegantly but can often be slow and responsive to errors. Gobuster may be a Go implementation of those tools and is obtainable in a convenient command-line format. The primary benefit Gobuster has over other directory scanners is speed. As a programing language, Go is understood to be fast. It also has excellent help for concurrency, so that Gobuster can benefit from multiple threads for quicker processing. The one defeat of Gobuster, though, is the lack of recursive directory exploration. For directories, quite one level deep, another scan is going to be needed, unfortunately. Often, this is not that big of a deal, and other scanners can intensify and fill in the gaps for Gobuster in this area. Step 1: Create a working directory to keep things neat, then change into it. ~# mkdir gobuster ~# cd gobuster/ Step 2: We need to install Gobuster Tool since it is not included on Kali Linux by default. ~/gobuster# apt-get install gobuster Step 3: Then, simply type gobuster into the terminal to run the tool for use. ~/gobuster# gobuster -h Step 4: Installing Additional Seclists for brute-forcing Directories and Files ~/gobuster# apt-get install seclists By default, Wordlists on Kali are located in the /usr/share/wordlists directory. Gobuster tools can be launched from the terminal or command-line interface. You just have to run the command using the syntax below. gobuster [Mode][Options] After entering the “gobuster” command in a terminal, you compulsory need to provide the mode or need to specify the purpose of the tool you are running for. Gobuster tool have many modes : dir – the classic directory brute-forcing mode or Enumerating URIs for directories and files.The Dir mode in Gobuster is mainly used to find extra content in a specific target domain or its subdomain. This additional information can include hidden directories or hidden files that can contain sensitive data. In Dir Mode, we can use the option “-u” to specify the target domain or subdomain you want to dig into the hidden directories and files. Also, the “-w” option will select the wordlist which you wish to use for brute-forcing. dir mode options dns – DNS subdomain brute-forcing mode or Enumerating SubdomainsThe DNS mode in Gobuster Tool is mainly used to enumerate subdomains in the target domain. You can use this mode to find some hidden or unidentifiable subdomains for a given target domain. In this mode, you can use the option “-d” to specify the target domain you want to find subdomain and the “-w” option allows you to select the wordlist you wish to use for brute-forcing. dns mode options vhost – virtual host brute-forcing mode or enumerating virtual hosts (not the same as DNS!)Finally, Vhost mode in Gobuster is used to find the virtual hosts on the victim server. Virtual Hosting is done when companies host several domain names on a single server or cluster of the server. Virtual Hosting allows one server to share its data and resources with several other hostnames. Identifying hostnames on a server can disclose additional web content belonging to a company. In host mode, it checks if the subdomains exist by actually visiting the formed URL and cross checking the IP address. vhost mode options Mostly, you will be using the Gobuster tool for digging directories and files. In this case, dir mode will be helpful for you. gobuster dir [options] After entering the specific mode as per requirement, you have to specify the options. Gobuster tool has a long list of options; to explore them, you can simply read the help page by typing “gobuster -h”. You could use “gobuster dns -h” to explore options that are specifically related to the dns mode). Some examples of options are : -o, –output string Output file to write results to (defaults to stdout)-q, –quiet Don’t print the banner and other noise-t, –threads int Number of concurrent threads (default 10)-v, –verbose Verbose output (errors) -o, –output string Output file to write results to (defaults to stdout) -q, –quiet Don’t print the banner and other noise -t, –threads int Number of concurrent threads (default 10) -v, –verbose Verbose output (errors) gobuster -h option result So, while using the tool, we need to specify the “-u” followed by a target URL, IP address, or a hostname. This option is compulsory, as there is a target specified for getting results. Some of the examples show how to use this option. gobuster dir -u https://www.geeksforgeeks.org/gobuster dir -u https://www.webscantest.comgobuster dir -u 192.168.21.154 gobuster dir -u https://www.geeksforgeeks.org/ gobuster dir -u https://www.webscantest.com gobuster dir -u 192.168.21.154 Note that these examples will not work if the mandatory option “-u” is not specified. Gobuster Tool enumerates hidden directories and files in the target domain by performing a brute-force attack. A brute-force attack consists of matching a list of words or a combination of words hoping that the correct term is present in the list. So, Gobuster performs a brute attack. To force an attack, we need to specify a collection of words, i.e., wordlist. So to provide this wordlist, you need to type the “-w” option, followed by the path of the wordlist where it is located. We can use a wordlist file that is already present in the system. gobuster dir -u https://www.geeksforgeeks.org/ -w /usr/share/wordlists/big.txt Gobuster Tool can enumerate hidden files along with the remote directories. Gobuster allows us to use the “-x” option followed by the file extensions you’d like to search for. Consider the example below: gobuster dir -u https://www.geeksforgeeks.com w /usr/share/wordlists/big.txt -x php,html,htm In this command, we are specifically searching for files that have php,htm or html extensions. Option “-e” is used for completing printing URL when extracting any hidden file or hidden directories. gobuster dir -e -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt –wildcard Obtaining Full Path for a directory or file Using -n Option “no status” mode prints the results’ output without presenting the status code. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -n –wildcard Hide Status Code Gobuster tool constantly adds the banner to define the brief introduction of applied options while launching a brute force attack. By using the -q option, we can disable the flag to hide extra data. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -q –wildcard Disable Banner Using the -t option enables the number of thread parameters to be implemented while brute-forcing sub-domain names or directories. gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt –wildcard Set Thread Number Using the -i option allows the IP parameter, which should show the IPs of selected sub-domains. gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -i –wildcard DNS mode is covered in this command Obtain Sub Domain IPs Using the –timeout option allows the timeout parameter for HTTP requests, and 5 seconds is the default time limit for the HTTP request. gobuster dir –timeout 5s -u geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt –wildcard Timeout I am using the -f option here for appending the forward-slash while making a brute-force attack on the target URL. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -f –wildcard Appending Forward Slash There are many scenarios where we need to extract the directories of a specific extension over the victim server, and then we can use the -X parameter of this scan. This parameter allows the file extension name and then explores the given extension files over the victim server or computer. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -x .php –wildcard Enumerating Directory with Specific Extension List Using -r options allows redirecting the parameters, redirecting HTTP requests to another, and changing the Status code for a directory or file. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -q –wildcard gobuster dir -u geeksforgeeks.org -r -w /usr/share/wordlists/dirb/common.txt -q –wildcard Follow Redirect HTTP Authentication/Authentication mechanisms are all based on the use of 401-status code and WWW-Authenticate response header. The most generally used HTTP authentication mechanisms are Primary. The client sends the user name and password un-encrypted base64 encoded data. So, to avoid this kind of authentication with the help of Gobuster, we have used the command below: gobuster dir -u http://testphp.vulnweb.com/login.php -w /usr/share/wordlists/dirb/common.txt -U test -P test –wildcard HTTP Authorization It ends by obtaining the sub-domain name if it meets any Wildcard DNS, which is a non-existing domain. Therefore, it uses the –wildcard option to allow parameters to continue the attack even if there is any Wildcard Domain. gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt –wildcard Force Processing Brute Force Using the -z option covers the process of obtaining sub-domains names while making brute force attacks. gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -z –wildcard Hide Process of Extraction Using the –cn option enables the CNAME Records parameter of the obtained sub-domains and their CNAME records. gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -c –wildcard Extracting CNAME Records Using the –p option allows proxy URL to be used for all requests; by default, it works on port 1080. As you can see, on examining the victim’s network IP in the web browser, it put up an “Access forbidden error”, which means this web page is operating backwards by some proxy. gobuster dir -p ‘https://18.172.30:3128’ -u ‘http://18.192.172.30/’ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt –wildcard Proxy URL Now that everything is set up and installed, we’re ready to go and use Gobuster. Let’s run it against our victim with the default parameters. Target for Scanning : https://testphp.vulnweb.com Scanning for Directories and Files kali@kali:~$ gobuster dir -u testphp.vulnweb.com -w /usr/share/wordlists/dirb/common.txt From the above screenshot, we are enumerating for directories on https://testphp.vulnweb.com. The wordlist used for the scanning is located at /usr/share/wordlists/dirb/common.txt Going to the current directory which is identified while scanning From the above screenshot, we have identified the admin panel while brute-forcing directories. After opening the web browser and typing the URL of our target, https://testphp.vulnweb.com/ and giving the identified directory /admin/, we will provide the contents available in that directory. Being a Security Researcher, you can test the functionality of that web page. In this article, we learned about Gobuster, a directory brute-force scanner written in the Go programming language. First, we learned how to install the tool and some valuable wordlists not found on Kali by default. Next, we ran it against our target and explored many of the varied options it ships with. Gobuster is a fast and powerful directory scanner that should be an essential part of any hacker’s collection, and now you know how to use it. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction UDP Server-Client implementation in C
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 1230, "s": 28, "text": "One of the primary steps in attacking an internet application is enumerating hidden directories and files. Doing so can often yield valuable information that makes it easier to execute a particular attack, leaving less room for errors and wasted time. There are many tools available to try to do this, but not all of them are created equally. Gobuster, a record scanner written in Go Language, is worth searching for. In popular directories, brute-force scanners like DirBuster and DIRB work just elegantly but can often be slow and responsive to errors. Gobuster may be a Go implementation of those tools and is obtainable in a convenient command-line format. The primary benefit Gobuster has over other directory scanners is speed. As a programing language, Go is understood to be fast. It also has excellent help for concurrency, so that Gobuster can benefit from multiple threads for quicker processing. The one defeat of Gobuster, though, is the lack of recursive directory exploration. For directories, quite one level deep, another scan is going to be needed, unfortunately. Often, this is not that big of a deal, and other scanners can intensify and fill in the gaps for Gobuster in this area." }, { "code": null, "e": 1239, "s": 1230, "text": "Step 1: " }, { "code": null, "e": 1308, "s": 1239, "text": "Create a working directory to keep things neat, then change into it." }, { "code": null, "e": 1342, "s": 1308, "text": "~# mkdir gobuster\n~# cd gobuster/" }, { "code": null, "e": 1351, "s": 1342, "text": "Step 2: " }, { "code": null, "e": 1435, "s": 1351, "text": "We need to install Gobuster Tool since it is not included on Kali Linux by default." }, { "code": null, "e": 1472, "s": 1435, "text": "~/gobuster# apt-get install gobuster" }, { "code": null, "e": 1481, "s": 1472, "text": "Step 3: " }, { "code": null, "e": 1551, "s": 1481, "text": "Then, simply type gobuster into the terminal to run the tool for use." }, { "code": null, "e": 1575, "s": 1551, "text": "~/gobuster# gobuster -h" }, { "code": null, "e": 1583, "s": 1575, "text": "Step 4:" }, { "code": null, "e": 1655, "s": 1583, "text": " Installing Additional Seclists for brute-forcing Directories and Files" }, { "code": null, "e": 1692, "s": 1655, "text": "~/gobuster# apt-get install seclists" }, { "code": null, "e": 1773, "s": 1692, "text": "By default, Wordlists on Kali are located in the /usr/share/wordlists directory." }, { "code": null, "e": 1907, "s": 1773, "text": "Gobuster tools can be launched from the terminal or command-line interface. You just have to run the command using the syntax below." }, { "code": null, "e": 1932, "s": 1907, "text": "gobuster [Mode][Options]" }, { "code": null, "e": 2089, "s": 1932, "text": "After entering the “gobuster” command in a terminal, you compulsory need to provide the mode or need to specify the purpose of the tool you are running for." }, { "code": null, "e": 2121, "s": 2089, "text": "Gobuster tool have many modes :" }, { "code": null, "e": 2656, "s": 2121, "text": "dir – the classic directory brute-forcing mode or Enumerating URIs for directories and files.The Dir mode in Gobuster is mainly used to find extra content in a specific target domain or its subdomain. This additional information can include hidden directories or hidden files that can contain sensitive data. In Dir Mode, we can use the option “-u” to specify the target domain or subdomain you want to dig into the hidden directories and files. Also, the “-w” option will select the wordlist which you wish to use for brute-forcing. " }, { "code": null, "e": 2675, "s": 2658, "text": "dir mode options" }, { "code": null, "e": 3116, "s": 2675, "text": "dns – DNS subdomain brute-forcing mode or Enumerating SubdomainsThe DNS mode in Gobuster Tool is mainly used to enumerate subdomains in the target domain. You can use this mode to find some hidden or unidentifiable subdomains for a given target domain. In this mode, you can use the option “-d” to specify the target domain you want to find subdomain and the “-w” option allows you to select the wordlist you wish to use for brute-forcing. " }, { "code": null, "e": 3133, "s": 3116, "text": "dns mode options" }, { "code": null, "e": 3732, "s": 3133, "text": "vhost – virtual host brute-forcing mode or enumerating virtual hosts (not the same as DNS!)Finally, Vhost mode in Gobuster is used to find the virtual hosts on the victim server. Virtual Hosting is done when companies host several domain names on a single server or cluster of the server. Virtual Hosting allows one server to share its data and resources with several other hostnames. Identifying hostnames on a server can disclose additional web content belonging to a company. In host mode, it checks if the subdomains exist by actually visiting the formed URL and cross checking the IP address. " }, { "code": null, "e": 3751, "s": 3732, "text": "vhost mode options" }, { "code": null, "e": 3878, "s": 3751, "text": "Mostly, you will be using the Gobuster tool for digging directories and files. In this case, dir mode will be helpful for you." }, { "code": null, "e": 3901, "s": 3878, "text": "gobuster dir [options]" }, { "code": null, "e": 4204, "s": 3901, "text": "After entering the specific mode as per requirement, you have to specify the options. Gobuster tool has a long list of options; to explore them, you can simply read the help page by typing “gobuster -h”. You could use “gobuster dns -h” to explore options that are specifically related to the dns mode)." }, { "code": null, "e": 4235, "s": 4204, "text": "Some examples of options are :" }, { "code": null, "e": 4490, "s": 4235, "text": "-o, –output string Output file to write results to (defaults to stdout)-q, –quiet Don’t print the banner and other noise-t, –threads int Number of concurrent threads (default 10)-v, –verbose Verbose output (errors)" }, { "code": null, "e": 4566, "s": 4490, "text": "-o, –output string Output file to write results to (defaults to stdout)" }, { "code": null, "e": 4632, "s": 4566, "text": "-q, –quiet Don’t print the banner and other noise" }, { "code": null, "e": 4699, "s": 4632, "text": "-t, –threads int Number of concurrent threads (default 10)" }, { "code": null, "e": 4748, "s": 4699, "text": "-v, –verbose Verbose output (errors)" }, { "code": null, "e": 4774, "s": 4748, "text": "gobuster -h option result" }, { "code": null, "e": 4960, "s": 4774, "text": "So, while using the tool, we need to specify the “-u” followed by a target URL, IP address, or a hostname. This option is compulsory, as there is a target specified for getting results." }, { "code": null, "e": 5010, "s": 4960, "text": "Some of the examples show how to use this option." }, { "code": null, "e": 5130, "s": 5010, "text": "gobuster dir -u https://www.geeksforgeeks.org/gobuster dir -u https://www.webscantest.comgobuster dir -u 192.168.21.154" }, { "code": null, "e": 5177, "s": 5130, "text": "gobuster dir -u https://www.geeksforgeeks.org/" }, { "code": null, "e": 5221, "s": 5177, "text": "gobuster dir -u https://www.webscantest.com" }, { "code": null, "e": 5252, "s": 5221, "text": "gobuster dir -u 192.168.21.154" }, { "code": null, "e": 5338, "s": 5252, "text": "Note that these examples will not work if the mandatory option “-u” is not specified." }, { "code": null, "e": 5889, "s": 5338, "text": "Gobuster Tool enumerates hidden directories and files in the target domain by performing a brute-force attack. A brute-force attack consists of matching a list of words or a combination of words hoping that the correct term is present in the list. So, Gobuster performs a brute attack. To force an attack, we need to specify a collection of words, i.e., wordlist. So to provide this wordlist, you need to type the “-w” option, followed by the path of the wordlist where it is located. We can use a wordlist file that is already present in the system." }, { "code": null, "e": 5968, "s": 5889, "text": "gobuster dir -u https://www.geeksforgeeks.org/ -w /usr/share/wordlists/big.txt" }, { "code": null, "e": 6144, "s": 5968, "text": "Gobuster Tool can enumerate hidden files along with the remote directories. Gobuster allows us to use the “-x” option followed by the file extensions you’d like to search for." }, { "code": null, "e": 6172, "s": 6144, "text": "Consider the example below:" }, { "code": null, "e": 6265, "s": 6172, "text": "gobuster dir -u https://www.geeksforgeeks.com w /usr/share/wordlists/big.txt -x php,html,htm" }, { "code": null, "e": 6360, "s": 6265, "text": "In this command, we are specifically searching for files that have php,htm or html extensions." }, { "code": null, "e": 6463, "s": 6360, "text": "Option “-e” is used for completing printing URL when extracting any hidden file or hidden directories." }, { "code": null, "e": 6550, "s": 6463, "text": "gobuster dir -e -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt –wildcard" }, { "code": null, "e": 6594, "s": 6550, "text": "Obtaining Full Path for a directory or file" }, { "code": null, "e": 6690, "s": 6594, "text": "Using -n Option “no status” mode prints the results’ output without presenting the status code." }, { "code": null, "e": 6777, "s": 6690, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -n –wildcard" }, { "code": null, "e": 6794, "s": 6777, "text": "Hide Status Code" }, { "code": null, "e": 6993, "s": 6794, "text": "Gobuster tool constantly adds the banner to define the brief introduction of applied options while launching a brute force attack. By using the -q option, we can disable the flag to hide extra data." }, { "code": null, "e": 7081, "s": 6993, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -q –wildcard" }, { "code": null, "e": 7096, "s": 7081, "text": "Disable Banner" }, { "code": null, "e": 7227, "s": 7096, "text": "Using the -t option enables the number of thread parameters to be implemented while brute-forcing sub-domain names or directories." }, { "code": null, "e": 7319, "s": 7227, "text": "gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt –wildcard" }, { "code": null, "e": 7337, "s": 7319, "text": "Set Thread Number" }, { "code": null, "e": 7433, "s": 7337, "text": "Using the -i option allows the IP parameter, which should show the IPs of selected sub-domains." }, { "code": null, "e": 7528, "s": 7433, "text": "gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -i –wildcard" }, { "code": null, "e": 7564, "s": 7528, "text": "DNS mode is covered in this command" }, { "code": null, "e": 7586, "s": 7564, "text": "Obtain Sub Domain IPs" }, { "code": null, "e": 7723, "s": 7586, "text": "Using the –timeout option allows the timeout parameter for HTTP requests, and 5 seconds is the default time limit for the HTTP request. " }, { "code": null, "e": 7826, "s": 7723, "text": "gobuster dir –timeout 5s -u geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt –wildcard" }, { "code": null, "e": 7834, "s": 7826, "text": "Timeout" }, { "code": null, "e": 7949, "s": 7834, "text": "I am using the -f option here for appending the forward-slash while making a brute-force attack on the target URL." }, { "code": null, "e": 8036, "s": 7949, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -f –wildcard" }, { "code": null, "e": 8060, "s": 8036, "text": "Appending Forward Slash" }, { "code": null, "e": 8351, "s": 8060, "text": "There are many scenarios where we need to extract the directories of a specific extension over the victim server, and then we can use the -X parameter of this scan. This parameter allows the file extension name and then explores the given extension files over the victim server or computer." }, { "code": null, "e": 8443, "s": 8351, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -x .php –wildcard" }, { "code": null, "e": 8494, "s": 8443, "text": "Enumerating Directory with Specific Extension List" }, { "code": null, "e": 8638, "s": 8494, "text": "Using -r options allows redirecting the parameters, redirecting HTTP requests to another, and changing the Status code for a directory or file." }, { "code": null, "e": 8725, "s": 8638, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt -q –wildcard" }, { "code": null, "e": 8815, "s": 8725, "text": "gobuster dir -u geeksforgeeks.org -r -w /usr/share/wordlists/dirb/common.txt -q –wildcard" }, { "code": null, "e": 8831, "s": 8815, "text": "Follow Redirect" }, { "code": null, "e": 9105, "s": 8831, "text": "HTTP Authentication/Authentication mechanisms are all based on the use of 401-status code and WWW-Authenticate response header. The most generally used HTTP authentication mechanisms are Primary. The client sends the user name and password un-encrypted base64 encoded data." }, { "code": null, "e": 9205, "s": 9105, "text": "So, to avoid this kind of authentication with the help of Gobuster, we have used the command below:" }, { "code": null, "e": 9324, "s": 9205, "text": "gobuster dir -u http://testphp.vulnweb.com/login.php -w /usr/share/wordlists/dirb/common.txt -U test -P test –wildcard" }, { "code": null, "e": 9343, "s": 9324, "text": "HTTP Authorization" }, { "code": null, "e": 9567, "s": 9343, "text": "It ends by obtaining the sub-domain name if it meets any Wildcard DNS, which is a non-existing domain. Therefore, it uses the –wildcard option to allow parameters to continue the attack even if there is any Wildcard Domain." }, { "code": null, "e": 9652, "s": 9567, "text": "gobuster dir -u geeksforgeeks.org -w /usr/share/wordlists/dirb/common.txt –wildcard" }, { "code": null, "e": 9681, "s": 9652, "text": "Force Processing Brute Force" }, { "code": null, "e": 9785, "s": 9681, "text": "Using the -z option covers the process of obtaining sub-domains names while making brute force attacks." }, { "code": null, "e": 9879, "s": 9785, "text": "gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -z –wildcard" }, { "code": null, "e": 9906, "s": 9879, "text": "Hide Process of Extraction" }, { "code": null, "e": 10016, "s": 9906, "text": "Using the –cn option enables the CNAME Records parameter of the obtained sub-domains and their CNAME records." }, { "code": null, "e": 10110, "s": 10016, "text": "gobuster dns -d geeksforgeeks.org -t 100 -w /usr/share/wordlists/dirb/common.txt -c –wildcard" }, { "code": null, "e": 10135, "s": 10110, "text": "Extracting CNAME Records" }, { "code": null, "e": 10412, "s": 10135, "text": "Using the –p option allows proxy URL to be used for all requests; by default, it works on port 1080. As you can see, on examining the victim’s network IP in the web browser, it put up an “Access forbidden error”, which means this web page is operating backwards by some proxy." }, { "code": null, "e": 10554, "s": 10412, "text": "gobuster dir -p ‘https://18.172.30:3128’ -u ‘http://18.192.172.30/’ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt –wildcard" }, { "code": null, "e": 10564, "s": 10554, "text": "Proxy URL" }, { "code": null, "e": 10706, "s": 10564, "text": "Now that everything is set up and installed, we’re ready to go and use Gobuster. Let’s run it against our victim with the default parameters." }, { "code": null, "e": 10756, "s": 10706, "text": "Target for Scanning : https://testphp.vulnweb.com" }, { "code": null, "e": 10791, "s": 10756, "text": "Scanning for Directories and Files" }, { "code": null, "e": 10880, "s": 10791, "text": "kali@kali:~$ gobuster dir -u testphp.vulnweb.com -w /usr/share/wordlists/dirb/common.txt" }, { "code": null, "e": 10974, "s": 10880, "text": "From the above screenshot, we are enumerating for directories on https://testphp.vulnweb.com." }, { "code": null, "e": 11060, "s": 10974, "text": "The wordlist used for the scanning is located at /usr/share/wordlists/dirb/common.txt" }, { "code": null, "e": 11126, "s": 11060, "text": "Going to the current directory which is identified while scanning" }, { "code": null, "e": 11495, "s": 11126, "text": "From the above screenshot, we have identified the admin panel while brute-forcing directories. After opening the web browser and typing the URL of our target, https://testphp.vulnweb.com/ and giving the identified directory /admin/, we will provide the contents available in that directory. Being a Security Researcher, you can test the functionality of that web page." }, { "code": null, "e": 11944, "s": 11495, "text": "In this article, we learned about Gobuster, a directory brute-force scanner written in the Go programming language. First, we learned how to install the tool and some valuable wordlists not found on Kali by default. Next, we ran it against our target and explored many of the varied options it ships with. Gobuster is a fast and powerful directory scanner that should be an essential part of any hacker’s collection, and now you know how to use it." }, { "code": null, "e": 11955, "s": 11944, "text": "Kali-Linux" }, { "code": null, "e": 11967, "s": 11955, "text": "Linux-Tools" }, { "code": null, "e": 11978, "s": 11967, "text": "Linux-Unix" }, { "code": null, "e": 12076, "s": 11978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12111, "s": 12076, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 12146, "s": 12111, "text": "tar command in Linux with examples" }, { "code": null, "e": 12182, "s": 12146, "text": "curl command in Linux with Examples" }, { "code": null, "e": 12223, "s": 12182, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 12256, "s": 12223, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 12294, "s": 12256, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 12330, "s": 12294, "text": "Tail command in Linux with examples" }, { "code": null, "e": 12368, "s": 12330, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 12394, "s": 12368, "text": "Docker - COPY Instruction" } ]
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
17 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like pandas dropna() method manage and remove Null values from a data frame, fillna() manages and let the user replace NaN values with some value of their own. Syntax: DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) Parameters: value : Static, dictionary, array, series or dataframe to fill instead of NaN.method : Method is used if user doesn’t pass any value. Pandas has different methods like bfill, backfill or ffill which fills the place with value in the Forward index or Previous/Back respectively.axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for Stringinplace: It is a boolean which makes the changes in data frame itself if True.limit : This is an integer value which specifies maximum number of consequetive forward/backward NaN value fills.downcast : It takes a dict which specifies what dtype to downcast to which one. Like Float64 to int64.**kwargs : Any other Keyword arguments For link to CSV file Used in Code, click here. Example #1: Replacing NaN values with a Static value. Before replacing: # importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv("nba.csv") nba Output: After replacing:In the following example, all the null values in College column has been replaced with “No college” string. Firstly, the data frame is imported from CSV and then College column is selected and fillna() method is used on it. # importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv("nba.csv") # replacing na values in college with No collegenba["College"].fillna("No College", inplace = True) nba Output: Example #2: Using method Parameter In the following example, method is set as ffill and hence the value in the same column replaces the null value. In this case Georgia State replaced null value in college column of row 4 and 5.Similarly, bfill, backfill and pad methods can also be used. # importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv("nba.csv") # replacing na values in college with No collegenba["College"].fillna( method ='ffill', inplace = True) nba Output: Example #3: Using Limit In this example, a limit of 1 is set in the fillna() method to check if the function stops replacing after one successful replacement of NaN value or not. # importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv("nba.csv") # replacing na values in college with No collegenba["College"].fillna( method ='ffill', limit = 1, inplace = True) nba Output:As shown in the output, The college column of 4th row was replaced but 5th one wasn’t since the limit was set 1. Python pandas-dataFrame Python pandas-dataFrame-methods python-modules Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Sep, 2018" }, { "code": null, "e": 267, "s": 52, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier." }, { "code": null, "e": 516, "s": 267, "text": "Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like pandas dropna() method manage and remove Null values from a data frame, fillna() manages and let the user replace NaN values with some value of their own." }, { "code": null, "e": 524, "s": 516, "text": "Syntax:" }, { "code": null, "e": 629, "s": 524, "text": "DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)" }, { "code": null, "e": 641, "s": 629, "text": "Parameters:" }, { "code": null, "e": 1372, "s": 641, "text": "value : Static, dictionary, array, series or dataframe to fill instead of NaN.method : Method is used if user doesn’t pass any value. Pandas has different methods like bfill, backfill or ffill which fills the place with value in the Forward index or Previous/Back respectively.axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for Stringinplace: It is a boolean which makes the changes in data frame itself if True.limit : This is an integer value which specifies maximum number of consequetive forward/backward NaN value fills.downcast : It takes a dict which specifies what dtype to downcast to which one. Like Float64 to int64.**kwargs : Any other Keyword arguments" }, { "code": null, "e": 1419, "s": 1372, "text": "For link to CSV file Used in Code, click here." }, { "code": null, "e": 1473, "s": 1419, "text": "Example #1: Replacing NaN values with a Static value." }, { "code": null, "e": 1491, "s": 1473, "text": "Before replacing:" }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv(\"nba.csv\") nba", "e": 1604, "s": 1491, "text": null }, { "code": null, "e": 1612, "s": 1604, "text": "Output:" }, { "code": null, "e": 1852, "s": 1612, "text": "After replacing:In the following example, all the null values in College column has been replaced with “No college” string. Firstly, the data frame is imported from CSV and then College column is selected and fillna() method is used on it." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv(\"nba.csv\") # replacing na values in college with No collegenba[\"College\"].fillna(\"No College\", inplace = True) nba", "e": 2066, "s": 1852, "text": null }, { "code": null, "e": 2075, "s": 2066, "text": "Output: " }, { "code": null, "e": 2110, "s": 2075, "text": "Example #2: Using method Parameter" }, { "code": null, "e": 2364, "s": 2110, "text": "In the following example, method is set as ffill and hence the value in the same column replaces the null value. In this case Georgia State replaced null value in college column of row 4 and 5.Similarly, bfill, backfill and pad methods can also be used." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv(\"nba.csv\") # replacing na values in college with No collegenba[\"College\"].fillna( method ='ffill', inplace = True) nba", "e": 2582, "s": 2364, "text": null }, { "code": null, "e": 2591, "s": 2582, "text": "Output: " }, { "code": null, "e": 2615, "s": 2591, "text": "Example #3: Using Limit" }, { "code": null, "e": 2770, "s": 2615, "text": "In this example, a limit of 1 is set in the fillna() method to check if the function stops replacing after one successful replacement of NaN value or not." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filenba = pd.read_csv(\"nba.csv\") # replacing na values in college with No collegenba[\"College\"].fillna( method ='ffill', limit = 1, inplace = True) nba", "e": 2999, "s": 2770, "text": null }, { "code": null, "e": 3119, "s": 2999, "text": "Output:As shown in the output, The college column of 4th row was replaced but 5th one wasn’t since the limit was set 1." }, { "code": null, "e": 3143, "s": 3119, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3175, "s": 3143, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 3190, "s": 3175, "text": "python-modules" }, { "code": null, "e": 3204, "s": 3190, "text": "Python-pandas" }, { "code": null, "e": 3211, "s": 3204, "text": "Python" }, { "code": null, "e": 3309, "s": 3211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3327, "s": 3309, "text": "Python Dictionary" }, { "code": null, "e": 3369, "s": 3327, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3391, "s": 3369, "text": "Enumerate() in Python" }, { "code": null, "e": 3426, "s": 3391, "text": "Read a file line by line in Python" }, { "code": null, "e": 3452, "s": 3426, "text": "Python String | replace()" }, { "code": null, "e": 3484, "s": 3452, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3513, "s": 3484, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3540, "s": 3513, "text": "Python Classes and Objects" }, { "code": null, "e": 3561, "s": 3540, "text": "Python OOPs Concepts" } ]
Difference between Nested Loop Join and Hash Join
29 Jul, 2020 1. Nested Loop Join :This is a type of physical join algorithm that is used in case of joining 2 relations. This join is an internal join technique, meaning that we cannot see the join. This is the simplest of all types of joins. This is the best-suited algorithm for small data and smaller transactions. In the case of 2 relations named R and S, the algorithm for the Nested Loop join would be as follows : For each record x of R read in, do Use the index on B for S Get all the matching records (having B=x.A) End 2. Hash Join :Hash Join is also a type of physical join algorithm that is used in case of joining two tables internally. The join being an internal join technique means that we cannot see the join. The join selection is done automatically by the query optimizer. The hash join is performed using two steps, the build, and probe. In the case of 2 relations named R and S, the algorithm for Hash join would be as follows : Hash records of R, one by one, using A values (Use the same M buckets and same hash function h) Hash matching pair of records into the same bucket End Difference between Nested Loop Join and Hash Join : DBMS Difference Between DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 SQL Trigger | Student Database Introduction of B-Tree Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2020" }, { "code": null, "e": 436, "s": 28, "text": "1. Nested Loop Join :This is a type of physical join algorithm that is used in case of joining 2 relations. This join is an internal join technique, meaning that we cannot see the join. This is the simplest of all types of joins. This is the best-suited algorithm for small data and smaller transactions. In the case of 2 relations named R and S, the algorithm for the Nested Loop join would be as follows :" }, { "code": null, "e": 544, "s": 436, "text": "For each record x of R read in, do\nUse the index on B for S\nGet all the matching records (having B=x.A)\nEnd" }, { "code": null, "e": 965, "s": 544, "text": "2. Hash Join :Hash Join is also a type of physical join algorithm that is used in case of joining two tables internally. The join being an internal join technique means that we cannot see the join. The join selection is done automatically by the query optimizer. The hash join is performed using two steps, the build, and probe. In the case of 2 relations named R and S, the algorithm for Hash join would be as follows :" }, { "code": null, "e": 1116, "s": 965, "text": "Hash records of R, one by one, using A values\n(Use the same M buckets and same hash function h)\nHash matching pair of records into the same bucket\nEnd" }, { "code": null, "e": 1168, "s": 1116, "text": "Difference between Nested Loop Join and Hash Join :" }, { "code": null, "e": 1173, "s": 1168, "text": "DBMS" }, { "code": null, "e": 1192, "s": 1173, "text": "Difference Between" }, { "code": null, "e": 1197, "s": 1192, "text": "DBMS" }, { "code": null, "e": 1295, "s": 1197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1306, "s": 1295, "text": "CTE in SQL" }, { "code": null, "e": 1359, "s": 1306, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 1417, "s": 1359, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 1448, "s": 1417, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1471, "s": 1448, "text": "Introduction of B-Tree" }, { "code": null, "e": 1511, "s": 1471, "text": "Class method vs Static method in Python" }, { "code": null, "e": 1542, "s": 1511, "text": "Difference between BFS and DFS" }, { "code": null, "e": 1603, "s": 1542, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1671, "s": 1603, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
How to validate GST (Goods and Services Tax) number using Regular Expression
27 Jan, 2021 Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number of the taxpayer.The 13th character (entity code) should be a number from 1-9 or an alphabet.The 14th character should be Z.The 15th character should be an alphabet or a number. It should be 15 characters long. The first 2 characters should be a number. The next 10 characters should be the PAN number of the taxpayer. The 13th character (entity code) should be a number from 1-9 or an alphabet. The 14th character should be Z. The 15th character should be an alphabet or a number. Examples: Input: str = “06BZAHM6385P6Z2”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid GST (Goods and Services Tax) number. Input: str = “06BZAF67”; Output: false Explanation: The given string is not 15 characters long. Therefore, it is not a valid GST (Goods and Services Tax) number. Input: str = “AZBZAHM6385P6Z2”; Output: false Explanation: The given string starts with alphabet. Therefore, it is not a valid GST (Goods and Services Tax) number. Approach: The idea is to use the concept of Regular Expression to solve this problem. The following steps can be followed to compute the answer: Get the String. Create a regular expression to check valid GST (Goods and Services Tax) number as mentioned below: regex = “^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$”; Where: ^ represents the starting of the string.[0-9]{2} represents the first two characters should be a number.[A-Z]{5} represents the next five characters should be any upper case alphabets.[0-9]{4} represents the next four characters should be any number.[A-Z]{1} represents the next character should be any upper case alphabet.[1-9A-Z]{1} represents the 13th character should be a number from 1-9 or an alphabet.Z represents the 14th character should be Z.[0-9A-Z]{1} represents the 15th character should be an alphabet or a number.$ represents the ending of the string. ^ represents the starting of the string. [0-9]{2} represents the first two characters should be a number. [A-Z]{5} represents the next five characters should be any upper case alphabets. [0-9]{4} represents the next four characters should be any number. [A-Z]{1} represents the next character should be any upper case alphabet. [1-9A-Z]{1} represents the 13th character should be a number from 1-9 or an alphabet. Z represents the 14th character should be Z. [0-9A-Z]{1} represents the 15th character should be an alphabet or a number. $ represents the ending of the string. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: Java Python3 C++ // Java program to validate the// GST (Goods and Services Tax) number// using regular expression. import java.util.regex.*; class GFG { // Function to validate // GST (Goods and Services Tax) number. public static boolean isValidGSTNo(String str) { // Regex to check valid // GST (Goods and Services Tax) number String regex = "^[0-9]{2}[A-Z]{5}[0-9]{4}" + "[A-Z]{1}[1-9A-Z]{1}" + "Z[0-9A-Z]{1}$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find the matching // between the given string // and the regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "06BZAHM6385P6Z2"; System.out.println(isValidGSTNo(str1)); // Test Case 2: String str2 = "06BZAF67"; System.out.println(isValidGSTNo(str2)); // Test Case 3: String str3 = "AZBZAHM6385P6Z2"; System.out.println(isValidGSTNo(str3)); // Test Case 4: String str4 = "06BZ63AHM85P6Z2"; System.out.println(isValidGSTNo(str4)); // Test Case 5: String str5 = "06BZAHM6385P6F2"; System.out.println(isValidGSTNo(str5)); }} # Python3 program to validate# GST (Goods and Services Tax) number # using regular expressionimport re # Function to validate GST# (Goods and Services Tax) number.def isValidMasterCardNo(str): # Regex to check valid # GST (Goods and Services Tax) number regex = "^[0-9]{2}[A-Z]{5}[0-9]{4}" + "[A-Z]{1}[1-9A-Z]{1}" + "Z[0-9A-Z]{1}$" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "06BZAHM6385P6Z2"print(isValidMasterCardNo(str1)) # Test Case 2:str2 = "06BZAF67"print(isValidMasterCardNo(str2)) # Test Case 3:str3 = "AZBZAHM6385P6Z2"print(isValidMasterCardNo(str3)) # Test Case 4:str4 = "06BZ63AHM85P6Z2"print(isValidMasterCardNo(str4)) # Test Case 5:str5 = "06BZAHM6385P6F2"print(isValidMasterCardNo(str5)) # This code is contributed by avanitrachhadiya2155 // C++ program to validate the// GST (Goods and Services Tax) number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the GST// (Goods and Services Tax) numberbool isValidGSTNo(string str){ // Regex to check valid GST // (Goods and Services Tax) number const regex pattern("^[0-9]{2}[A-Z]{5}" "[0-9]{4}[A-Z]{1}[" "1-9A-Z]{1}Z[0-9A-Z]{1}$"); // If the GST (Goods and Services Tax) // number is empty return false if (str.empty()) { return false; } // Return true if the GST number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "06BZAHM6385P6Z2"; cout << isValidGSTNo(str1) << endl; // Test Case 2: string str2 = "06BZAF67"; cout << isValidGSTNo(str2) << endl; // Test Case 3: string str3 = "AZBZAHM6385P6Z2"; cout << isValidGSTNo(str3) << endl; // Test Case 4: string str4 = "06BZ63AHM85P6Z2"; cout << isValidGSTNo(str4) << endl; // Test Case 5: string str5 = "06BZAHM6385P6F2"; cout << isValidGSTNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra true false false false false avanitrachhadiya2155 yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2021" }, { "code": null, "e": 258, "s": 28, "text": "Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: " }, { "code": null, "e": 557, "s": 258, "text": "It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number of the taxpayer.The 13th character (entity code) should be a number from 1-9 or an alphabet.The 14th character should be Z.The 15th character should be an alphabet or a number." }, { "code": null, "e": 590, "s": 557, "text": "It should be 15 characters long." }, { "code": null, "e": 633, "s": 590, "text": "The first 2 characters should be a number." }, { "code": null, "e": 698, "s": 633, "text": "The next 10 characters should be the PAN number of the taxpayer." }, { "code": null, "e": 775, "s": 698, "text": "The 13th character (entity code) should be a number from 1-9 or an alphabet." }, { "code": null, "e": 807, "s": 775, "text": "The 14th character should be Z." }, { "code": null, "e": 861, "s": 807, "text": "The 15th character should be an alphabet or a number." }, { "code": null, "e": 872, "s": 861, "text": "Examples: " }, { "code": null, "e": 1055, "s": 872, "text": "Input: str = “06BZAHM6385P6Z2”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid GST (Goods and Services Tax) number." }, { "code": null, "e": 1217, "s": 1055, "text": "Input: str = “06BZAF67”; Output: false Explanation: The given string is not 15 characters long. Therefore, it is not a valid GST (Goods and Services Tax) number." }, { "code": null, "e": 1382, "s": 1217, "text": "Input: str = “AZBZAHM6385P6Z2”; Output: false Explanation: The given string starts with alphabet. Therefore, it is not a valid GST (Goods and Services Tax) number. " }, { "code": null, "e": 1528, "s": 1382, "text": "Approach: The idea is to use the concept of Regular Expression to solve this problem. The following steps can be followed to compute the answer: " }, { "code": null, "e": 1544, "s": 1528, "text": "Get the String." }, { "code": null, "e": 1643, "s": 1544, "text": "Create a regular expression to check valid GST (Goods and Services Tax) number as mentioned below:" }, { "code": null, "e": 1713, "s": 1643, "text": "regex = “^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$”; " }, { "code": null, "e": 2287, "s": 1713, "text": "Where: ^ represents the starting of the string.[0-9]{2} represents the first two characters should be a number.[A-Z]{5} represents the next five characters should be any upper case alphabets.[0-9]{4} represents the next four characters should be any number.[A-Z]{1} represents the next character should be any upper case alphabet.[1-9A-Z]{1} represents the 13th character should be a number from 1-9 or an alphabet.Z represents the 14th character should be Z.[0-9A-Z]{1} represents the 15th character should be an alphabet or a number.$ represents the ending of the string." }, { "code": null, "e": 2328, "s": 2287, "text": "^ represents the starting of the string." }, { "code": null, "e": 2393, "s": 2328, "text": "[0-9]{2} represents the first two characters should be a number." }, { "code": null, "e": 2474, "s": 2393, "text": "[A-Z]{5} represents the next five characters should be any upper case alphabets." }, { "code": null, "e": 2541, "s": 2474, "text": "[0-9]{4} represents the next four characters should be any number." }, { "code": null, "e": 2615, "s": 2541, "text": "[A-Z]{1} represents the next character should be any upper case alphabet." }, { "code": null, "e": 2701, "s": 2615, "text": "[1-9A-Z]{1} represents the 13th character should be a number from 1-9 or an alphabet." }, { "code": null, "e": 2746, "s": 2701, "text": "Z represents the 14th character should be Z." }, { "code": null, "e": 2823, "s": 2746, "text": "[0-9A-Z]{1} represents the 15th character should be an alphabet or a number." }, { "code": null, "e": 2862, "s": 2823, "text": "$ represents the ending of the string." }, { "code": null, "e": 2968, "s": 2862, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 3056, "s": 2968, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 3107, "s": 3056, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3112, "s": 3107, "text": "Java" }, { "code": null, "e": 3120, "s": 3112, "text": "Python3" }, { "code": null, "e": 3124, "s": 3120, "text": "C++" }, { "code": "// Java program to validate the// GST (Goods and Services Tax) number// using regular expression. import java.util.regex.*; class GFG { // Function to validate // GST (Goods and Services Tax) number. public static boolean isValidGSTNo(String str) { // Regex to check valid // GST (Goods and Services Tax) number String regex = \"^[0-9]{2}[A-Z]{5}[0-9]{4}\" + \"[A-Z]{1}[1-9A-Z]{1}\" + \"Z[0-9A-Z]{1}$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find the matching // between the given string // and the regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = \"06BZAHM6385P6Z2\"; System.out.println(isValidGSTNo(str1)); // Test Case 2: String str2 = \"06BZAF67\"; System.out.println(isValidGSTNo(str2)); // Test Case 3: String str3 = \"AZBZAHM6385P6Z2\"; System.out.println(isValidGSTNo(str3)); // Test Case 4: String str4 = \"06BZ63AHM85P6Z2\"; System.out.println(isValidGSTNo(str4)); // Test Case 5: String str5 = \"06BZAHM6385P6F2\"; System.out.println(isValidGSTNo(str5)); }}", "e": 4699, "s": 3124, "text": null }, { "code": "# Python3 program to validate# GST (Goods and Services Tax) number # using regular expressionimport re # Function to validate GST# (Goods and Services Tax) number.def isValidMasterCardNo(str): # Regex to check valid # GST (Goods and Services Tax) number regex = \"^[0-9]{2}[A-Z]{5}[0-9]{4}\" + \"[A-Z]{1}[1-9A-Z]{1}\" + \"Z[0-9A-Z]{1}$\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"06BZAHM6385P6Z2\"print(isValidMasterCardNo(str1)) # Test Case 2:str2 = \"06BZAF67\"print(isValidMasterCardNo(str2)) # Test Case 3:str3 = \"AZBZAHM6385P6Z2\"print(isValidMasterCardNo(str3)) # Test Case 4:str4 = \"06BZ63AHM85P6Z2\"print(isValidMasterCardNo(str4)) # Test Case 5:str5 = \"06BZAHM6385P6F2\"print(isValidMasterCardNo(str5)) # This code is contributed by avanitrachhadiya2155", "e": 5741, "s": 4699, "text": null }, { "code": "// C++ program to validate the// GST (Goods and Services Tax) number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the GST// (Goods and Services Tax) numberbool isValidGSTNo(string str){ // Regex to check valid GST // (Goods and Services Tax) number const regex pattern(\"^[0-9]{2}[A-Z]{5}\" \"[0-9]{4}[A-Z]{1}[\" \"1-9A-Z]{1}Z[0-9A-Z]{1}$\"); // If the GST (Goods and Services Tax) // number is empty return false if (str.empty()) { return false; } // Return true if the GST number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"06BZAHM6385P6Z2\"; cout << isValidGSTNo(str1) << endl; // Test Case 2: string str2 = \"06BZAF67\"; cout << isValidGSTNo(str2) << endl; // Test Case 3: string str3 = \"AZBZAHM6385P6Z2\"; cout << isValidGSTNo(str3) << endl; // Test Case 4: string str4 = \"06BZ63AHM85P6Z2\"; cout << isValidGSTNo(str4) << endl; // Test Case 5: string str5 = \"06BZAHM6385P6F2\"; cout << isValidGSTNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 7043, "s": 5741, "text": null }, { "code": null, "e": 7073, "s": 7043, "text": "true\nfalse\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 7094, "s": 7073, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7109, "s": 7094, "text": "yuvraj_chandra" }, { "code": null, "e": 7119, "s": 7109, "text": "CPP-regex" }, { "code": null, "e": 7143, "s": 7119, "text": "java-regular-expression" }, { "code": null, "e": 7162, "s": 7143, "text": "regular-expression" }, { "code": null, "e": 7180, "s": 7162, "text": "Pattern Searching" }, { "code": null, "e": 7188, "s": 7180, "text": "Strings" }, { "code": null, "e": 7196, "s": 7188, "text": "Strings" }, { "code": null, "e": 7214, "s": 7196, "text": "Pattern Searching" } ]
How to place content under fixed flexbox navigation bar ?
05 Jun, 2020 Navigation bar: With CSS, you can change HTML menus into astonishing navigation bars. Navigation bar is nothing but the list of links. A navigation bar needs standard HTML as a base. By using <ul> and <li> components makes idealize sense. We can place Content in the fixed navigation bar by two methods as follows: Method 1: Using float in CSSSyntax:float: none | left | right | initial | inherit;Property Values:none: It will not influence the position of content (This is default). left: Content will float to the left of its container. right: Content will float to the right of its container. initial: Sets this property to its default value.inherit: Acquires this property from its parent component.Fixed Navigation Bar: We can include CSS and can make the navigation bar remain at the top of the foot of the page, indeed when the user scrolls the page:Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); position: fixed; /* position property is used to fix navbar */ top: 0; width: 100%; } li { float: left; /* when flexbox will be used then there will be no need to write float properties of CSS*/ } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <ul> <li> <a class="active" href="#home">Home</a> </li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> <div style="padding: 20px; margin-top: 30px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;">GeeksforGeeks</h1> <h1>Fixed Top Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output:Note: position:absolute; to the content ignores the float property. List-style-type: none; is utilized to expel the bullets. A navigation bar does not require list markers. Set margin: 0; and padding: 0; to expel browser default settings. Method 1: Using float in CSS Syntax: float: none | left | right | initial | inherit; Property Values: none: It will not influence the position of content (This is default). left: Content will float to the left of its container. right: Content will float to the right of its container. initial: Sets this property to its default value. inherit: Acquires this property from its parent component. Fixed Navigation Bar: We can include CSS and can make the navigation bar remain at the top of the foot of the page, indeed when the user scrolls the page: Example: <!DOCTYPE html><html> <head> <style> body { margin: 0; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); position: fixed; /* position property is used to fix navbar */ top: 0; width: 100%; } li { float: left; /* when flexbox will be used then there will be no need to write float properties of CSS*/ } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <ul> <li> <a class="active" href="#home">Home</a> </li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> <div style="padding: 20px; margin-top: 30px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;">GeeksforGeeks</h1> <h1>Fixed Top Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html> Output: Note: position:absolute; to the content ignores the float property. List-style-type: none; is utilized to expel the bullets. A navigation bar does not require list markers. Set margin: 0; and padding: 0; to expel browser default settings. Method 2: Using Flexbox in CSSFlexbox Flexbox could be an amazing layout device. By utilizing flexbox we are able to set content into columns and many more. We’ll shortly go through the properties of the flexbox. (You can use this following syntax in code and play with it!)Properties of flexbox for flex container: (property:values;)display: flex;flex-direction: row | row-reverse | column | column-reverse;flex-wrap: wrap | nowrap | wrap-reverse;flex-flow: column wrap;justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly | start | end | left | right;align-items: stretch | flex-start | flex-end | center | start | end | baseline | first baseline | last baseline | self-start | self-end;align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline;Properties of flexbox for flex items: (property:values;)order: 4; /* default is 0 */flex-grow: 2; /* default 0 */flex-shrink: 5; /* default 1 */flex-basis: auto; /* default auto */flex: none; (It is shorthand property for flex-grow, flex-shrink and flex-basis combined (Ex. flex: 0 1 auto;) by default)align-self: auto | center | baseline | flex-start | flex-end | stretch;**Note that float, clear and vertical-align do no effect on a flex item. Also the use of negative numbers is prohibited .How to create fixed flexbox navigation bar?/* Modify the header(above we modified ul and li instead of header)*/ header { display: flex; /* using flexbox property for parent also known as inline-flex*/ justify-content: space-between; align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } In this Example, display: flex; utilizing flexbox property for parent moreover known as inline-flex. justify-content: space-between; things are evenly dispersed within the line; firstitem is on the begin line, final thing on the conclusion line. But in this illustration we styled header tag consequently this impact may not be seen. But on the off chance that we styled ul tag this impact will be seen.order: 1; The arrange property controls the order in which they show up within the flex holder. By default order is 0;Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { display: flex; /* Using flexbox property for parent also known as inline-flex */ justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line*/ align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } nav { order: 1; } .nav_links { list-style: none; } .nav_links li { display: inline-block; padding: 0px 20px; } .nav_links li a:hover { color: rgb(255, 255, 255); } li a { display: block; color: white; text-align: center; padding: 5px 5px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <header> <nav> <ul class="nav_links"> <li><a class="active" href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> </nav> </header> <div style="padding: 20px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;"> <br /> GeeksforGeeks </h1> <h1>Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output: Method 2: Using Flexbox in CSS Flexbox Flexbox could be an amazing layout device. By utilizing flexbox we are able to set content into columns and many more. We’ll shortly go through the properties of the flexbox. (You can use this following syntax in code and play with it!) Properties of flexbox for flex container: (property:values;) display: flex; flex-direction: row | row-reverse | column | column-reverse; flex-wrap: wrap | nowrap | wrap-reverse; flex-flow: column wrap; justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly | start | end | left | right; align-items: stretch | flex-start | flex-end | center | start | end | baseline | first baseline | last baseline | self-start | self-end; align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline; Properties of flexbox for flex items: (property:values;) order: 4; /* default is 0 */ flex-grow: 2; /* default 0 */ flex-shrink: 5; /* default 1 */ flex-basis: auto; /* default auto */ flex: none; (It is shorthand property for flex-grow, flex-shrink and flex-basis combined (Ex. flex: 0 1 auto;) by default) align-self: auto | center | baseline | flex-start | flex-end | stretch; **Note that float, clear and vertical-align do no effect on a flex item. Also the use of negative numbers is prohibited . How to create fixed flexbox navigation bar? /* Modify the header(above we modified ul and li instead of header)*/ header { display: flex; /* using flexbox property for parent also known as inline-flex*/ justify-content: space-between; align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } In this Example, display: flex; utilizing flexbox property for parent moreover known as inline-flex. justify-content: space-between; things are evenly dispersed within the line; firstitem is on the begin line, final thing on the conclusion line. But in this illustration we styled header tag consequently this impact may not be seen. But on the off chance that we styled ul tag this impact will be seen. order: 1; The arrange property controls the order in which they show up within the flex holder. By default order is 0; Example: <!DOCTYPE html><html> <head> <style> body { margin: 0; } header { display: flex; /* Using flexbox property for parent also known as inline-flex */ justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line*/ align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } nav { order: 1; } .nav_links { list-style: none; } .nav_links li { display: inline-block; padding: 0px 20px; } .nav_links li a:hover { color: rgb(255, 255, 255); } li a { display: block; color: white; text-align: center; padding: 5px 5px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <header> <nav> <ul class="nav_links"> <li><a class="active" href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> </nav> </header> <div style="padding: 20px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;"> <br /> GeeksforGeeks </h1> <h1>Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html> Output: How to place content under fixed flexbox navigation bar?Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line */ padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } .bar { display: flex; /* Use flexbox property for parent also known as inline-flex */ align-items: center; } .search { /* Take up the rest of the remaining space */ flex: 1; } .search input { width: 90%; } nav { order: 1; } </style> </head> <body> <header> <nav> <div class="bar"> <div class="username" style="color: rgb(255, 255, 255); font-size: 30px;"> Search here : </div> <div class="search"> <input type="search" placeholder="search..." /> </div> </div> </nav> </header> <div style="padding: 20px; background-color: rgba( 135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;"> <br /> GeeksforGeeks </h1> <h1>Content in Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output: How to place content under fixed flexbox navigation bar? Example: <!DOCTYPE html><html> <head> <style> body { margin: 0; } header { justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line */ padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } .bar { display: flex; /* Use flexbox property for parent also known as inline-flex */ align-items: center; } .search { /* Take up the rest of the remaining space */ flex: 1; } .search input { width: 90%; } nav { order: 1; } </style> </head> <body> <header> <nav> <div class="bar"> <div class="username" style="color: rgb(255, 255, 255); font-size: 30px;"> Search here : </div> <div class="search"> <input type="search" placeholder="search..." /> </div> </div> </nav> </header> <div style="padding: 20px; background-color: rgba( 135, 206, 235, 0.5); height: 1500px;"> <h1 style="color: green;"> <br /> GeeksforGeeks </h1> <h1>Content in Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html> Output: CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 267, "s": 28, "text": "Navigation bar: With CSS, you can change HTML menus into astonishing navigation bars. Navigation bar is nothing but the list of links. A navigation bar needs standard HTML as a base. By using <ul> and <li> components makes idealize sense." }, { "code": null, "e": 343, "s": 267, "text": "We can place Content in the fixed navigation bar by two methods as follows:" }, { "code": null, "e": 4821, "s": 343, "text": "Method 1: Using float in CSSSyntax:float: none | left | right | initial | inherit;Property Values:none: It will not influence the position of content (This is default). left: Content will float to the left of its container. right: Content will float to the right of its container. initial: Sets this property to its default value.inherit: Acquires this property from its parent component.Fixed Navigation Bar: We can include CSS and can make the navigation bar remain at the top of the foot of the page, indeed when the user scrolls the page:Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); position: fixed; /* position property is used to fix navbar */ top: 0; width: 100%; } li { float: left; /* when flexbox will be used then there will be no need to write float properties of CSS*/ } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <ul> <li> <a class=\"active\" href=\"#home\">Home</a> </li> <li><a href=\"#news\">News</a></li> <li><a href=\"#contact\">Contact</a></li> <li><a href=\"#about\">About</a></li> </ul> <div style=\"padding: 20px; margin-top: 30px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h1>Fixed Top Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output:Note: position:absolute; to the content ignores the float property. List-style-type: none; is utilized to expel the bullets. A navigation bar does not require list markers. Set margin: 0; and padding: 0; to expel browser default settings." }, { "code": null, "e": 4850, "s": 4821, "text": "Method 1: Using float in CSS" }, { "code": null, "e": 4858, "s": 4850, "text": "Syntax:" }, { "code": null, "e": 4906, "s": 4858, "text": "float: none | left | right | initial | inherit;" }, { "code": null, "e": 4923, "s": 4906, "text": "Property Values:" }, { "code": null, "e": 4995, "s": 4923, "text": "none: It will not influence the position of content (This is default). " }, { "code": null, "e": 5052, "s": 4995, "text": "left: Content will float to the left of its container. " }, { "code": null, "e": 5111, "s": 5052, "text": "right: Content will float to the right of its container. " }, { "code": null, "e": 5161, "s": 5111, "text": "initial: Sets this property to its default value." }, { "code": null, "e": 5220, "s": 5161, "text": "inherit: Acquires this property from its parent component." }, { "code": null, "e": 5375, "s": 5220, "text": "Fixed Navigation Bar: We can include CSS and can make the navigation bar remain at the top of the foot of the page, indeed when the user scrolls the page:" }, { "code": null, "e": 5384, "s": 5375, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { margin: 0; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); position: fixed; /* position property is used to fix navbar */ top: 0; width: 100%; } li { float: left; /* when flexbox will be used then there will be no need to write float properties of CSS*/ } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <ul> <li> <a class=\"active\" href=\"#home\">Home</a> </li> <li><a href=\"#news\">News</a></li> <li><a href=\"#contact\">Contact</a></li> <li><a href=\"#about\">About</a></li> </ul> <div style=\"padding: 20px; margin-top: 30px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h1>Fixed Top Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>", "e": 9064, "s": 5384, "text": null }, { "code": null, "e": 9072, "s": 9064, "text": "Output:" }, { "code": null, "e": 9142, "s": 9072, "text": "Note: position:absolute; to the content ignores the float property. " }, { "code": null, "e": 9248, "s": 9142, "text": "List-style-type: none; is utilized to expel the bullets. A navigation bar does not require list markers. " }, { "code": null, "e": 9314, "s": 9248, "text": "Set margin: 0; and padding: 0; to expel browser default settings." }, { "code": null, "e": 15822, "s": 9314, "text": "Method 2: Using Flexbox in CSSFlexbox Flexbox could be an amazing layout device. By utilizing flexbox we are able to set content into columns and many more. We’ll shortly go through the properties of the flexbox. (You can use this following syntax in code and play with it!)Properties of flexbox for flex container: (property:values;)display: flex;flex-direction: row | row-reverse | column | column-reverse;flex-wrap: wrap | nowrap | wrap-reverse;flex-flow: column wrap;justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly | start | end | left | right;align-items: stretch | flex-start | flex-end | center | start | end | baseline | first baseline | last baseline | self-start | self-end;align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline;Properties of flexbox for flex items: (property:values;)order: 4; /* default is 0 */flex-grow: 2; /* default 0 */flex-shrink: 5; /* default 1 */flex-basis: auto; /* default auto */flex: none; (It is shorthand property for flex-grow, flex-shrink and flex-basis combined (Ex. flex: 0 1 auto;) by default)align-self: auto | center | baseline | flex-start | flex-end | stretch;**Note that float, clear and vertical-align do no effect on a flex item. Also the use of negative numbers is prohibited .How to create fixed flexbox navigation bar?/* Modify the header(above we modified \n ul and li instead of header)*/ \nheader {\n display: flex; \n /* using flexbox property for parent\n also known as inline-flex*/ \n justify-content: space-between;\n align-items: center;\n padding: 5px;\n position: fixed;\n overflow: hidden;\n background-color: rgba(0, 0, 0, 0.7);\n width: 100%;\n}\nIn this Example, display: flex; utilizing flexbox property for parent moreover known as inline-flex. justify-content: space-between; things are evenly dispersed within the line; firstitem is on the begin line, final thing on the conclusion line. But in this illustration we styled header tag consequently this impact may not be seen. But on the off chance that we styled ul tag this impact will be seen.order: 1; The arrange property controls the order in which they show up within the flex holder. By default order is 0;Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { display: flex; /* Using flexbox property for parent also known as inline-flex */ justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line*/ align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } nav { order: 1; } .nav_links { list-style: none; } .nav_links li { display: inline-block; padding: 0px 20px; } .nav_links li a:hover { color: rgb(255, 255, 255); } li a { display: block; color: white; text-align: center; padding: 5px 5px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <header> <nav> <ul class=\"nav_links\"> <li><a class=\"active\" href=\"#home\">Home</a></li> <li><a href=\"#news\">News</a></li> <li><a href=\"#contact\">Contact</a></li> <li><a href=\"#about\">About</a></li> </ul> </nav> </header> <div style=\"padding: 20px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\"> <br /> GeeksforGeeks </h1> <h1>Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output:" }, { "code": null, "e": 15853, "s": 15822, "text": "Method 2: Using Flexbox in CSS" }, { "code": null, "e": 16098, "s": 15853, "text": "Flexbox Flexbox could be an amazing layout device. By utilizing flexbox we are able to set content into columns and many more. We’ll shortly go through the properties of the flexbox. (You can use this following syntax in code and play with it!)" }, { "code": null, "e": 16159, "s": 16098, "text": "Properties of flexbox for flex container: (property:values;)" }, { "code": null, "e": 16174, "s": 16159, "text": "display: flex;" }, { "code": null, "e": 16235, "s": 16174, "text": "flex-direction: row | row-reverse | column | column-reverse;" }, { "code": null, "e": 16276, "s": 16235, "text": "flex-wrap: wrap | nowrap | wrap-reverse;" }, { "code": null, "e": 16300, "s": 16276, "text": "flex-flow: column wrap;" }, { "code": null, "e": 16424, "s": 16300, "text": "justify-content: flex-start | flex-end | center | space-around | space-between | space-evenly | start | end | left | right;" }, { "code": null, "e": 16561, "s": 16424, "text": "align-items: stretch | flex-start | flex-end | center | start | end | baseline | first baseline | last baseline | self-start | self-end;" }, { "code": null, "e": 16722, "s": 16561, "text": "align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline;" }, { "code": null, "e": 16779, "s": 16722, "text": "Properties of flexbox for flex items: (property:values;)" }, { "code": null, "e": 16830, "s": 16779, "text": "order: 4; /* default is 0 */" }, { "code": null, "e": 16875, "s": 16830, "text": "flex-grow: 2; /* default 0 */" }, { "code": null, "e": 16920, "s": 16875, "text": "flex-shrink: 5; /* default 1 */" }, { "code": null, "e": 16966, "s": 16920, "text": "flex-basis: auto; /* default auto */" }, { "code": null, "e": 17089, "s": 16966, "text": "flex: none; (It is shorthand property for flex-grow, flex-shrink and flex-basis combined (Ex. flex: 0 1 auto;) by default)" }, { "code": null, "e": 17161, "s": 17089, "text": "align-self: auto | center | baseline | flex-start | flex-end | stretch;" }, { "code": null, "e": 17283, "s": 17161, "text": "**Note that float, clear and vertical-align do no effect on a flex item. Also the use of negative numbers is prohibited ." }, { "code": null, "e": 17327, "s": 17283, "text": "How to create fixed flexbox navigation bar?" }, { "code": null, "e": 17675, "s": 17327, "text": "/* Modify the header(above we modified \n ul and li instead of header)*/ \nheader {\n display: flex; \n /* using flexbox property for parent\n also known as inline-flex*/ \n justify-content: space-between;\n align-items: center;\n padding: 5px;\n position: fixed;\n overflow: hidden;\n background-color: rgba(0, 0, 0, 0.7);\n width: 100%;\n}\n" }, { "code": null, "e": 17694, "s": 17675, "text": "In this Example, " }, { "code": null, "e": 17780, "s": 17694, "text": "display: flex; utilizing flexbox property for parent moreover known as inline-flex. " }, { "code": null, "e": 18083, "s": 17780, "text": "justify-content: space-between; things are evenly dispersed within the line; firstitem is on the begin line, final thing on the conclusion line. But in this illustration we styled header tag consequently this impact may not be seen. But on the off chance that we styled ul tag this impact will be seen." }, { "code": null, "e": 18202, "s": 18083, "text": "order: 1; The arrange property controls the order in which they show up within the flex holder. By default order is 0;" }, { "code": null, "e": 18211, "s": 18202, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { display: flex; /* Using flexbox property for parent also known as inline-flex */ justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line*/ align-items: center; padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } nav { order: 1; } .nav_links { list-style: none; } .nav_links li { display: inline-block; padding: 0px 20px; } .nav_links li a:hover { color: rgb(255, 255, 255); } li a { display: block; color: white; text-align: center; padding: 5px 5px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #4caf50; } </style> </head> <body> <header> <nav> <ul class=\"nav_links\"> <li><a class=\"active\" href=\"#home\">Home</a></li> <li><a href=\"#news\">News</a></li> <li><a href=\"#contact\">Contact</a></li> <li><a href=\"#about\">About</a></li> </ul> </nav> </header> <div style=\"padding: 20px; background-color: rgba(135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\"> <br /> GeeksforGeeks </h1> <h1>Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>", "e": 22348, "s": 18211, "text": null }, { "code": null, "e": 22356, "s": 22348, "text": "Output:" }, { "code": null, "e": 26323, "s": 22356, "text": "How to place content under fixed flexbox navigation bar?Example:<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line */ padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } .bar { display: flex; /* Use flexbox property for parent also known as inline-flex */ align-items: center; } .search { /* Take up the rest of the remaining space */ flex: 1; } .search input { width: 90%; } nav { order: 1; } </style> </head> <body> <header> <nav> <div class=\"bar\"> <div class=\"username\" style=\"color: rgb(255, 255, 255); font-size: 30px;\"> Search here : </div> <div class=\"search\"> <input type=\"search\" placeholder=\"search...\" /> </div> </div> </nav> </header> <div style=\"padding: 20px; background-color: rgba( 135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\"> <br /> GeeksforGeeks </h1> <h1>Content in Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>Output:" }, { "code": null, "e": 26380, "s": 26323, "text": "How to place content under fixed flexbox navigation bar?" }, { "code": null, "e": 26389, "s": 26380, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { margin: 0; } header { justify-content: space-between; /* Items are evenly distributed in the line; firstitem is on the start line, last item on the end line */ padding: 5px; position: fixed; overflow: hidden; background-color: rgba(0, 0, 0, 0.7); width: 100%; } .bar { display: flex; /* Use flexbox property for parent also known as inline-flex */ align-items: center; } .search { /* Take up the rest of the remaining space */ flex: 1; } .search input { width: 90%; } nav { order: 1; } </style> </head> <body> <header> <nav> <div class=\"bar\"> <div class=\"username\" style=\"color: rgb(255, 255, 255); font-size: 30px;\"> Search here : </div> <div class=\"search\"> <input type=\"search\" placeholder=\"search...\" /> </div> </div> </nav> </header> <div style=\"padding: 20px; background-color: rgba( 135, 206, 235, 0.5); height: 1500px;\"> <h1 style=\"color: green;\"> <br /> GeeksforGeeks </h1> <h1>Content in Fixed Flexbox Navigation Bar</h1> <h2>Scroll Scroll Scroll......</h2> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> <p>Write Something Write Something Write Something Write Something..</p> </div> </body></html>", "e": 30285, "s": 26389, "text": null }, { "code": null, "e": 30293, "s": 30285, "text": "Output:" }, { "code": null, "e": 30302, "s": 30293, "text": "CSS-Misc" }, { "code": null, "e": 30312, "s": 30302, "text": "HTML-Misc" }, { "code": null, "e": 30319, "s": 30312, "text": "Picked" }, { "code": null, "e": 30323, "s": 30319, "text": "CSS" }, { "code": null, "e": 30328, "s": 30323, "text": "HTML" }, { "code": null, "e": 30345, "s": 30328, "text": "Web Technologies" }, { "code": null, "e": 30372, "s": 30345, "text": "Web technologies Questions" }, { "code": null, "e": 30377, "s": 30372, "text": "HTML" }, { "code": null, "e": 30475, "s": 30377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30514, "s": 30475, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 30553, "s": 30514, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30592, "s": 30553, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 30629, "s": 30592, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30658, "s": 30629, "text": "Form validation using jQuery" }, { "code": null, "e": 30682, "s": 30658, "text": "REST API (Introduction)" }, { "code": null, "e": 30735, "s": 30682, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30795, "s": 30735, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30856, "s": 30795, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Getting the time since OS startup using Python
16 Jun, 2021 Uptime is the time elapsed since the Operating system started. Operating systems have discrete mechanisms to keep track of this time, which they further utilize for performing OS related tasks. This time is particularly useful for certain applications such as:- Usage Tracking Applications Backup Applications Antivirus Applications In this article, we will take a look at methods of getting the time since OS startup of different operating systems. Getting Uptime on MAC OS and Linux For Mac OS and Linux users, the method is very trivial. There exists an inbuilt command offered by the terminal of the OS, which allows for the extraction of the uptime. We would be integrating that command-line method into our Python program. Python3 # for using os.popen()import os # sending the uptime command as an argument to popen()# and saving the returned result (after truncating the trailing \n)t = os.popen('uptime -p').read()[:-1] print(t) Output Up 6 minutes Things to consider while using the above code: It is not necessary for the user to use os.popen(). It is just required to invoke the command-line interpreter, and therefore any other methods/functions leading to the same result (subprocess etc) could be used instead of it. The -p after the uptime command is to prettify the output, otherwise, the output contains way too much unwanted information. GETTING UPTIME ON WINDOWS OS For Windows, we would be using an inbuilt API function found in Windows OS under the name gettickcount64(). This function retrieves the number of milliseconds that have elapsed since the system was started. Python3 # ctypes required for using GetTickCount64()import ctypes # getting the library in which GetTickCount64() resideslib = ctypes.windll.kernel32 # calling the function and storing the return valuet = lib.GetTickCount64() # since the time is in milliseconds i.e. 1000 * seconds# therefore truncating the valuet = int(str(t)[:-3]) # extracting hours, minutes, seconds & days from t# variable (which stores total time in seconds)mins, sec = divmod(t, 60)hour, mins = divmod(mins, 60)days, hour = divmod(hour, 24) # formatting the time in readable form# (format = x days, HH:MM:SS)print(f"{days} days, {hour:02}:{mins:02}:{sec:02}") Output 0 days, 3:09:04 The above output states, that this system is running for 3 hours, 9 minutes, and 4 seconds (0 days). If the system would be used for more than one day (or hours = 24+) then the hours will roll back to 0, and the days will be incremented. Things to consider while running the above code: gettickcount64() does not work properly if hybrid sleep is enabled as a turn off mechanism on your OS. The program will only work on python version >= 3.x, because of the inclusion of f-strings. For using this on python 2, change the f strings to str.format() or % formatting. gettickcount64() does include time elapsed during hibernation or sleep. simranarora5sos Python os-module-programs python-os-module python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 290, "s": 28, "text": "Uptime is the time elapsed since the Operating system started. Operating systems have discrete mechanisms to keep track of this time, which they further utilize for performing OS related tasks. This time is particularly useful for certain applications such as:-" }, { "code": null, "e": 318, "s": 290, "text": "Usage Tracking Applications" }, { "code": null, "e": 338, "s": 318, "text": "Backup Applications" }, { "code": null, "e": 361, "s": 338, "text": "Antivirus Applications" }, { "code": null, "e": 480, "s": 361, "text": " In this article, we will take a look at methods of getting the time since OS startup of different operating systems. " }, { "code": null, "e": 515, "s": 480, "text": "Getting Uptime on MAC OS and Linux" }, { "code": null, "e": 759, "s": 515, "text": "For Mac OS and Linux users, the method is very trivial. There exists an inbuilt command offered by the terminal of the OS, which allows for the extraction of the uptime. We would be integrating that command-line method into our Python program." }, { "code": null, "e": 767, "s": 759, "text": "Python3" }, { "code": "# for using os.popen()import os # sending the uptime command as an argument to popen()# and saving the returned result (after truncating the trailing \\n)t = os.popen('uptime -p').read()[:-1] print(t)", "e": 967, "s": 767, "text": null }, { "code": null, "e": 975, "s": 967, "text": "Output " }, { "code": null, "e": 989, "s": 975, "text": " Up 6 minutes" }, { "code": null, "e": 1036, "s": 989, "text": "Things to consider while using the above code:" }, { "code": null, "e": 1263, "s": 1036, "text": "It is not necessary for the user to use os.popen(). It is just required to invoke the command-line interpreter, and therefore any other methods/functions leading to the same result (subprocess etc) could be used instead of it." }, { "code": null, "e": 1388, "s": 1263, "text": "The -p after the uptime command is to prettify the output, otherwise, the output contains way too much unwanted information." }, { "code": null, "e": 1417, "s": 1388, "text": "GETTING UPTIME ON WINDOWS OS" }, { "code": null, "e": 1625, "s": 1417, "text": "For Windows, we would be using an inbuilt API function found in Windows OS under the name gettickcount64(). This function retrieves the number of milliseconds that have elapsed since the system was started. " }, { "code": null, "e": 1633, "s": 1625, "text": "Python3" }, { "code": "# ctypes required for using GetTickCount64()import ctypes # getting the library in which GetTickCount64() resideslib = ctypes.windll.kernel32 # calling the function and storing the return valuet = lib.GetTickCount64() # since the time is in milliseconds i.e. 1000 * seconds# therefore truncating the valuet = int(str(t)[:-3]) # extracting hours, minutes, seconds & days from t# variable (which stores total time in seconds)mins, sec = divmod(t, 60)hour, mins = divmod(mins, 60)days, hour = divmod(hour, 24) # formatting the time in readable form# (format = x days, HH:MM:SS)print(f\"{days} days, {hour:02}:{mins:02}:{sec:02}\")", "e": 2259, "s": 1633, "text": null }, { "code": null, "e": 2270, "s": 2263, "text": "Output" }, { "code": null, "e": 2289, "s": 2272, "text": " 0 days, 3:09:04" }, { "code": null, "e": 2530, "s": 2291, "text": "The above output states, that this system is running for 3 hours, 9 minutes, and 4 seconds (0 days). If the system would be used for more than one day (or hours = 24+) then the hours will roll back to 0, and the days will be incremented. " }, { "code": null, "e": 2581, "s": 2532, "text": "Things to consider while running the above code:" }, { "code": null, "e": 2687, "s": 2583, "text": "gettickcount64() does not work properly if hybrid sleep is enabled as a turn off mechanism on your OS." }, { "code": null, "e": 2861, "s": 2687, "text": "The program will only work on python version >= 3.x, because of the inclusion of f-strings. For using this on python 2, change the f strings to str.format() or % formatting." }, { "code": null, "e": 2934, "s": 2861, "text": "gettickcount64() does include time elapsed during hibernation or sleep. " }, { "code": null, "e": 2952, "s": 2936, "text": "simranarora5sos" }, { "code": null, "e": 2978, "s": 2952, "text": "Python os-module-programs" }, { "code": null, "e": 2995, "s": 2978, "text": "python-os-module" }, { "code": null, "e": 3010, "s": 2995, "text": "python-utility" }, { "code": null, "e": 3017, "s": 3010, "text": "Python" }, { "code": null, "e": 3115, "s": 3017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3133, "s": 3115, "text": "Python Dictionary" }, { "code": null, "e": 3175, "s": 3133, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3201, "s": 3175, "text": "Python String | replace()" }, { "code": null, "e": 3233, "s": 3201, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3262, "s": 3233, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3289, "s": 3262, "text": "Python Classes and Objects" }, { "code": null, "e": 3325, "s": 3289, "text": "Convert integer to string in Python" }, { "code": null, "e": 3356, "s": 3325, "text": "Python | os.path.join() method" }, { "code": null, "e": 3393, "s": 3356, "text": "Create a Pandas DataFrame from Lists" } ]
Length of direct common tangent between two intersecting Circles
07 Jun, 2022 Given two circles, of given radii, have there centres a given distance apart, such that the circles intersect each other at two points. The task is to find the length of the direct common tangent between the circles.Examples: Input: r1 = 4, r2 = 6, d = 3 Output: 2.23607 Input: r1 = 14, r2 = 43, d = 35 Output: 19.5959 Approach: Let the radii of the circles be r1 & r2 respectively. Let the distance between the centers be d units. Draw a line OR parallel to PQ angle OPQ = 90 deg angle O’QP = 90 deg { line joining the centre of the circle to the point of contact makes an angle of 90 degrees with the tangent } angle OPQ + angle O’QP = 180 deg OP || QR Since opposite sides are parallel and interior angles are 90, therefore OPQR is a rectangle. So OP = QR = r1 and PQ = OR = d In triangle OO’Rangle ORO’ = 90 By Pythagoras theoremOR^2 + O’R^2 = (OO’^2) OR^2 + (r1-r2)^2 = d^2 so, OR^2= d^2-(r1-r2)^2 OR = √{d^2-(r1-r2)^2} Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find// the length of the direct// common tangent between two circles// which intersect each other#include <bits/stdc++.h>using namespace std; // Function to find the length of the direct common tangentvoid lengtang(double r1, double r2, double d){ cout << "The length of the direct" <<" common tangent is " << sqrt(pow(d, 2) - pow((r1 - r2), 2)) << endl;} // Driver codeint main(){ double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); return 0;} // Java program to find// the length of the direct// common tangent between two circles// which intersect each otherclass GFG{ // Function to find the length of // the direct common tangent static void lengtang(double r1, double r2, double d) { System.out.println("The length of the direct" + " common tangent is " + (Math.sqrt(Math.pow(d, 2) - Math.pow((r1 - r2), 2)))); } // Driver code public static void main(String[] args) { double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); }} /* This code contributed by PrinciRaj1992 */ # Python program to find# the length of the direct# common tangent between two circles# which intersect each other # Function to find the length of# the direct common tangentdef lengtang(r1, r2, d): print("The length of the direct common tangent is " ,((d** 2) - ((r1 - r2)** 2))**(1/2)); # Driver coder1 = 4; r2 = 6; d = 3;lengtang(r1, r2, d); # This code has been contributed by 29AjayKumar // C# program to find// the length of the direct// common tangent between two circles// which intersect each otherusing System; class GFG{ // Function to find the length of // the direct common tangent static void lengtang(double r1, double r2, double d) { Console.WriteLine("The length of the direct" + " common tangent is " + (Math.Sqrt(Math.Pow(d, 2) - Math.Pow((r1 - r2), 2)))); } // Driver code public static void Main(String[] args) { double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to find// the length of the direct// common tangent between two circles// which intersect each other // Function to find the length of// the direct common tangentfunction lengtang($r1, $r2, $d){ echo "The length of the direct common tangent is " ,sqrt(pow($d, 2) - pow(($r1 - $r2), 2)) ;} // Driver code$r1 = 4; $r2 = 6; $d = 3;lengtang($r1, $r2, $d); // This code is contributed by AnkitRai01?> <script> // javascript program to find// the length of the direct// common tangent between two circles// which intersect each other // Function to find the length of// the direct common tangentfunction lengtang(r1 , r2 , d){ document.write("The length of the direct" + " common tangent is " + (Math.sqrt(Math.pow(d, 2) - Math.pow((r1 - r2), 2))).toFixed(5));} // Driver codevar r1 = 4, r2 = 6, d = 3;lengtang(r1, r2, d); // This code contributed by Princi Singh </script> The length of the direct common tangent is 2.23607 Time Complexity: O(1) Auxiliary Space: O(1) princiraj1992 ankthon 29AjayKumar princi singh souravkumar29 circle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2022" }, { "code": null, "e": 256, "s": 28, "text": "Given two circles, of given radii, have there centres a given distance apart, such that the circles intersect each other at two points. The task is to find the length of the direct common tangent between the circles.Examples: " }, { "code": null, "e": 352, "s": 256, "text": "Input: r1 = 4, r2 = 6, d = 3 \nOutput: 2.23607\n\nInput: r1 = 14, r2 = 43, d = 35\nOutput: 19.5959" }, { "code": null, "e": 365, "s": 354, "text": "Approach: " }, { "code": null, "e": 419, "s": 365, "text": "Let the radii of the circles be r1 & r2 respectively." }, { "code": null, "e": 470, "s": 421, "text": "Let the distance between the centers be d units." }, { "code": null, "e": 502, "s": 472, "text": "Draw a line OR parallel to PQ" }, { "code": null, "e": 655, "s": 504, "text": "angle OPQ = 90 deg angle O’QP = 90 deg { line joining the centre of the circle to the point of contact makes an angle of 90 degrees with the tangent }" }, { "code": null, "e": 699, "s": 657, "text": "angle OPQ + angle O’QP = 180 deg OP || QR" }, { "code": null, "e": 794, "s": 701, "text": "Since opposite sides are parallel and interior angles are 90, therefore OPQR is a rectangle." }, { "code": null, "e": 828, "s": 796, "text": "So OP = QR = r1 and PQ = OR = d" }, { "code": null, "e": 929, "s": 830, "text": "In triangle OO’Rangle ORO’ = 90 By Pythagoras theoremOR^2 + O’R^2 = (OO’^2) OR^2 + (r1-r2)^2 = d^2" }, { "code": null, "e": 979, "s": 931, "text": "so, OR^2= d^2-(r1-r2)^2 OR = √{d^2-(r1-r2)^2} " }, { "code": null, "e": 1031, "s": 979, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1035, "s": 1031, "text": "C++" }, { "code": null, "e": 1040, "s": 1035, "text": "Java" }, { "code": null, "e": 1048, "s": 1040, "text": "Python3" }, { "code": null, "e": 1051, "s": 1048, "text": "C#" }, { "code": null, "e": 1055, "s": 1051, "text": "PHP" }, { "code": null, "e": 1066, "s": 1055, "text": "Javascript" }, { "code": "// C++ program to find// the length of the direct// common tangent between two circles// which intersect each other#include <bits/stdc++.h>using namespace std; // Function to find the length of the direct common tangentvoid lengtang(double r1, double r2, double d){ cout << \"The length of the direct\" <<\" common tangent is \" << sqrt(pow(d, 2) - pow((r1 - r2), 2)) << endl;} // Driver codeint main(){ double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); return 0;}", "e": 1564, "s": 1066, "text": null }, { "code": "// Java program to find// the length of the direct// common tangent between two circles// which intersect each otherclass GFG{ // Function to find the length of // the direct common tangent static void lengtang(double r1, double r2, double d) { System.out.println(\"The length of the direct\" + \" common tangent is \" + (Math.sqrt(Math.pow(d, 2) - Math.pow((r1 - r2), 2)))); } // Driver code public static void main(String[] args) { double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); }} /* This code contributed by PrinciRaj1992 */", "e": 2192, "s": 1564, "text": null }, { "code": "# Python program to find# the length of the direct# common tangent between two circles# which intersect each other # Function to find the length of# the direct common tangentdef lengtang(r1, r2, d): print(\"The length of the direct common tangent is \" ,((d** 2) - ((r1 - r2)** 2))**(1/2)); # Driver coder1 = 4; r2 = 6; d = 3;lengtang(r1, r2, d); # This code has been contributed by 29AjayKumar", "e": 2598, "s": 2192, "text": null }, { "code": "// C# program to find// the length of the direct// common tangent between two circles// which intersect each otherusing System; class GFG{ // Function to find the length of // the direct common tangent static void lengtang(double r1, double r2, double d) { Console.WriteLine(\"The length of the direct\" + \" common tangent is \" + (Math.Sqrt(Math.Pow(d, 2) - Math.Pow((r1 - r2), 2)))); } // Driver code public static void Main(String[] args) { double r1 = 4, r2 = 6, d = 3; lengtang(r1, r2, d); }} /* This code contributed by PrinciRaj1992 */", "e": 3237, "s": 2598, "text": null }, { "code": "<?php// PHP program to find// the length of the direct// common tangent between two circles// which intersect each other // Function to find the length of// the direct common tangentfunction lengtang($r1, $r2, $d){ echo \"The length of the direct common tangent is \" ,sqrt(pow($d, 2) - pow(($r1 - $r2), 2)) ;} // Driver code$r1 = 4; $r2 = 6; $d = 3;lengtang($r1, $r2, $d); // This code is contributed by AnkitRai01?>", "e": 3667, "s": 3237, "text": null }, { "code": "<script> // javascript program to find// the length of the direct// common tangent between two circles// which intersect each other // Function to find the length of// the direct common tangentfunction lengtang(r1 , r2 , d){ document.write(\"The length of the direct\" + \" common tangent is \" + (Math.sqrt(Math.pow(d, 2) - Math.pow((r1 - r2), 2))).toFixed(5));} // Driver codevar r1 = 4, r2 = 6, d = 3;lengtang(r1, r2, d); // This code contributed by Princi Singh </script>", "e": 4180, "s": 3667, "text": null }, { "code": null, "e": 4231, "s": 4180, "text": "The length of the direct common tangent is 2.23607" }, { "code": null, "e": 4255, "s": 4233, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4277, "s": 4255, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4291, "s": 4277, "text": "princiraj1992" }, { "code": null, "e": 4299, "s": 4291, "text": "ankthon" }, { "code": null, "e": 4311, "s": 4299, "text": "29AjayKumar" }, { "code": null, "e": 4324, "s": 4311, "text": "princi singh" }, { "code": null, "e": 4338, "s": 4324, "text": "souravkumar29" }, { "code": null, "e": 4345, "s": 4338, "text": "circle" }, { "code": null, "e": 4355, "s": 4345, "text": "Geometric" }, { "code": null, "e": 4368, "s": 4355, "text": "Mathematical" }, { "code": null, "e": 4381, "s": 4368, "text": "Mathematical" }, { "code": null, "e": 4391, "s": 4381, "text": "Geometric" } ]
Write a C program that does not terminate when Ctrl+C is pressed
21 Jun, 2022 Write a C program that doesn’t terminate when Ctrl+C is pressed. It prints a message “Cannot be terminated using Ctrl+c” and continues execution. We can use signal handling in C for this. When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler. C standard defines following 6 signals in signal.h header file. SIGABRT – abnormal termination. SIGFPE – floating point exception. SIGILL – invalid instruction. SIGINT – interactive attention request sent to the program. SIGSEGV – invalid memory access. SIGTERM – termination request sent to the program. Additional signals are specified Unix and Unix-like operating systems (such as Linux) defines more than 15 additional signals. See http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals The standard C library function signal() can be used to set up a handler for any of the above signals. C /* A C program that does not terminate when Ctrl+C is pressed */#include <stdio.h>#include <signal.h> /* Signal Handler for SIGINT */void sigintHandler(int sig_num){ /* Reset handler to catch SIGINT next time. Refer http://en.cppreference.com/w/c/program/signal */ signal(SIGINT, sigintHandler); printf("\n Cannot be terminated using Ctrl+C \n"); fflush(stdout);} int main (){ /* Set the SIGINT (Ctrl-C) signal handler to sigintHandler Refer http://en.cppreference.com/w/c/program/signal */ signal(SIGINT, sigintHandler); /* Infinite loop */ while(1) { } return 0;} Output: When Ctrl+C was pressed two times Cannot be terminated using Ctrl+C Cannot be terminated using Ctrl+C Time Complexity: O(1) Auxiliary Space: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet tarakki100 cpp-puzzle system-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 949, "s": 52, "text": "Write a C program that doesn’t terminate when Ctrl+C is pressed. It prints a message “Cannot be terminated using Ctrl+c” and continues execution. We can use signal handling in C for this. When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler. C standard defines following 6 signals in signal.h header file. SIGABRT – abnormal termination. SIGFPE – floating point exception. SIGILL – invalid instruction. SIGINT – interactive attention request sent to the program. SIGSEGV – invalid memory access. SIGTERM – termination request sent to the program. Additional signals are specified Unix and Unix-like operating systems (such as Linux) defines more than 15 additional signals. See http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals The standard C library function signal() can be used to set up a handler for any of the above signals. " }, { "code": null, "e": 951, "s": 949, "text": "C" }, { "code": "/* A C program that does not terminate when Ctrl+C is pressed */#include <stdio.h>#include <signal.h> /* Signal Handler for SIGINT */void sigintHandler(int sig_num){ /* Reset handler to catch SIGINT next time. Refer http://en.cppreference.com/w/c/program/signal */ signal(SIGINT, sigintHandler); printf(\"\\n Cannot be terminated using Ctrl+C \\n\"); fflush(stdout);} int main (){ /* Set the SIGINT (Ctrl-C) signal handler to sigintHandler Refer http://en.cppreference.com/w/c/program/signal */ signal(SIGINT, sigintHandler); /* Infinite loop */ while(1) { } return 0;}", "e": 1565, "s": 951, "text": null }, { "code": null, "e": 1607, "s": 1565, "text": "Output: When Ctrl+C was pressed two times" }, { "code": null, "e": 1681, "s": 1607, "text": " \n Cannot be terminated using Ctrl+C\n \n Cannot be terminated using Ctrl+C" }, { "code": null, "e": 1703, "s": 1681, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1725, "s": 1703, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1850, "s": 1725, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1861, "s": 1850, "text": "nidhi_biet" }, { "code": null, "e": 1872, "s": 1861, "text": "tarakki100" }, { "code": null, "e": 1883, "s": 1872, "text": "cpp-puzzle" }, { "code": null, "e": 1902, "s": 1883, "text": "system-programming" }, { "code": null, "e": 1913, "s": 1902, "text": "C Language" }, { "code": null, "e": 1917, "s": 1913, "text": "C++" }, { "code": null, "e": 1921, "s": 1917, "text": "CPP" }, { "code": null, "e": 2019, "s": 1921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2036, "s": 2019, "text": "Substring in C++" }, { "code": null, "e": 2058, "s": 2036, "text": "Function Pointer in C" }, { "code": null, "e": 2093, "s": 2058, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 2139, "s": 2093, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2184, "s": 2139, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2202, "s": 2184, "text": "Vector in C++ STL" }, { "code": null, "e": 2245, "s": 2202, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2291, "s": 2245, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2334, "s": 2291, "text": "Set in C++ Standard Template Library (STL)" } ]
Number of Transpositions in a Permutation
01 Jun, 2022 Permutation A permutation is an arrangement of elements. A permutation of n elements can be represented by an arrangement of the numbers 1, 2, ...n in some order. Eg. 5, 1, 4, 2, 3.Cycle notation A permutation can be represented as a composition of permutation cycles. A permutation cycle is a set of elements in a permutation that trade places with one another. For e.g. P = { 5, 1, 4, 2, 3 }: Here, 5 goes to 1, 1 goes to 2 and so on (according to their indices position): 5 -> 1 1 -> 2 2 -> 4 4 -> 3 3 -> 5 Thus it can be represented as a single cycle: (5, 1, 2, 4, 3).Now consider the permutation: {5, 1, 4, 3, 2}. Here 5 -> 1 1 -> 2 2 -> 5 this closes 1 cycle. The other cycle is 4 -> 3 3 -> 4 In cycle notation it will be represented as (5, 1, 2) (4, 3). Transpositions Now all cycles can be decomposed into a composition of 2 cycles (transpositions). The number of transpositions in a permutation is important as it gives the minimum number of 2 element swaps required to get this particular arrangement from the identity arrangement: 1, 2, 3, ... n. The parity of the number of such 2 cycles represents whether the permutation is even or odd. For e.g. The cycle (5, 1, 2, 4, 3) can be written as (5, 3)(5, 4)(5, 2)(5, 1). 4 transpositions (even). Similarly, (5, 1, 2) -> (5, 2)(5, 1) (5, 1, 2)(4, 3) -> (5, 2)(5, 1)(4, 3). 3 transpositions (odd). It is clear from the examples that the number of transpositions from a cycle = length of the cycle – 1. Problem Given a permutation of n numbers P1, P2, P3, ... Pn. Calculate the number of transpositions in it. Example: Input: 5 1 4 3 2 Output: 3 Approach: The permutation can be easily represented as a directed graph where the number of connected components gives the number of cycles. And (the size of each component – 1) gives the number of transpositions from that cycle.Example Permutation : {5, 1, 4, 3, 2} -> (5, 1, 2)(4, 3) Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP Program to find the number of// transpositions in a permutation#include <bits/stdc++.h>using namespace std; #define N 1000001 int visited[N]; // This array stores which element goes to which positionint goesTo[N]; // For eg. in { 5, 1, 4, 3, 2 }// goesTo[1] = 2// goesTo[2] = 5// goesTo[3] = 4// goesTo[4] = 3// goesTo[5] = 1 // This function returns the size of a component cycleint dfs(int i){ // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1);} // This function returns the number// of transpositions in the permutationint noOfTranspositions(int P[], int n){ // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions;} // Driver Codeint main(){ int permutation[] = { 5, 1, 4, 3, 2 }; int n = sizeof(permutation) / sizeof(permutation[0]); cout << noOfTranspositions(permutation, n); return 0;} // Java Program to find the number of// transpositions in a permutationimport java.io.*; class GFG { static int N = 1000001; static int visited[] = new int[N]; // This array stores which element // goes to which position static int goesTo[]= new int[N]; // For eg. in { 5, 1, 4, 3, 2 } // goesTo[1] = 2 // goesTo[2] = 5 // goesTo[3] = 4 // goesTo[4] = 3 // goesTo[5] = 1 // This function returns the size // of a component cycle static int dfs(int i) { // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1); } // This function returns the number // of transpositions in the // permutation static int noOfTranspositions(int P[], int n) { // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions; } // Driver Code public static void main (String[] args) { int permutation[] = { 5, 1, 4, 3, 2 }; int n = permutation.length ; System.out.println( noOfTranspositions(permutation, n)); }} // This code is contributed by anuj_67. # Python Program to find the number of# transpositions in a permutationN = 1000001 visited = [0] * N; # This array stores which element goes to which positiongoesTo = [0] * N; # For eg. in { 5, 1, 4, 3, 2 }# goesTo[1] = 2# goesTo[2] = 5# goesTo[3] = 4# goesTo[4] = 3# goesTo[5] = 1 # This function returns the size of a component cycledef dfs(i) : # If it is already visited if (visited[i] == 1) : return 0; visited[i] = 1; x = dfs(goesTo[i]); return (x + 1); # This function returns the number# of transpositions in the permutationdef noOfTranspositions(P, n) : # Initializing visited[] array for i in range(1, n + 1) : visited[i] = 0; # building the goesTo[] array for i in range(n) : goesTo[P[i]] = i + 1; transpositions = 0; for i in range(1, n + 1) : if (visited[i] == 0) : ans = dfs(i); transpositions += ans - 1; return transpositions; # Driver Codeif __name__ == "__main__" : permutation = [ 5, 1, 4, 3, 2 ]; n = len(permutation); print(noOfTranspositions(permutation, n)); # This code is contributed by AnkitRai01 // C# Program to find the number of// transpositions in a permutationusing System; class GFG { static int N = 1000001; static int []visited = new int[N]; // This array stores which element // goes to which position static int []goesTo= new int[N]; // For eg. in { 5, 1, 4, 3, 2 } // goesTo[1] = 2 // goesTo[2] = 5 // goesTo[3] = 4 // goesTo[4] = 3 // goesTo[5] = 1 // This function returns the size // of a component cycle static int dfs(int i) { // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1); } // This function returns the number // of transpositions in the // permutation static int noOfTranspositions(int []P, int n) { // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions; } // Driver Code public static void Main () { int []permutation = { 5, 1, 4, 3, 2 }; int n = permutation.Length ; Console.WriteLine( noOfTranspositions(permutation, n)); }} // This code is contributed by anuj_67. <script> // Javascript Program to find the number of// transpositions in a permutation let N = 1000001var visited = new Array(N); // This array stores which element goes to which positionvar goesTo = new Array(N); // For eg. in { 5, 1, 4, 3, 2 }// goesTo[1] = 2// goesTo[2] = 5// goesTo[3] = 4// goesTo[4] = 3// goesTo[5] = 1 // This function returns the size of a component cyclefunction dfs( i){ // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; let x = dfs(goesTo[i]); return (x + 1);} // This function returns the number// of transpositions in the permutationfunction noOfTranspositions( P, n){ // Initializing visited[] array for (let i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (let i = 0; i < n; i++) goesTo[P[i]] = i + 1; let transpositions = 0; for (let i = 1; i <= n; i++) { if (visited[i] == 0) { let ans = dfs(i); transpositions += ans - 1; } } return transpositions;} // Driver Code let permutation = [ 5, 1, 4, 3, 2 ];let n = permutation.length; document.write(noOfTranspositions(permutation, n)); </script> Output: 3 Time Complexity : O(n) Auxiliary space : O(n) vt_m ankthon jana_sayantan surinderdawra388 DFS Competitive Programming Graph Mathematical Mathematical DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Count of strings whose prefix match with the given string to a given length k Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 426, "s": 52, "text": "Permutation A permutation is an arrangement of elements. A permutation of n elements can be represented by an arrangement of the numbers 1, 2, ...n in some order. Eg. 5, 1, 4, 2, 3.Cycle notation A permutation can be represented as a composition of permutation cycles. A permutation cycle is a set of elements in a permutation that trade places with one another. For e.g. " }, { "code": null, "e": 816, "s": 426, "text": "P = { 5, 1, 4, 2, 3 }: Here, 5 goes to 1, 1 goes to 2 and so on (according to their indices position): 5 -> 1 1 -> 2 2 -> 4 4 -> 3 3 -> 5 Thus it can be represented as a single cycle: (5, 1, 2, 4, 3).Now consider the permutation: {5, 1, 4, 3, 2}. Here 5 -> 1 1 -> 2 2 -> 5 this closes 1 cycle. The other cycle is 4 -> 3 3 -> 4 In cycle notation it will be represented as (5, 1, 2) (4, 3). " }, { "code": null, "e": 1217, "s": 816, "text": "Transpositions Now all cycles can be decomposed into a composition of 2 cycles (transpositions). The number of transpositions in a permutation is important as it gives the minimum number of 2 element swaps required to get this particular arrangement from the identity arrangement: 1, 2, 3, ... n. The parity of the number of such 2 cycles represents whether the permutation is even or odd. For e.g. " }, { "code": null, "e": 1518, "s": 1217, "text": "The cycle (5, 1, 2, 4, 3) can be written as (5, 3)(5, 4)(5, 2)(5, 1). 4 transpositions (even). Similarly, (5, 1, 2) -> (5, 2)(5, 1) (5, 1, 2)(4, 3) -> (5, 2)(5, 1)(4, 3). 3 transpositions (odd). It is clear from the examples that the number of transpositions from a cycle = length of the cycle – 1. " }, { "code": null, "e": 1636, "s": 1518, "text": "Problem Given a permutation of n numbers P1, P2, P3, ... Pn. Calculate the number of transpositions in it. Example: " }, { "code": null, "e": 1664, "s": 1636, "text": "Input: 5 1 4 3 2\nOutput: 3 " }, { "code": null, "e": 1951, "s": 1664, "text": "Approach: The permutation can be easily represented as a directed graph where the number of connected components gives the number of cycles. And (the size of each component – 1) gives the number of transpositions from that cycle.Example Permutation : {5, 1, 4, 3, 2} -> (5, 1, 2)(4, 3) " }, { "code": null, "e": 2004, "s": 1951, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 2008, "s": 2004, "text": "C++" }, { "code": null, "e": 2013, "s": 2008, "text": "Java" }, { "code": null, "e": 2021, "s": 2013, "text": "Python3" }, { "code": null, "e": 2024, "s": 2021, "text": "C#" }, { "code": null, "e": 2035, "s": 2024, "text": "Javascript" }, { "code": "// CPP Program to find the number of// transpositions in a permutation#include <bits/stdc++.h>using namespace std; #define N 1000001 int visited[N]; // This array stores which element goes to which positionint goesTo[N]; // For eg. in { 5, 1, 4, 3, 2 }// goesTo[1] = 2// goesTo[2] = 5// goesTo[3] = 4// goesTo[4] = 3// goesTo[5] = 1 // This function returns the size of a component cycleint dfs(int i){ // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1);} // This function returns the number// of transpositions in the permutationint noOfTranspositions(int P[], int n){ // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions;} // Driver Codeint main(){ int permutation[] = { 5, 1, 4, 3, 2 }; int n = sizeof(permutation) / sizeof(permutation[0]); cout << noOfTranspositions(permutation, n); return 0;}", "e": 3264, "s": 2035, "text": null }, { "code": "// Java Program to find the number of// transpositions in a permutationimport java.io.*; class GFG { static int N = 1000001; static int visited[] = new int[N]; // This array stores which element // goes to which position static int goesTo[]= new int[N]; // For eg. in { 5, 1, 4, 3, 2 } // goesTo[1] = 2 // goesTo[2] = 5 // goesTo[3] = 4 // goesTo[4] = 3 // goesTo[5] = 1 // This function returns the size // of a component cycle static int dfs(int i) { // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1); } // This function returns the number // of transpositions in the // permutation static int noOfTranspositions(int P[], int n) { // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions; } // Driver Code public static void main (String[] args) { int permutation[] = { 5, 1, 4, 3, 2 }; int n = permutation.length ; System.out.println( noOfTranspositions(permutation, n)); }} // This code is contributed by anuj_67.", "e": 4881, "s": 3264, "text": null }, { "code": "# Python Program to find the number of# transpositions in a permutationN = 1000001 visited = [0] * N; # This array stores which element goes to which positiongoesTo = [0] * N; # For eg. in { 5, 1, 4, 3, 2 }# goesTo[1] = 2# goesTo[2] = 5# goesTo[3] = 4# goesTo[4] = 3# goesTo[5] = 1 # This function returns the size of a component cycledef dfs(i) : # If it is already visited if (visited[i] == 1) : return 0; visited[i] = 1; x = dfs(goesTo[i]); return (x + 1); # This function returns the number# of transpositions in the permutationdef noOfTranspositions(P, n) : # Initializing visited[] array for i in range(1, n + 1) : visited[i] = 0; # building the goesTo[] array for i in range(n) : goesTo[P[i]] = i + 1; transpositions = 0; for i in range(1, n + 1) : if (visited[i] == 0) : ans = dfs(i); transpositions += ans - 1; return transpositions; # Driver Codeif __name__ == \"__main__\" : permutation = [ 5, 1, 4, 3, 2 ]; n = len(permutation); print(noOfTranspositions(permutation, n)); # This code is contributed by AnkitRai01", "e": 6008, "s": 4881, "text": null }, { "code": "// C# Program to find the number of// transpositions in a permutationusing System; class GFG { static int N = 1000001; static int []visited = new int[N]; // This array stores which element // goes to which position static int []goesTo= new int[N]; // For eg. in { 5, 1, 4, 3, 2 } // goesTo[1] = 2 // goesTo[2] = 5 // goesTo[3] = 4 // goesTo[4] = 3 // goesTo[5] = 1 // This function returns the size // of a component cycle static int dfs(int i) { // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; int x = dfs(goesTo[i]); return (x + 1); } // This function returns the number // of transpositions in the // permutation static int noOfTranspositions(int []P, int n) { // Initializing visited[] array for (int i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (int i = 0; i < n; i++) goesTo[P[i]] = i + 1; int transpositions = 0; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { int ans = dfs(i); transpositions += ans - 1; } } return transpositions; } // Driver Code public static void Main () { int []permutation = { 5, 1, 4, 3, 2 }; int n = permutation.Length ; Console.WriteLine( noOfTranspositions(permutation, n)); }} // This code is contributed by anuj_67.", "e": 7602, "s": 6008, "text": null }, { "code": "<script> // Javascript Program to find the number of// transpositions in a permutation let N = 1000001var visited = new Array(N); // This array stores which element goes to which positionvar goesTo = new Array(N); // For eg. in { 5, 1, 4, 3, 2 }// goesTo[1] = 2// goesTo[2] = 5// goesTo[3] = 4// goesTo[4] = 3// goesTo[5] = 1 // This function returns the size of a component cyclefunction dfs( i){ // If it is already visited if (visited[i] == 1) return 0; visited[i] = 1; let x = dfs(goesTo[i]); return (x + 1);} // This function returns the number// of transpositions in the permutationfunction noOfTranspositions( P, n){ // Initializing visited[] array for (let i = 1; i <= n; i++) visited[i] = 0; // building the goesTo[] array for (let i = 0; i < n; i++) goesTo[P[i]] = i + 1; let transpositions = 0; for (let i = 1; i <= n; i++) { if (visited[i] == 0) { let ans = dfs(i); transpositions += ans - 1; } } return transpositions;} // Driver Code let permutation = [ 5, 1, 4, 3, 2 ];let n = permutation.length; document.write(noOfTranspositions(permutation, n)); </script>", "e": 8776, "s": 7602, "text": null }, { "code": null, "e": 8786, "s": 8776, "text": "Output: " }, { "code": null, "e": 8788, "s": 8786, "text": "3" }, { "code": null, "e": 8835, "s": 8788, "text": "Time Complexity : O(n) Auxiliary space : O(n) " }, { "code": null, "e": 8840, "s": 8835, "text": "vt_m" }, { "code": null, "e": 8848, "s": 8840, "text": "ankthon" }, { "code": null, "e": 8862, "s": 8848, "text": "jana_sayantan" }, { "code": null, "e": 8879, "s": 8862, "text": "surinderdawra388" }, { "code": null, "e": 8883, "s": 8879, "text": "DFS" }, { "code": null, "e": 8907, "s": 8883, "text": "Competitive Programming" }, { "code": null, "e": 8913, "s": 8907, "text": "Graph" }, { "code": null, "e": 8926, "s": 8913, "text": "Mathematical" }, { "code": null, "e": 8939, "s": 8926, "text": "Mathematical" }, { "code": null, "e": 8943, "s": 8939, "text": "DFS" }, { "code": null, "e": 8949, "s": 8943, "text": "Graph" }, { "code": null, "e": 9047, "s": 8949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9074, "s": 9047, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9152, "s": 9074, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 9190, "s": 9152, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 9249, "s": 9190, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 9327, "s": 9249, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 9367, "s": 9327, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 9405, "s": 9367, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 9456, "s": 9405, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 9507, "s": 9456, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Longest subsequence of the form 0*1*0* in a binary string
28 Jun, 2021 Given a binary string, find the longest subsequence of the form (0)*(1)*(0)* in it. Basically we need to divide the string into 3 non overlapping strings (these strings might be empty) without changing the order of letters. First and third strings are made up of only 0 and the second string is made up of only 1. These strings could be made by deleting some characters in original string. What is the maximum size of string, we can get? Examples: Input : 000011100000 Output : 12 Explanation : First part from 1 to 4. Second part 5 to 7. Third part from 8 to 12 Input : 100001100 Output : 8 Explanation : Delete the first letter. First part from 2 to 4. Second part from 5 to 6. Last part from 7. Input : 00000 Output : 5 Explanation : Special Case of Only 0 Input : 111111 Output : 6 Explanation : Special Case of Only 1 Input : 0000001111011011110000 Output : 20 Explanation : Second part is from 7 to 18. Remove all the 0 between indices 7 to 18. A simple solution is to generate all subsequences of given sequence. For every subsequence, check if it is in given form. If yes, compare it with result so far and update the result if needed.This problem can be efficiently solved by pre-computing below arrays in O(n^2) time.Let pre_count_0[i] be the count of letter 0 in the prefix of string till index i. Let pre_count_1[i] be the count of letter 1 in the prefix of string till length i. Let post_count_0[i] be the count of letter 0 in the suffix string from index i till index n (here n is the size of string).Now we fix two two positions i and j, 1 <=i <= j <=n. We will remove all 0 from substring which starts at index i and ends in index j. Thus this makes the second substring of only 1. In the prefix before the index i and in the postfix after the index j we will delete all 1 and thus it will make first and third part of the string.then the maximum length of string attainable is max of pre_count_0[i-1] + (pre_count_1[j]-pre_count_1[i-1]) + pre_count_1[j+1]Special cases : When String is made of only 0s or 1s, ans is n where n is length of string. C++ Java Python3 C# Javascript // CPP program to find longest subsequence// of the form 0*1*0* in a binary string#include <bits/stdc++.h>using namespace std; // Returns length of the longest subsequence// of the form 0*1*0*int longestSubseq(string s){ int n = s.length(); // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int pre_count_0[n + 2]; int pre_count_1[n + 1]; int post_count_0[n + 1]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans;} // driver programint main(){ string s = "000011100000"; cout << longestSubseq(s); return 0;} // Java program to find longest subsequence// of the form 0*1*0* in a binary stringclass GFG{ // Returns length of the longest subsequence // of the form 0*1*0* public static int longestSubseq(String s) { int n = s.length(); // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int[] pre_count_0 = new int[n + 2]; int[] pre_count_1 = new int[n + 1]; int[] post_count_0 = new int[n + 2]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s.charAt(j - 1) == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s.charAt(n - j) == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = Math.max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans; } // Driver code public static void main(String[] args) { String s = "000011100000"; System.out.println(longestSubseq(s)); }} // This code is contributed by// sanjeev2552 # Python 3 program to find longest subsequence# of the form 0*1*0* in a binary string # Returns length of the longest subsequence# of the form 0*1*0*def longestSubseq(s): n = len(s) # Precomputing values in three arrays # pre_count_0[i] is going to store count # of 0s in prefix str[0..i-1] # pre_count_1[i] is going to store count # of 1s in prefix str[0..i-1] # post_count_0[i] is going to store count # of 0s in suffix str[i-1..n-1] pre_count_0 = [0 for i in range(n + 2)] pre_count_1 = [0 for i in range(n + 1)] post_count_0 = [0 for i in range(n + 2)] pre_count_0[0] = 0 post_count_0[n + 1] = 0 pre_count_1[0] = 0 for j in range(1, n + 1): pre_count_0[j] = pre_count_0[j - 1] pre_count_1[j] = pre_count_1[j - 1] post_count_0[n - j + 1] = post_count_0[n - j + 2] if (s[j - 1] == '0'): pre_count_0[j] += 1 else: pre_count_1[j] += 1 if (s[n - j] == '0'): post_count_0[n - j + 1] += 1 # string is made up of all 0s or all 1s if (pre_count_0[n] == n or pre_count_0[n] == 0): return n # Compute result using precomputed values ans = 0 for i in range(1, n + 1): for j in range(i, n + 1, 1): ans = max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans) return ans # Driver Codeif __name__ == '__main__': s = "000011100000" print(longestSubseq(s)) # This code is contributed by# Surendra_Gangwar // C# program to find longest subsequence// of the form 0*1*0* in a binary stringusing System; class GFG{ // Returns length of the longest subsequence // of the form 0*1*0* public static int longestSubseq(String s) { int n = s.Length; // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int[] pre_count_0 = new int[n + 2]; int[] pre_count_1 = new int[n + 1]; int[] post_count_0 = new int[n + 2]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = Math.Max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans; } // Driver code public static void Main(String[] args) { String s = "000011100000"; Console.WriteLine(longestSubseq(s)); }} // This code is contributed by Princi Singh <script> // Javascript program to find longest subsequence// of the form 0*1*0* in a binary string // Returns length of the longest subsequence// of the form 0*1*0*function longestSubseq(s){ let n = s.length; // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] let pre_count_0 = new Array(n + 2); let pre_count_1 = new Array(n + 1); let post_count_0 = new Array(n + 2); pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for(let j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // String is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values let ans = 0; for(let i = 1; i <= n; i++) for(let j = i; j <= n; j++) ans = Math.max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans;} // Driver codelet s = "000011100000"; document.write(longestSubseq(s)); // This code is contributed by vaibhavrabadiya3 </script> Output : 12 This article is contributed by nikhil ranjan 7. 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. SURENDRA_GANGWAR sanjeev2552 princi singh vaibhavrabadiya3 binary-string prefix-sum subsequence Strings prefix-sum Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Check if an URL is valid or not using Regular Expression Remove first and last character of a string in Java Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 490, "s": 52, "text": "Given a binary string, find the longest subsequence of the form (0)*(1)*(0)* in it. Basically we need to divide the string into 3 non overlapping strings (these strings might be empty) without changing the order of letters. First and third strings are made up of only 0 and the second string is made up of only 1. These strings could be made by deleting some characters in original string. What is the maximum size of string, we can get?" }, { "code": null, "e": 501, "s": 490, "text": "Examples: " }, { "code": null, "e": 1024, "s": 501, "text": "Input : 000011100000 \nOutput : 12\nExplanation : \nFirst part from 1 to 4.\nSecond part 5 to 7. \nThird part from 8 to 12 \n\nInput : 100001100 \nOutput : 8\nExplanation : \nDelete the first letter. \nFirst part from 2 to 4. \nSecond part from 5 to 6. \nLast part from 7.\n\nInput : 00000 \nOutput : 5\nExplanation : \nSpecial Case of Only 0\n\nInput : 111111\nOutput : 6\nExplanation : \nSpecial Case of Only 1\n\nInput : 0000001111011011110000 \nOutput : 20\nExplanation : \nSecond part is from 7 to 18. \nRemove all the 0 between indices 7 to 18." }, { "code": null, "e": 2138, "s": 1024, "text": "A simple solution is to generate all subsequences of given sequence. For every subsequence, check if it is in given form. If yes, compare it with result so far and update the result if needed.This problem can be efficiently solved by pre-computing below arrays in O(n^2) time.Let pre_count_0[i] be the count of letter 0 in the prefix of string till index i. Let pre_count_1[i] be the count of letter 1 in the prefix of string till length i. Let post_count_0[i] be the count of letter 0 in the suffix string from index i till index n (here n is the size of string).Now we fix two two positions i and j, 1 <=i <= j <=n. We will remove all 0 from substring which starts at index i and ends in index j. Thus this makes the second substring of only 1. In the prefix before the index i and in the postfix after the index j we will delete all 1 and thus it will make first and third part of the string.then the maximum length of string attainable is max of pre_count_0[i-1] + (pre_count_1[j]-pre_count_1[i-1]) + pre_count_1[j+1]Special cases : When String is made of only 0s or 1s, ans is n where n is length of string. " }, { "code": null, "e": 2142, "s": 2138, "text": "C++" }, { "code": null, "e": 2147, "s": 2142, "text": "Java" }, { "code": null, "e": 2155, "s": 2147, "text": "Python3" }, { "code": null, "e": 2158, "s": 2155, "text": "C#" }, { "code": null, "e": 2169, "s": 2158, "text": "Javascript" }, { "code": "// CPP program to find longest subsequence// of the form 0*1*0* in a binary string#include <bits/stdc++.h>using namespace std; // Returns length of the longest subsequence// of the form 0*1*0*int longestSubseq(string s){ int n = s.length(); // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int pre_count_0[n + 2]; int pre_count_1[n + 1]; int post_count_0[n + 1]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans;} // driver programint main(){ string s = \"000011100000\"; cout << longestSubseq(s); return 0;}", "e": 3793, "s": 2169, "text": null }, { "code": "// Java program to find longest subsequence// of the form 0*1*0* in a binary stringclass GFG{ // Returns length of the longest subsequence // of the form 0*1*0* public static int longestSubseq(String s) { int n = s.length(); // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int[] pre_count_0 = new int[n + 2]; int[] pre_count_1 = new int[n + 1]; int[] post_count_0 = new int[n + 2]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s.charAt(j - 1) == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s.charAt(n - j) == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = Math.max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans; } // Driver code public static void main(String[] args) { String s = \"000011100000\"; System.out.println(longestSubseq(s)); }} // This code is contributed by// sanjeev2552", "e": 5690, "s": 3793, "text": null }, { "code": "# Python 3 program to find longest subsequence# of the form 0*1*0* in a binary string # Returns length of the longest subsequence# of the form 0*1*0*def longestSubseq(s): n = len(s) # Precomputing values in three arrays # pre_count_0[i] is going to store count # of 0s in prefix str[0..i-1] # pre_count_1[i] is going to store count # of 1s in prefix str[0..i-1] # post_count_0[i] is going to store count # of 0s in suffix str[i-1..n-1] pre_count_0 = [0 for i in range(n + 2)] pre_count_1 = [0 for i in range(n + 1)] post_count_0 = [0 for i in range(n + 2)] pre_count_0[0] = 0 post_count_0[n + 1] = 0 pre_count_1[0] = 0 for j in range(1, n + 1): pre_count_0[j] = pre_count_0[j - 1] pre_count_1[j] = pre_count_1[j - 1] post_count_0[n - j + 1] = post_count_0[n - j + 2] if (s[j - 1] == '0'): pre_count_0[j] += 1 else: pre_count_1[j] += 1 if (s[n - j] == '0'): post_count_0[n - j + 1] += 1 # string is made up of all 0s or all 1s if (pre_count_0[n] == n or pre_count_0[n] == 0): return n # Compute result using precomputed values ans = 0 for i in range(1, n + 1): for j in range(i, n + 1, 1): ans = max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans) return ans # Driver Codeif __name__ == '__main__': s = \"000011100000\" print(longestSubseq(s)) # This code is contributed by# Surendra_Gangwar", "e": 7287, "s": 5690, "text": null }, { "code": "// C# program to find longest subsequence// of the form 0*1*0* in a binary stringusing System; class GFG{ // Returns length of the longest subsequence // of the form 0*1*0* public static int longestSubseq(String s) { int n = s.Length; // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] int[] pre_count_0 = new int[n + 2]; int[] pre_count_1 = new int[n + 1]; int[] post_count_0 = new int[n + 2]; pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for (int j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // string is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values int ans = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) ans = Math.Max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans; } // Driver code public static void Main(String[] args) { String s = \"000011100000\"; Console.WriteLine(longestSubseq(s)); }} // This code is contributed by Princi Singh", "e": 9182, "s": 7287, "text": null }, { "code": "<script> // Javascript program to find longest subsequence// of the form 0*1*0* in a binary string // Returns length of the longest subsequence// of the form 0*1*0*function longestSubseq(s){ let n = s.length; // Precomputing values in three arrays // pre_count_0[i] is going to store count // of 0s in prefix str[0..i-1] // pre_count_1[i] is going to store count // of 1s in prefix str[0..i-1] // post_count_0[i] is going to store count // of 0s in suffix str[i-1..n-1] let pre_count_0 = new Array(n + 2); let pre_count_1 = new Array(n + 1); let post_count_0 = new Array(n + 2); pre_count_0[0] = 0; post_count_0[n + 1] = 0; pre_count_1[0] = 0; for(let j = 1; j <= n; j++) { pre_count_0[j] = pre_count_0[j - 1]; pre_count_1[j] = pre_count_1[j - 1]; post_count_0[n - j + 1] = post_count_0[n - j + 2]; if (s[j - 1] == '0') pre_count_0[j]++; else pre_count_1[j]++; if (s[n - j] == '0') post_count_0[n - j + 1]++; } // String is made up of all 0s or all 1s if (pre_count_0[n] == n || pre_count_0[n] == 0) return n; // Compute result using precomputed values let ans = 0; for(let i = 1; i <= n; i++) for(let j = i; j <= n; j++) ans = Math.max(pre_count_0[i - 1] + pre_count_1[j] - pre_count_1[i - 1] + post_count_0[j + 1], ans); return ans;} // Driver codelet s = \"000011100000\"; document.write(longestSubseq(s)); // This code is contributed by vaibhavrabadiya3 </script>", "e": 10812, "s": 9182, "text": null }, { "code": null, "e": 10822, "s": 10812, "text": "Output : " }, { "code": null, "e": 10825, "s": 10822, "text": "12" }, { "code": null, "e": 11249, "s": 10825, "text": "This article is contributed by nikhil ranjan 7. 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": 11266, "s": 11249, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 11278, "s": 11266, "text": "sanjeev2552" }, { "code": null, "e": 11291, "s": 11278, "text": "princi singh" }, { "code": null, "e": 11308, "s": 11291, "text": "vaibhavrabadiya3" }, { "code": null, "e": 11322, "s": 11308, "text": "binary-string" }, { "code": null, "e": 11333, "s": 11322, "text": "prefix-sum" }, { "code": null, "e": 11345, "s": 11333, "text": "subsequence" }, { "code": null, "e": 11353, "s": 11345, "text": "Strings" }, { "code": null, "e": 11364, "s": 11353, "text": "prefix-sum" }, { "code": null, "e": 11372, "s": 11364, "text": "Strings" }, { "code": null, "e": 11470, "s": 11372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11515, "s": 11470, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 11579, "s": 11515, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11624, "s": 11579, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 11659, "s": 11624, "text": "Print all subsequences of a string" }, { "code": null, "e": 11724, "s": 11659, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 11753, "s": 11724, "text": "String class in Java | Set 1" }, { "code": null, "e": 11814, "s": 11753, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 11871, "s": 11814, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 11923, "s": 11871, "text": "Remove first and last character of a string in Java" } ]
Difference between Method Overloading and Method Overriding in Python
29 Apr, 2021 Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method.Example: Python3 # Function to take multiple argumentsdef add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integeradd('int', 5, 6) # Stringadd('str', 'Hi ', 'Geeks') Output: 11 Hi Geeks Method Overriding: Method overriding is an example of run time polymorphism. In this, the specific implementation of the method that is already provided by the parent class is provided by the child class. It is used to change the behavior of existing methods and there is a need for at least two classes for method overriding. In method overriding, inheritance always required as it is done between parent class(superclass) and child class(child class) methods.Example of Method Overriding in python: Python3 class A: def fun1(self): print('feature_1 of class A') def fun2(self): print('feature_2 of class A') class B(A): # Modified function that is # already exist in class A def fun1(self): print('Modified feature_1 of class A by class B') def fun3(self): print('feature_3 of class B') # Create instanceobj = B() # Call the override functionobj.fun1() Output: Modified feature_1 of class A by class B Difference between Method Overloading and Method Overriding in Python: anks005 rajavslk python-basics python-oop-concepts Difference Between Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Method Overloading and Method Overriding in Java Difference between Compile-time and Run-time Polymorphism in Java Difference between Synchronous and Asynchronous Transmission Difference between Structure and Union in C Differences between Procedural and Object Oriented Programming Iterate over a list in Python Python map() function Read JSON file using Python How to iterate through Excel rows in Python? Enumerate() in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Apr, 2021" }, { "code": null, "e": 506, "s": 53, "text": "Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method.Example: " }, { "code": null, "e": 514, "s": 506, "text": "Python3" }, { "code": "# Function to take multiple argumentsdef add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integeradd('int', 5, 6) # Stringadd('str', 'Hi ', 'Geeks')", "e": 1071, "s": 514, "text": null }, { "code": null, "e": 1081, "s": 1071, "text": "Output: " }, { "code": null, "e": 1093, "s": 1081, "text": "11\nHi Geeks" }, { "code": null, "e": 1596, "s": 1093, "text": "Method Overriding: Method overriding is an example of run time polymorphism. In this, the specific implementation of the method that is already provided by the parent class is provided by the child class. It is used to change the behavior of existing methods and there is a need for at least two classes for method overriding. In method overriding, inheritance always required as it is done between parent class(superclass) and child class(child class) methods.Example of Method Overriding in python: " }, { "code": null, "e": 1604, "s": 1596, "text": "Python3" }, { "code": "class A: def fun1(self): print('feature_1 of class A') def fun2(self): print('feature_2 of class A') class B(A): # Modified function that is # already exist in class A def fun1(self): print('Modified feature_1 of class A by class B') def fun3(self): print('feature_3 of class B') # Create instanceobj = B() # Call the override functionobj.fun1()", "e": 2041, "s": 1604, "text": null }, { "code": null, "e": 2051, "s": 2041, "text": "Output: " }, { "code": null, "e": 2092, "s": 2051, "text": "Modified feature_1 of class A by class B" }, { "code": null, "e": 2169, "s": 2092, "text": " Difference between Method Overloading and Method Overriding in Python: " }, { "code": null, "e": 2179, "s": 2171, "text": "anks005" }, { "code": null, "e": 2188, "s": 2179, "text": "rajavslk" }, { "code": null, "e": 2202, "s": 2188, "text": "python-basics" }, { "code": null, "e": 2222, "s": 2202, "text": "python-oop-concepts" }, { "code": null, "e": 2241, "s": 2222, "text": "Difference Between" }, { "code": null, "e": 2248, "s": 2241, "text": "Python" }, { "code": null, "e": 2346, "s": 2248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2414, "s": 2346, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2480, "s": 2414, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 2541, "s": 2480, "text": "Difference between Synchronous and Asynchronous Transmission" }, { "code": null, "e": 2585, "s": 2541, "text": "Difference between Structure and Union in C" }, { "code": null, "e": 2648, "s": 2585, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 2678, "s": 2648, "text": "Iterate over a list in Python" }, { "code": null, "e": 2700, "s": 2678, "text": "Python map() function" }, { "code": null, "e": 2728, "s": 2700, "text": "Read JSON file using Python" }, { "code": null, "e": 2773, "s": 2728, "text": "How to iterate through Excel rows in Python?" } ]
JavaScript | Adding seconds to Date object
23 May, 2019 Given a date, the task is to add seconds to it. To add seconds to date in javascript, we’re going to discuss a few techniques. First few methods to know. JavaScript getSeconds() MethodThis method returns the Seconds(from 0 to 59) of the provided date and time.Syntax:Date.getSeconds() Return value:It returns a number, from 0 to 59, representing the seconds. Date.getSeconds() Return value:It returns a number, from 0 to 59, representing the seconds. JavaScript setSeconds() MethodThis method set the seconds of a date object.This method can also be used to set the milliseconds.Syntax:Date.setSeconds(sec, millisec) Parameters:sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note:All the previous 2 parameters accept values apart from their range and these values adjust like.sec = -1, means the last second of the previous minute and same for the other parameters.if sec passed is 60, means the first second of the next minute and same for the other parameters.Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970. JavaScript setSeconds() MethodThis method set the seconds of a date object.This method can also be used to set the milliseconds.Syntax: Date.setSeconds(sec, millisec) Parameters: sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed. millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed. Note:All the previous 2 parameters accept values apart from their range and these values adjust like. sec = -1, means the last second of the previous minute and same for the other parameters. if sec passed is 60, means the first second of the next minute and same for the other parameters. Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970. JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime() Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970. Date.getTime() Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970. JavaScript setTime() methodThis method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec) Parameters:millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1, 1970. JavaScript setTime() methodThis method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax: Date.setTime(millisec) Parameters: millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970 Return value:It returns, representing the number of milliseconds between the date object and midnight January 1, 1970. Example 1: This example adds 100 seconds to the var today by using setTime() and getTime() method. <!DOCTYPE HTML><html> <head> <title> JavaScript | Adding Seconds to Date object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> addSeconds </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addSecs = function(s) { this.setTime(this.getTime() + (s * 1000)); return this; } function gfg_Run() { var a = new Date(); a.addSecs(100); el_down.innerHTML = a; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds 10 seconds to the var today by using setSeconds() and getSeconds() method. <!DOCTYPE HTML><html> <head> <title> JavaScript | Adding Seconds to Date object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> addSeconds </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addSecs = function(s) { this.setSeconds(this.getSeconds() + s); return this; } function gfg_Run() { var a = new Date(); a.addSecs(10); el_down.innerHTML = a; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 182, "s": 28, "text": "Given a date, the task is to add seconds to it. To add seconds to date in javascript, we’re going to discuss a few techniques. First few methods to know." }, { "code": null, "e": 387, "s": 182, "text": "JavaScript getSeconds() MethodThis method returns the Seconds(from 0 to 59) of the provided date and time.Syntax:Date.getSeconds()\nReturn value:It returns a number, from 0 to 59, representing the seconds." }, { "code": null, "e": 406, "s": 387, "text": "Date.getSeconds()\n" }, { "code": null, "e": 480, "s": 406, "text": "Return value:It returns a number, from 0 to 59, representing the seconds." }, { "code": null, "e": 1357, "s": 480, "text": "JavaScript setSeconds() MethodThis method set the seconds of a date object.This method can also be used to set the milliseconds.Syntax:Date.setSeconds(sec, millisec)\nParameters:sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note:All the previous 2 parameters accept values apart from their range and these values adjust like.sec = -1, means the last second of the previous minute and same for the other parameters.if sec passed is 60, means the first second of the next minute and same for the other parameters.Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 1493, "s": 1357, "text": "JavaScript setSeconds() MethodThis method set the seconds of a date object.This method can also be used to set the milliseconds.Syntax:" }, { "code": null, "e": 1525, "s": 1493, "text": "Date.setSeconds(sec, millisec)\n" }, { "code": null, "e": 1537, "s": 1525, "text": "Parameters:" }, { "code": null, "e": 1677, "s": 1537, "text": "sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed." }, { "code": null, "e": 1828, "s": 1677, "text": "millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed." }, { "code": null, "e": 1930, "s": 1828, "text": "Note:All the previous 2 parameters accept values apart from their range and these values adjust like." }, { "code": null, "e": 2020, "s": 1930, "text": "sec = -1, means the last second of the previous minute and same for the other parameters." }, { "code": null, "e": 2118, "s": 2020, "text": "if sec passed is 60, means the first second of the next minute and same for the other parameters." }, { "code": null, "e": 2242, "s": 2118, "text": "Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 2504, "s": 2242, "text": "JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime()\nReturn value:It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 2520, "s": 2504, "text": "Date.getTime()\n" }, { "code": null, "e": 2626, "s": 2520, "text": "Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 3061, "s": 2626, "text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)\nParameters:millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 3218, "s": 3061, "text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax:" }, { "code": null, "e": 3242, "s": 3218, "text": "Date.setTime(millisec)\n" }, { "code": null, "e": 3254, "s": 3242, "text": "Parameters:" }, { "code": null, "e": 3381, "s": 3254, "text": "millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970" }, { "code": null, "e": 3500, "s": 3381, "text": "Return value:It returns, representing the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 3599, "s": 3500, "text": "Example 1: This example adds 100 seconds to the var today by using setTime() and getTime() method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Adding Seconds to Date object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> addSeconds </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addSecs = function(s) { this.setTime(this.getTime() + (s * 1000)); return this; } function gfg_Run() { var a = new Date(); a.addSecs(100); el_down.innerHTML = a; } </script></body> </html>", "e": 4629, "s": 3599, "text": null }, { "code": null, "e": 4637, "s": 4629, "text": "Output:" }, { "code": null, "e": 4668, "s": 4637, "text": "Before clicking on the button:" }, { "code": null, "e": 4698, "s": 4668, "text": "After clicking on the button:" }, { "code": null, "e": 4802, "s": 4698, "text": "Example 2: This example adds 10 seconds to the var today by using setSeconds() and getSeconds() method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Adding Seconds to Date object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> addSeconds </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addSecs = function(s) { this.setSeconds(this.getSeconds() + s); return this; } function gfg_Run() { var a = new Date(); a.addSecs(10); el_down.innerHTML = a; } </script></body> </html>", "e": 5826, "s": 4802, "text": null }, { "code": null, "e": 5834, "s": 5826, "text": "Output:" }, { "code": null, "e": 5865, "s": 5834, "text": "Before clicking on the button:" }, { "code": null, "e": 5895, "s": 5865, "text": "After clicking on the button:" }, { "code": null, "e": 5911, "s": 5895, "text": "javascript-date" }, { "code": null, "e": 5922, "s": 5911, "text": "JavaScript" }, { "code": null, "e": 5939, "s": 5922, "text": "Web Technologies" }, { "code": null, "e": 6037, "s": 5939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6098, "s": 6037, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6170, "s": 6098, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6210, "s": 6170, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6262, "s": 6210, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 6303, "s": 6262, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6365, "s": 6303, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6398, "s": 6365, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6459, "s": 6398, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6509, "s": 6459, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?
01 Nov, 2019 In PHP if you want to delete the file or directory then keep one thing in mind that you cannot delete the file or directory directly there is a condition on that i.e. there are some security issues are there so the best way to do this is you first have to delete the data present in the file or the sub files or directories present in it . Then only you are able to delete the directory . And after deleting the sub directories or files use the rmdir function to delete the main directory. PHP function to delete all files: In the following code, first passing the path of directory which need to delete. It checks whether the file or directory which need to delete is actually present/exist or not. If it does exist then it will open the file check whether there is something in that file or not. If not then delete the directory using rmdir directory. But if any other files are present in the directory if then it will delete the files using unlink function except the . and .. files which means the system files. After deleting all the stuff just use the rmdir function to delete the directory completely. Example: <?php // Variable to store directory name// which need to delete$folder = 'temporary_files'; // Get the list of all of file names// in the folder.$files = glob($folder . '/*'); // Loop through the file listforeach($files as $file) { // Check for file if(is_file($file)) { // Use unlink function to // delete the file. unlink($file); }}?> Before Removing the files: After Removing the files: Description: In this above example, deleting all files from a folder called “temp”. List the files in this directory by using PHP glob function. The glob function basically “finds pathnames that match a certain pattern”. In this case, use a wildcard * (asterix) to select everything that is in the “temp” folder. The glob function returns an array of file names that are in the specified folder. Loop through this array. Using the is_file function to check if it is a file and not a parent directory or a sub-directory. Finally, use the unlink function, which deletes the file (if PHP has valid permissions – if not, an E_WARNING error will be thrown and the function will return a boolean FALSE value). Delete all files and sub-directories in a directory: To delete all files and directories in all sub-directories, we can use recursion. Here is an example of a recursive PHP function that deletes every file and folder in a specified directory. Example: <?php // Function to delete all files// and directoriesfunction deleteAll($str) { // Check for files if (is_file($str)) { // If it is file then remove by // using unlink function return unlink($str); } // If it is a directory. elseif (is_dir($str)) { // Get the list of the files in this // directory $scan = glob(rtrim($str, '/').'/*'); // Loop through the list of files foreach($scan as $index=>$path) { // Call recursive function deleteAll($path); } // Remove the directory itself return @rmdir($str); }} // Function calldeleteAll('temporary_files'); ?> Output: Before removing the directory: After removing the directory: The directory is completely deleted. The function checks if the $str variable represents a path to a file then it deletes the file using the function unlink. However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one. Finally, it removes the sub-directory itself by using PHP rmdir function. Akanksha_Rai Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? PHP | Ternary Operator How to create admin login page using PHP? How to send an email using PHPMailer ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2019" }, { "code": null, "e": 518, "s": 28, "text": "In PHP if you want to delete the file or directory then keep one thing in mind that you cannot delete the file or directory directly there is a condition on that i.e. there are some security issues are there so the best way to do this is you first have to delete the data present in the file or the sub files or directories present in it . Then only you are able to delete the directory . And after deleting the sub directories or files use the rmdir function to delete the main directory." }, { "code": null, "e": 1138, "s": 518, "text": "PHP function to delete all files: In the following code, first passing the path of directory which need to delete. It checks whether the file or directory which need to delete is actually present/exist or not. If it does exist then it will open the file check whether there is something in that file or not. If not then delete the directory using rmdir directory. But if any other files are present in the directory if then it will delete the files using unlink function except the . and .. files which means the system files. After deleting all the stuff just use the rmdir function to delete the directory completely." }, { "code": null, "e": 1147, "s": 1138, "text": "Example:" }, { "code": "<?php // Variable to store directory name// which need to delete$folder = 'temporary_files'; // Get the list of all of file names// in the folder.$files = glob($folder . '/*'); // Loop through the file listforeach($files as $file) { // Check for file if(is_file($file)) { // Use unlink function to // delete the file. unlink($file); }}?>", "e": 1535, "s": 1147, "text": null }, { "code": null, "e": 1562, "s": 1535, "text": "Before Removing the files:" }, { "code": null, "e": 1588, "s": 1562, "text": "After Removing the files:" }, { "code": null, "e": 1601, "s": 1588, "text": "Description:" }, { "code": null, "e": 1672, "s": 1601, "text": "In this above example, deleting all files from a folder called “temp”." }, { "code": null, "e": 1901, "s": 1672, "text": "List the files in this directory by using PHP glob function. The glob function basically “finds pathnames that match a certain pattern”. In this case, use a wildcard * (asterix) to select everything that is in the “temp” folder." }, { "code": null, "e": 1984, "s": 1901, "text": "The glob function returns an array of file names that are in the specified folder." }, { "code": null, "e": 2009, "s": 1984, "text": "Loop through this array." }, { "code": null, "e": 2108, "s": 2009, "text": "Using the is_file function to check if it is a file and not a parent directory or a sub-directory." }, { "code": null, "e": 2292, "s": 2108, "text": "Finally, use the unlink function, which deletes the file (if PHP has valid permissions – if not, an E_WARNING error will be thrown and the function will return a boolean FALSE value)." }, { "code": null, "e": 2535, "s": 2292, "text": "Delete all files and sub-directories in a directory: To delete all files and directories in all sub-directories, we can use recursion. Here is an example of a recursive PHP function that deletes every file and folder in a specified directory." }, { "code": null, "e": 2544, "s": 2535, "text": "Example:" }, { "code": "<?php // Function to delete all files// and directoriesfunction deleteAll($str) { // Check for files if (is_file($str)) { // If it is file then remove by // using unlink function return unlink($str); } // If it is a directory. elseif (is_dir($str)) { // Get the list of the files in this // directory $scan = glob(rtrim($str, '/').'/*'); // Loop through the list of files foreach($scan as $index=>$path) { // Call recursive function deleteAll($path); } // Remove the directory itself return @rmdir($str); }} // Function calldeleteAll('temporary_files'); ?>", "e": 3289, "s": 2544, "text": null }, { "code": null, "e": 3297, "s": 3289, "text": "Output:" }, { "code": null, "e": 3328, "s": 3297, "text": "Before removing the directory:" }, { "code": null, "e": 3395, "s": 3328, "text": "After removing the directory: The directory is completely deleted." }, { "code": null, "e": 3708, "s": 3395, "text": "The function checks if the $str variable represents a path to a file then it deletes the file using the function unlink. However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one. Finally, it removes the sub-directory itself by using PHP rmdir function." }, { "code": null, "e": 3721, "s": 3708, "text": "Akanksha_Rai" }, { "code": null, "e": 3728, "s": 3721, "text": "Picked" }, { "code": null, "e": 3732, "s": 3728, "text": "PHP" }, { "code": null, "e": 3745, "s": 3732, "text": "PHP Programs" }, { "code": null, "e": 3762, "s": 3745, "text": "Web Technologies" }, { "code": null, "e": 3766, "s": 3762, "text": "PHP" }, { "code": null, "e": 3864, "s": 3766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3946, "s": 3864, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 3991, "s": 3946, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 4042, "s": 3991, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 4072, "s": 4042, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 4095, "s": 4072, "text": "PHP | Ternary Operator" }, { "code": null, "e": 4147, "s": 4095, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 4229, "s": 4147, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 4252, "s": 4229, "text": "PHP | Ternary Operator" }, { "code": null, "e": 4294, "s": 4252, "text": "How to create admin login page using PHP?" } ]
Number of perfect squares between two given numbers
02 Jun, 2022 Given two given numbers a and b where 1<=a<=b, find the number of perfect squares between a and b (a and b inclusive).Examples Input : a = 3, b = 8 Output : 1 The only perfect square in given range is 4. Input : a = 9, b = 25 Output : 3 The three perfect squares in given range are 9, 16 and 25 Method 1 : One naive approach is to check all the numbers between a and b (inclusive a and b) and increase count by one whenever we encounter a perfect square. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // A Simple Method to count squares between a and b#include <bits/stdc++.h>using namespace std; int countSquares(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt;} // Driver codeint main(){ int a = 9, b = 25; cout << "Count of squares is " << countSquares(a, b); return 0;} // Java program to count squares between a and bclass CountSquares { static int countSquares(int a, int b) { int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt; }} // Driver Codepublic class PerfectSquares { public static void main(String[] args) { int a = 9, b = 25; CountSquares obj = new CountSquares(); System.out.print("Count of squares is " + obj.countSquares(a, b)); }} # Python program to count squares between a and b def CountSquares(a, b): cnt = 0 # initialize result # Traverse through all numbers for i in range (a, b + 1): j = 1; while j * j <= i: if j * j == i: cnt = cnt + 1 j = j + 1 i = i + 1 return cnt # Driver Codea = 9b = 25print ("Count of squares is:", CountSquares(a, b)) // C# program to count squares// between a and busing System; class GFG { // Function to count squares static int countSquares(int a, int b) { // Initialize result int cnt = 0; // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number // 'i' is perfect square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt; } // Driver Code public static void Main() { int a = 9, b = 25; Console.Write("Count of squares is " + countSquares(a, b)); }} // This code is contributed by Sam007 <?php// A Simple Method to count squares//between a and b function countSquares($a, $b){ $cnt = 0; // Initialize result // Traverse through all numbers for ($i = $a; $i <= $b; $i++) // Check if current number // 'i' is perfect square for ($j = 1; $j * $j <= $i; $j++) if ($j * $j == $i) $cnt++; return $cnt;} // Driver code $a = 9; $b = 25; echo "Count of squares is ". countSquares($a, $b); // This code is contributed by ajit.?> <script>// A Simple Method to count squares//between a and b function countSquares(a, b){ let cnt = 0; // Traverse through all numbers for (let i = a; i <= b; i++) // Check if current number // 'i' is perfect square for (let j = 1; j * j <= i;j++) if (j * j == i) cnt++; return cnt;} // Driver code let a = 9; let b = 25; document.write( "Count of squares is ", countSquares(a, b)); // This code is contributed by sravan.</script> Count of squares is 3 An upper bound on time Complexity of this solution is O((b-a) * sqrt(b)).Method 2 (Efficient) We can simply take square root of ‘a’ and square root of ‘b’ and count the perfect squares between them using floor(sqrt(b)) - ceil(sqrt(a)) + 1 We take floor of sqrt(b) because we need to consider numbers before b. We take ceil of sqrt(a) because we need to consider numbers after a. For example, let b = 24, a = 8. floor(sqrt(b)) = 4, ceil(sqrt(a)) = 3. And number of squares is 4 - 3 + 1 = 2. The two numbers are 9 and 16. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // An Efficient Method to count squares between a and b#include <bits/stdc++.h>using namespace std; // An efficient solution to count square between a// and bint countSquares(int a, int b){ return (floor(sqrt(b)) - ceil(sqrt(a)) + 1);} // Driver codeint main(){ int a = 9, b = 25; cout << "Count of squares is " << countSquares(a, b); return 0;} // An Efficient method to count squares between// a and bclass CountSquares { double countSquares(int a, int b) { return (Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1); }} // Driver Codepublic class PerfectSquares { public static void main(String[] args) { int a = 9, b = 25; CountSquares obj = new CountSquares(); System.out.print("Count of squares is " + (int)obj.countSquares(a, b)); }} # An Efficient Method to count squares between a# and bimport mathdef CountSquares(a, b): return (math.floor(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1) # Driver Codea = 9b = 25print ("Count of squares is:", int(CountSquares(a, b))) // C# program for efficient method// to count squares between a & busing System; class GFG { // Function to count squares static double countSquares(int a, int b) { return (Math.Floor(Math.Sqrt(b)) - Math.Ceiling(Math.Sqrt(a)) + 1); } // Driver Code public static void Main() { int a = 9, b = 25; Console.Write("Count of squares is " + (int)countSquares(a, b)); }} // This code is contributed by Sam007. <?php// An Efficient PHP code to count// squares between a and b // Method to count square// between a and bfunction countSquares($a, $b){ return (floor(sqrt($b)) - ceil(sqrt($a)) + 1);} // Driver code{ $a = 9; $b = 25; echo "Count of squares is ", countSquares($a, $b); return 0;}// This code is contributed by nitin mittal.?> <script>// A Simple Method to count squares//between a and b function countSquares(a, b){ return (Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1);} // Driver code let a = 9; let b = 25; document.write( "Count of squares is ", countSquares(a, b)); // This code is contributed by sravan.</script> Count of squares is 3 Time complexity of this solution is O(Log b). A typical implementation of square root for a number n takes time equal to O(Log n) [See this for a sample implementation of square root] This article is contributed by Rahul Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 Sam007 jit_t nitin mittal sravankumar8128 amartyaniel20 saitej7 maths-perfect-square Wipro Mathematical Wipro Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2022" }, { "code": null, "e": 181, "s": 52, "text": "Given two given numbers a and b where 1<=a<=b, find the number of perfect squares between a and b (a and b inclusive).Examples " }, { "code": null, "e": 352, "s": 181, "text": "Input : a = 3, b = 8\nOutput : 1\nThe only perfect square in given range is 4.\n\nInput : a = 9, b = 25\nOutput : 3\nThe three perfect squares in given range are 9, \n16 and 25" }, { "code": null, "e": 512, "s": 352, "text": "Method 1 : One naive approach is to check all the numbers between a and b (inclusive a and b) and increase count by one whenever we encounter a perfect square." }, { "code": null, "e": 558, "s": 512, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 562, "s": 558, "text": "C++" }, { "code": null, "e": 567, "s": 562, "text": "Java" }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": null, "e": 578, "s": 575, "text": "C#" }, { "code": null, "e": 582, "s": 578, "text": "PHP" }, { "code": null, "e": 593, "s": 582, "text": "Javascript" }, { "code": "// A Simple Method to count squares between a and b#include <bits/stdc++.h>using namespace std; int countSquares(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt;} // Driver codeint main(){ int a = 9, b = 25; cout << \"Count of squares is \" << countSquares(a, b); return 0;}", "e": 1126, "s": 593, "text": null }, { "code": "// Java program to count squares between a and bclass CountSquares { static int countSquares(int a, int b) { int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt; }} // Driver Codepublic class PerfectSquares { public static void main(String[] args) { int a = 9, b = 25; CountSquares obj = new CountSquares(); System.out.print(\"Count of squares is \" + obj.countSquares(a, b)); }}", "e": 1803, "s": 1126, "text": null }, { "code": "# Python program to count squares between a and b def CountSquares(a, b): cnt = 0 # initialize result # Traverse through all numbers for i in range (a, b + 1): j = 1; while j * j <= i: if j * j == i: cnt = cnt + 1 j = j + 1 i = i + 1 return cnt # Driver Codea = 9b = 25print (\"Count of squares is:\", CountSquares(a, b))", "e": 2196, "s": 1803, "text": null }, { "code": "// C# program to count squares// between a and busing System; class GFG { // Function to count squares static int countSquares(int a, int b) { // Initialize result int cnt = 0; // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number // 'i' is perfect square for (int j = 1; j * j <= i; j++) if (j * j == i) cnt++; return cnt; } // Driver Code public static void Main() { int a = 9, b = 25; Console.Write(\"Count of squares is \" + countSquares(a, b)); }} // This code is contributed by Sam007", "e": 2863, "s": 2196, "text": null }, { "code": "<?php// A Simple Method to count squares//between a and b function countSquares($a, $b){ $cnt = 0; // Initialize result // Traverse through all numbers for ($i = $a; $i <= $b; $i++) // Check if current number // 'i' is perfect square for ($j = 1; $j * $j <= $i; $j++) if ($j * $j == $i) $cnt++; return $cnt;} // Driver code $a = 9; $b = 25; echo \"Count of squares is \". countSquares($a, $b); // This code is contributed by ajit.?>", "e": 3405, "s": 2863, "text": null }, { "code": "<script>// A Simple Method to count squares//between a and b function countSquares(a, b){ let cnt = 0; // Traverse through all numbers for (let i = a; i <= b; i++) // Check if current number // 'i' is perfect square for (let j = 1; j * j <= i;j++) if (j * j == i) cnt++; return cnt;} // Driver code let a = 9; let b = 25; document.write( \"Count of squares is \", countSquares(a, b)); // This code is contributed by sravan.</script>", "e": 3923, "s": 3405, "text": null }, { "code": null, "e": 3945, "s": 3923, "text": "Count of squares is 3" }, { "code": null, "e": 4151, "s": 3945, "text": "An upper bound on time Complexity of this solution is O((b-a) * sqrt(b)).Method 2 (Efficient) We can simply take square root of ‘a’ and square root of ‘b’ and count the perfect squares between them using " }, { "code": null, "e": 4476, "s": 4151, "text": "floor(sqrt(b)) - ceil(sqrt(a)) + 1\n\nWe take floor of sqrt(b) because we need to consider \nnumbers before b.\n\nWe take ceil of sqrt(a) because we need to consider \nnumbers after a.\n\n\nFor example, let b = 24, a = 8. floor(sqrt(b)) = 4, \nceil(sqrt(a)) = 3. And number of squares is 4 - 3 + 1\n= 2. The two numbers are 9 and 16." }, { "code": null, "e": 4521, "s": 4476, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 4525, "s": 4521, "text": "C++" }, { "code": null, "e": 4530, "s": 4525, "text": "Java" }, { "code": null, "e": 4538, "s": 4530, "text": "Python3" }, { "code": null, "e": 4541, "s": 4538, "text": "C#" }, { "code": null, "e": 4545, "s": 4541, "text": "PHP" }, { "code": null, "e": 4556, "s": 4545, "text": "Javascript" }, { "code": "// An Efficient Method to count squares between a and b#include <bits/stdc++.h>using namespace std; // An efficient solution to count square between a// and bint countSquares(int a, int b){ return (floor(sqrt(b)) - ceil(sqrt(a)) + 1);} // Driver codeint main(){ int a = 9, b = 25; cout << \"Count of squares is \" << countSquares(a, b); return 0;}", "e": 4922, "s": 4556, "text": null }, { "code": "// An Efficient method to count squares between// a and bclass CountSquares { double countSquares(int a, int b) { return (Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1); }} // Driver Codepublic class PerfectSquares { public static void main(String[] args) { int a = 9, b = 25; CountSquares obj = new CountSquares(); System.out.print(\"Count of squares is \" + (int)obj.countSquares(a, b)); }}", "e": 5368, "s": 4922, "text": null }, { "code": "# An Efficient Method to count squares between a# and bimport mathdef CountSquares(a, b): return (math.floor(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1) # Driver Codea = 9b = 25print (\"Count of squares is:\", int(CountSquares(a, b)))", "e": 5605, "s": 5368, "text": null }, { "code": "// C# program for efficient method// to count squares between a & busing System; class GFG { // Function to count squares static double countSquares(int a, int b) { return (Math.Floor(Math.Sqrt(b)) - Math.Ceiling(Math.Sqrt(a)) + 1); } // Driver Code public static void Main() { int a = 9, b = 25; Console.Write(\"Count of squares is \" + (int)countSquares(a, b)); }} // This code is contributed by Sam007.", "e": 6056, "s": 5605, "text": null }, { "code": "<?php// An Efficient PHP code to count// squares between a and b // Method to count square// between a and bfunction countSquares($a, $b){ return (floor(sqrt($b)) - ceil(sqrt($a)) + 1);} // Driver code{ $a = 9; $b = 25; echo \"Count of squares is \", countSquares($a, $b); return 0;}// This code is contributed by nitin mittal.?>", "e": 6420, "s": 6056, "text": null }, { "code": "<script>// A Simple Method to count squares//between a and b function countSquares(a, b){ return (Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1);} // Driver code let a = 9; let b = 25; document.write( \"Count of squares is \", countSquares(a, b)); // This code is contributed by sravan.</script>", "e": 6749, "s": 6420, "text": null }, { "code": null, "e": 6771, "s": 6749, "text": "Count of squares is 3" }, { "code": null, "e": 6956, "s": 6771, "text": "Time complexity of this solution is O(Log b). A typical implementation of square root for a number n takes time equal to O(Log n) [See this for a sample implementation of square root] " }, { "code": null, "e": 7225, "s": 6956, "text": "This article is contributed by Rahul Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7351, "s": 7227, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 7360, "s": 7353, "text": "Sam007" }, { "code": null, "e": 7366, "s": 7360, "text": "jit_t" }, { "code": null, "e": 7379, "s": 7366, "text": "nitin mittal" }, { "code": null, "e": 7395, "s": 7379, "text": "sravankumar8128" }, { "code": null, "e": 7409, "s": 7395, "text": "amartyaniel20" }, { "code": null, "e": 7417, "s": 7409, "text": "saitej7" }, { "code": null, "e": 7438, "s": 7417, "text": "maths-perfect-square" }, { "code": null, "e": 7444, "s": 7438, "text": "Wipro" }, { "code": null, "e": 7457, "s": 7444, "text": "Mathematical" }, { "code": null, "e": 7463, "s": 7457, "text": "Wipro" }, { "code": null, "e": 7476, "s": 7463, "text": "Mathematical" }, { "code": null, "e": 7574, "s": 7476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7598, "s": 7574, "text": "Merge two sorted arrays" }, { "code": null, "e": 7619, "s": 7598, "text": "Operators in C / C++" }, { "code": null, "e": 7641, "s": 7619, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 7655, "s": 7641, "text": "Prime Numbers" }, { "code": null, "e": 7697, "s": 7655, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 7750, "s": 7697, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7787, "s": 7750, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7830, "s": 7787, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7862, "s": 7830, "text": "Algorithm to solve Rubik's Cube" } ]
Python – math.dist() method
23 Jan, 2020 Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.dist() method in Python is used to the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.This method is new in Python version 3.8. Syntax: math.dist(p, q) Parameters:p: A sequence or iterable of coordinates representing first pointq: A sequence or iterable of coordinates representing second point Returns: the calculated Euclidean distance between the given points. Code #1: Use of math.dist() method # Python Program to explain math.dist() method # Importing math moduleimport math # One dimensional Point # Coordinate of Point PP = 3 # Coordinates of point QQ = -8 # Calculate the Euclidean distance # between points P and QeDistance = math.dist([P], [Q])print(eDistance) 11.0 Code #2: # Python Program to explain math.dist() method # Importing math moduleimport math # Two dimensional Point # Coordinates of Point PPx = 3 Py = 7 # Coordinates of point QQx = -5Qy = -9 # Calculate the Euclidean distance # between points P and QeDistance = math.dist([Px, Py], [Qx, Qy])print(eDistance) # Three-dimensional point # Coordinates of Point PP = [3, 6, 9] # Coordinates of point QQ = [1, 0, -2] # Calculate the Euclidean distance # between points P and QeDistance = math.dist(P, Q)print(eDistance) 17.88854381999832 12.688577540449518 Code #3: # Python Program to explain math.dist() method # Importing math moduleimport math # n-dimensional Point # Coordinates of Point PP = [3, 9, 7, 2, 4, 5] # Coordinates of point QQ = [-5, -3, -9, 0, 6, 2] # Calculate the Euclidean distance # between points P and QeDistance = math.dist(P, Q)print(eDistance) # Dimension of both points # should be the same 21.93171219946131 Reference: Python math library Python math-library Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 379, "s": 28, "text": "Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.dist() method in Python is used to the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.This method is new in Python version 3.8." }, { "code": null, "e": 403, "s": 379, "text": "Syntax: math.dist(p, q)" }, { "code": null, "e": 546, "s": 403, "text": "Parameters:p: A sequence or iterable of coordinates representing first pointq: A sequence or iterable of coordinates representing second point" }, { "code": null, "e": 615, "s": 546, "text": "Returns: the calculated Euclidean distance between the given points." }, { "code": null, "e": 650, "s": 615, "text": "Code #1: Use of math.dist() method" }, { "code": "# Python Program to explain math.dist() method # Importing math moduleimport math # One dimensional Point # Coordinate of Point PP = 3 # Coordinates of point QQ = -8 # Calculate the Euclidean distance # between points P and QeDistance = math.dist([P], [Q])print(eDistance)", "e": 928, "s": 650, "text": null }, { "code": null, "e": 934, "s": 928, "text": "11.0\n" }, { "code": null, "e": 943, "s": 934, "text": "Code #2:" }, { "code": "# Python Program to explain math.dist() method # Importing math moduleimport math # Two dimensional Point # Coordinates of Point PPx = 3 Py = 7 # Coordinates of point QQx = -5Qy = -9 # Calculate the Euclidean distance # between points P and QeDistance = math.dist([Px, Py], [Qx, Qy])print(eDistance) # Three-dimensional point # Coordinates of Point PP = [3, 6, 9] # Coordinates of point QQ = [1, 0, -2] # Calculate the Euclidean distance # between points P and QeDistance = math.dist(P, Q)print(eDistance)", "e": 1461, "s": 943, "text": null }, { "code": null, "e": 1499, "s": 1461, "text": "17.88854381999832\n12.688577540449518\n" }, { "code": null, "e": 1508, "s": 1499, "text": "Code #3:" }, { "code": "# Python Program to explain math.dist() method # Importing math moduleimport math # n-dimensional Point # Coordinates of Point PP = [3, 9, 7, 2, 4, 5] # Coordinates of point QQ = [-5, -3, -9, 0, 6, 2] # Calculate the Euclidean distance # between points P and QeDistance = math.dist(P, Q)print(eDistance) # Dimension of both points # should be the same ", "e": 1868, "s": 1508, "text": null }, { "code": null, "e": 1887, "s": 1868, "text": "21.93171219946131\n" }, { "code": null, "e": 1918, "s": 1887, "text": "Reference: Python math library" }, { "code": null, "e": 1938, "s": 1918, "text": "Python math-library" }, { "code": null, "e": 1968, "s": 1938, "text": "Python math-library-functions" }, { "code": null, "e": 1975, "s": 1968, "text": "Python" }, { "code": null, "e": 2073, "s": 1975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2105, "s": 2073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2132, "s": 2105, "text": "Python Classes and Objects" }, { "code": null, "e": 2153, "s": 2132, "text": "Python OOPs Concepts" }, { "code": null, "e": 2176, "s": 2153, "text": "Introduction To PYTHON" }, { "code": null, "e": 2232, "s": 2176, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2263, "s": 2232, "text": "Python | os.path.join() method" }, { "code": null, "e": 2305, "s": 2263, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2347, "s": 2305, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2386, "s": 2347, "text": "Python | Get unique values from a list" } ]
MathF.Acos() Method in C# with Examples
The MathF.Acos() method in C# is used to return the angle whose cosine is given as a float value argument. Following is the syntax − public static float Acos (float val); Above, Val is the floating-point number. Let us now see an example to implement the MathF.Acos() method − using System; public class Demo { public static void Main(){ float val1 = 0.1f; float val2 = 0.9f; Console.WriteLine("Angle (val1) = "+(MathF.Acos(val1))); Console.WriteLine("Angle (val2) = "+(MathF.Acos(val2))); } } This will produce the following output − Angle (val1) = 1.470629 Angle (val2) = 0.4510269 Let us now see another example to implement the MathF.Acos() method − using System; public class Demo { public static void Main(){ float val1 = 2.5f; float val2 = 5.0f; Console.WriteLine("Angle (val1) = "+(MathF.Acos(val1))); Console.WriteLine("Angle (val2) = "+(MathF.Acos(val2))); } } This will produce the following output − Angle (val1) = NaN Angle (val2) = NaN
[ { "code": null, "e": 1169, "s": 1062, "text": "The MathF.Acos() method in C# is used to return the angle whose cosine is given as a float value argument." }, { "code": null, "e": 1195, "s": 1169, "text": "Following is the syntax −" }, { "code": null, "e": 1233, "s": 1195, "text": "public static float Acos (float val);" }, { "code": null, "e": 1274, "s": 1233, "text": "Above, Val is the floating-point number." }, { "code": null, "e": 1339, "s": 1274, "text": "Let us now see an example to implement the MathF.Acos() method −" }, { "code": null, "e": 1586, "s": 1339, "text": "using System;\npublic class Demo {\n public static void Main(){\n float val1 = 0.1f;\n float val2 = 0.9f;\n Console.WriteLine(\"Angle (val1) = \"+(MathF.Acos(val1)));\n Console.WriteLine(\"Angle (val2) = \"+(MathF.Acos(val2)));\n }\n}" }, { "code": null, "e": 1627, "s": 1586, "text": "This will produce the following output −" }, { "code": null, "e": 1676, "s": 1627, "text": "Angle (val1) = 1.470629\nAngle (val2) = 0.4510269" }, { "code": null, "e": 1746, "s": 1676, "text": "Let us now see another example to implement the MathF.Acos() method −" }, { "code": null, "e": 1993, "s": 1746, "text": "using System;\npublic class Demo {\n public static void Main(){\n float val1 = 2.5f;\n float val2 = 5.0f;\n Console.WriteLine(\"Angle (val1) = \"+(MathF.Acos(val1)));\n Console.WriteLine(\"Angle (val2) = \"+(MathF.Acos(val2)));\n }\n}" }, { "code": null, "e": 2034, "s": 1993, "text": "This will produce the following output −" }, { "code": null, "e": 2072, "s": 2034, "text": "Angle (val1) = NaN\nAngle (val2) = NaN" } ]
Building an Auto-Encoder using Keras
21 Jun, 2019 Prerequisites: Auto-encoders This article will demonstrate the process of data compression and the reconstruction of the encoded data by using Machine Learning by first building an Auto-encoder using Keras and then reconstructing the encoded data and visualizing the reconstruction. We would be using the MNIST handwritten digits dataset which is preloaded into the Keras module about which you can read here. The code is structured as follows: First all the utility functions are defined which are needed at different steps of the building of the Auto-encoder are defined and then each function is called accordingly. Step 1: Importing the required libraries import numpy as npimport matplotlib.pyplot as pltfrom random import randintfrom keras import backend as Kfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2Dfrom keras.models import Modelfrom keras.datasets import mnistfrom keras.callbacks import TensorBoard Step 2: Defining a utility function to load the data def load_data(): # defining the input image size input_image = Input(shape =(28, 28, 1)) # Loading the data and dividing the data into training and testing sets (X_train, _), (X_test, _) = mnist.load_data() # Cleaning and reshaping the data as required by the model X_train = X_train.astype('float32') / 255. X_train = np.reshape(X_train, (len(X_train), 28, 28, 1)) X_test = X_test.astype('float32') / 255. X_test = np.reshape(X_test, (len(X_test), 28, 28, 1)) return X_train, X_test, input_image Note: While loading the data, notice that the space where the training labels are loaded are kept empty because the compression process does not involve the output labels Step 3: Defining a utility function to build the Auto-encoder neural network def build_network(input_image): # Building the encoder of the Auto-encoder x = Conv2D(16, (3, 3), activation ='relu', padding ='same')(input_image) x = MaxPooling2D((2, 2), padding ='same')(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) x = MaxPooling2D((2, 2), padding ='same')(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) encoded_layer = MaxPooling2D((2, 2), padding ='same')(x) # Building the decoder of the Auto-encoder x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(encoded_layer) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation ='relu')(x) x = UpSampling2D((2, 2))(x) decoded_layer = Conv2D(1, (3, 3), activation ='sigmoid', padding ='same')(x) return decoded_layer Step 4: Defining a utility function to build and train the Auto-encoder network def build_auto_encoder_model(X_train, X_test, input_image, decoded_layer): # Defining the parameters of the Auto-encoder autoencoder = Model(input_image, decoded_layer) autoencoder.compile(optimizer ='adadelta', loss ='binary_crossentropy') # Training the Auto-encoder autoencoder.fit(X_train, X_train, epochs = 15, batch_size = 256, shuffle = True, validation_data =(X_test, X_test), callbacks =[TensorBoard(log_dir ='/tmp / autoencoder')]) return autoencoder Step 5: Defining a utility function to visualize the reconstruction def visualize(model, X_test): # Reconstructing the encoded images reconstructed_images = model.predict(X_test) plt.figure(figsize =(20, 4)) for i in range(1, 11): # Generating a random to get random results rand_num = randint(0, 10001) # To display the original image ax = plt.subplot(2, 10, i) plt.imshow(X_test[rand_num].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # To display the reconstructed image ax = plt.subplot(2, 10, i + 10) plt.imshow(reconstructed_images[rand_num].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Displaying the plot plt.show() Step 6: Calling the utility functions in the appropriate order a) Loading the data X_train, X_test, input_image = load_data() b) Building the network decoded_layer = build_network(input_image) c) Building and training the Auto-encoder auto_encoder_model = build_auto_encoder_model(X_train, X_test, input_image, decoded_layer) d) Visualizing the reconstruction visualize(auto_encoder_model, X_test) Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2019" }, { "code": null, "e": 57, "s": 28, "text": "Prerequisites: Auto-encoders" }, { "code": null, "e": 438, "s": 57, "text": "This article will demonstrate the process of data compression and the reconstruction of the encoded data by using Machine Learning by first building an Auto-encoder using Keras and then reconstructing the encoded data and visualizing the reconstruction. We would be using the MNIST handwritten digits dataset which is preloaded into the Keras module about which you can read here." }, { "code": null, "e": 647, "s": 438, "text": "The code is structured as follows: First all the utility functions are defined which are needed at different steps of the building of the Auto-encoder are defined and then each function is called accordingly." }, { "code": null, "e": 688, "s": 647, "text": "Step 1: Importing the required libraries" }, { "code": "import numpy as npimport matplotlib.pyplot as pltfrom random import randintfrom keras import backend as Kfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2Dfrom keras.models import Modelfrom keras.datasets import mnistfrom keras.callbacks import TensorBoard", "e": 968, "s": 688, "text": null }, { "code": null, "e": 1021, "s": 968, "text": "Step 2: Defining a utility function to load the data" }, { "code": "def load_data(): # defining the input image size input_image = Input(shape =(28, 28, 1)) # Loading the data and dividing the data into training and testing sets (X_train, _), (X_test, _) = mnist.load_data() # Cleaning and reshaping the data as required by the model X_train = X_train.astype('float32') / 255. X_train = np.reshape(X_train, (len(X_train), 28, 28, 1)) X_test = X_test.astype('float32') / 255. X_test = np.reshape(X_test, (len(X_test), 28, 28, 1)) return X_train, X_test, input_image", "e": 1567, "s": 1021, "text": null }, { "code": null, "e": 1738, "s": 1567, "text": "Note: While loading the data, notice that the space where the training labels are loaded are kept empty because the compression process does not involve the output labels" }, { "code": null, "e": 1815, "s": 1738, "text": "Step 3: Defining a utility function to build the Auto-encoder neural network" }, { "code": "def build_network(input_image): # Building the encoder of the Auto-encoder x = Conv2D(16, (3, 3), activation ='relu', padding ='same')(input_image) x = MaxPooling2D((2, 2), padding ='same')(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) x = MaxPooling2D((2, 2), padding ='same')(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) encoded_layer = MaxPooling2D((2, 2), padding ='same')(x) # Building the decoder of the Auto-encoder x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(encoded_layer) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation ='relu', padding ='same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation ='relu')(x) x = UpSampling2D((2, 2))(x) decoded_layer = Conv2D(1, (3, 3), activation ='sigmoid', padding ='same')(x) return decoded_layer", "e": 2707, "s": 1815, "text": null }, { "code": null, "e": 2787, "s": 2707, "text": "Step 4: Defining a utility function to build and train the Auto-encoder network" }, { "code": "def build_auto_encoder_model(X_train, X_test, input_image, decoded_layer): # Defining the parameters of the Auto-encoder autoencoder = Model(input_image, decoded_layer) autoencoder.compile(optimizer ='adadelta', loss ='binary_crossentropy') # Training the Auto-encoder autoencoder.fit(X_train, X_train, epochs = 15, batch_size = 256, shuffle = True, validation_data =(X_test, X_test), callbacks =[TensorBoard(log_dir ='/tmp / autoencoder')]) return autoencoder", "e": 3359, "s": 2787, "text": null }, { "code": null, "e": 3427, "s": 3359, "text": "Step 5: Defining a utility function to visualize the reconstruction" }, { "code": "def visualize(model, X_test): # Reconstructing the encoded images reconstructed_images = model.predict(X_test) plt.figure(figsize =(20, 4)) for i in range(1, 11): # Generating a random to get random results rand_num = randint(0, 10001) # To display the original image ax = plt.subplot(2, 10, i) plt.imshow(X_test[rand_num].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # To display the reconstructed image ax = plt.subplot(2, 10, i + 10) plt.imshow(reconstructed_images[rand_num].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Displaying the plot plt.show()", "e": 4242, "s": 3427, "text": null }, { "code": null, "e": 4305, "s": 4242, "text": "Step 6: Calling the utility functions in the appropriate order" }, { "code": null, "e": 4325, "s": 4305, "text": "a) Loading the data" }, { "code": "X_train, X_test, input_image = load_data()", "e": 4368, "s": 4325, "text": null }, { "code": null, "e": 4392, "s": 4368, "text": "b) Building the network" }, { "code": "decoded_layer = build_network(input_image)", "e": 4435, "s": 4392, "text": null }, { "code": null, "e": 4477, "s": 4435, "text": "c) Building and training the Auto-encoder" }, { "code": "auto_encoder_model = build_auto_encoder_model(X_train, X_test, input_image, decoded_layer)", "e": 4700, "s": 4477, "text": null }, { "code": null, "e": 4734, "s": 4700, "text": "d) Visualizing the reconstruction" }, { "code": "visualize(auto_encoder_model, X_test)", "e": 4772, "s": 4734, "text": null }, { "code": null, "e": 4789, "s": 4772, "text": "Machine Learning" }, { "code": null, "e": 4796, "s": 4789, "text": "Python" }, { "code": null, "e": 4813, "s": 4796, "text": "Machine Learning" } ]
Spring Boot – Difference Between CrudRepository and JpaRepository
22 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface. Syntax: public interface CrudRepository<T, ID> extends Repository<T, ID> Where: T: Domain type that repository manages (Generally the Entity/Model class name) ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class) Example: public interface DepartmentRepository extends CrudRepository<Department, Long> {} JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. Syntax: public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> Where: T: Domain type that repository manages (Generally the Entity/Model class name) ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class) Example: public interface DepartmentRepository extends JpaRepository<Department, Long> {} Here in the following image Repository, CrudRepository and PagingAndSortingRepository belong to Spring Data Commons whereas JpaRepository belongs to Spring Data JPA. Difference Table CrudRepository JpaRepository Syntax: public interface CrudRepository<T, ID> extends Repository<T, ID> Syntax: public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> Java-Spring-Boot Picked 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 Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Compile-time and Run-time Polymorphism in Java Difference between Internal and External fragmentation Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2021" }, { "code": null, "e": 451, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time." }, { "code": null, "e": 881, "s": 451, "text": "There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface. " }, { "code": null, "e": 889, "s": 881, "text": "Syntax:" }, { "code": null, "e": 954, "s": 889, "text": "public interface CrudRepository<T, ID> extends Repository<T, ID>" }, { "code": null, "e": 961, "s": 954, "text": "Where:" }, { "code": null, "e": 1040, "s": 961, "text": "T: Domain type that repository manages (Generally the Entity/Model class name)" }, { "code": null, "e": 1185, "s": 1040, "text": "ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)" }, { "code": null, "e": 1194, "s": 1185, "text": "Example:" }, { "code": null, "e": 1276, "s": 1194, "text": "public interface DepartmentRepository extends CrudRepository<Department, Long> {}" }, { "code": null, "e": 1518, "s": 1276, "text": "JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. " }, { "code": null, "e": 1526, "s": 1518, "text": "Syntax:" }, { "code": null, "e": 1631, "s": 1526, "text": "public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>" }, { "code": null, "e": 1638, "s": 1631, "text": "Where:" }, { "code": null, "e": 1717, "s": 1638, "text": "T: Domain type that repository manages (Generally the Entity/Model class name)" }, { "code": null, "e": 1862, "s": 1717, "text": "ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)" }, { "code": null, "e": 1871, "s": 1862, "text": "Example:" }, { "code": null, "e": 1952, "s": 1871, "text": "public interface DepartmentRepository extends JpaRepository<Department, Long> {}" }, { "code": null, "e": 2119, "s": 1952, "text": "Here in the following image Repository, CrudRepository and PagingAndSortingRepository belong to Spring Data Commons whereas JpaRepository belongs to Spring Data JPA. " }, { "code": null, "e": 2136, "s": 2119, "text": "Difference Table" }, { "code": null, "e": 2152, "s": 2136, "text": "CrudRepository " }, { "code": null, "e": 2167, "s": 2152, "text": "JpaRepository " }, { "code": null, "e": 2176, "s": 2167, "text": "Syntax: " }, { "code": null, "e": 2241, "s": 2176, "text": "public interface CrudRepository<T, ID> extends Repository<T, ID>" }, { "code": null, "e": 2249, "s": 2241, "text": "Syntax:" }, { "code": null, "e": 2354, "s": 2249, "text": "public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>" }, { "code": null, "e": 2371, "s": 2354, "text": "Java-Spring-Boot" }, { "code": null, "e": 2378, "s": 2371, "text": "Picked" }, { "code": null, "e": 2397, "s": 2378, "text": "Difference Between" }, { "code": null, "e": 2402, "s": 2397, "text": "Java" }, { "code": null, "e": 2407, "s": 2402, "text": "Java" }, { "code": null, "e": 2505, "s": 2407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2566, "s": 2505, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2634, "s": 2566, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2683, "s": 2634, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 2749, "s": 2683, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 2804, "s": 2749, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 2819, "s": 2804, "text": "Arrays in Java" }, { "code": null, "e": 2863, "s": 2819, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2899, "s": 2863, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2924, "s": 2899, "text": "Reverse a string in Java" } ]
Types of Boltzmann Machines
20 Nov, 2021 Deep Learning models are broadly classified into supervised and unsupervised models. Supervised DL models: Artificial Neural Networks (ANNs) Recurrent Neural Networks (RNNs) Convolutional Neural Networks (CNNs) Unsupervised DL models: Self Organizing Maps (SOMs) Boltzmann Machines Autoencoders Let us learn what exactly Boltzmann machines are, how they work and also implement a recommender system which recommends whether the user likes a movie or not based on the previous movies watched. Boltzmann Machines is an unsupervised DL model in which every node is connected to every other node. That is, unlike the ANNs, CNNs, RNNs and SOMs, the Boltzmann Machines are undirected (or the connections are bidirectional). Boltzmann Machine is not a deterministic DL model but a stochastic or generative DL model. It is rather a representation of a certain system. There are two types of nodes in the Boltzmann Machine — Visible nodes — those nodes which we can and do measure, and the Hidden nodes – those nodes which we cannot or do not measure. Although the node types are different, the Boltzmann machine considers them as the same and everything works as one single system. The training data is fed into the Boltzmann Machine and the weights of the system are adjusted accordingly. Boltzmann machines help us understand abnormalities by learning about the working of the system in normal conditions. Boltzmann Machine Energy-Based Models: Boltzmann Distribution is used in the sampling distribution of the Boltzmann Machine. The Boltzmann distribution is governed by the equation – Pi = e(-∈i/kT)/ ∑e(-∈j/kT) Pi - probability of system being in state i ∈i - Energy of system in state i T - Temperature of the system k - Boltzmann constant ∑e(-∈j/kT) - Sum of values for all possible states of the system Boltzmann Distribution describes different states of the system and thus Boltzmann machines create different states of the machine using this distribution. From the above equation, as the energy of system increases, the probability for the system to be in state ‘i’ decreases. Thus, the system is the most stable in its lowest energy state (a gas is most stable when it spreads). Here, in Boltzmann machines, the energy of the system is defined in terms of the weights of synapses. Once the system is trained and the weights are set, the system always tries to find the lowest energy state for itself by adjusting the weights. Types of Boltzmann Machines: Restricted Boltzmann Machines (RBMs) Deep Belief Networks (DBNs) Deep Boltzmann Machines (DBMs) Restricted Boltzmann Machines (RBMs): In a full Boltzmann machine, each node is connected to every other node and hence the connections grow exponentially. This is the reason we use RBMs. The restrictions in the node connections in RBMs are as follows – Hidden nodes cannot be connected to one another. Visible nodes connected to one another. Energy function example for Restricted Boltzmann Machine – E(v, h) = -∑ aivi - ∑ bjhj - ∑∑ viwi,jhj a, v - biases in the system - constants vi, hj - visible node, hidden node P(v, h) = Probability of being in a certain state P(v, h) = e(-E(v, h))/Z Z - sum if values for all possible states Suppose that we are using our RBM for building a recommender system that works on six (6) movies. RBM learns how to allocate the hidden nodes to certain features. By the process of Contrastive Divergence, we make the RBM close to our set of movies that is our case or scenario. RBM identifies which features are important by the training process. The training data is either 0 or 1 or missing data based on whether a user liked that movie (1), disliked that movie (0) or did not watch the movie (missing data). RBM automatically identifies important features. Contrastive Divergence: RBM adjusts its weights by this method. Using some randomly assigned initial weights, RBM calculates the hidden nodes, which in turn use the same weights to reconstruct the input nodes. Each hidden node is constructed from all the visible nodes and each visible node is reconstructed from all the hidden node and hence, the input is different from the reconstructed input, though the weights are the same. The process continues until the reconstructed input matches the previous input. The process is said to be converged at this stage. This entire procedure is known as Gibbs Sampling. Gibb’s Sampling The Gradient Formula gives the gradient of the log probability of the certain state of the system with respect to the weights of the system. It is given as follows – d/dwij(log(P(v0))) = <vi0 * hj0> - <vi∞ * hj∞> v - visible state, h- hidden state <vi0 * hj0> - initial state of the system <vi∞ * hj∞> - final state of the system P(v0) - probability that the system is in state v0 wij - weights of the system The above equations tell us – how the change in weights of the system will change the log probability of the system to be a particular state. The system tries to end up in the lowest possible energy state (most stable). Instead of continuing the adjusting of weights process until the current input matches the previous one, we can also consider the first few pauses only. It is sufficient to understand how to adjust our curve so as to get the lowest energy state. Therefore, we adjust the weights, redesign the system and energy curve such that we get the lowest energy for the current position. This is known as the Hinton’s shortcut. Hinton’s Shortcut Working of RBM – Illustrative Example – Consider – Mary watches four movies out of the six available movies and rates four of them. Say, she watched m1, m3, m4 and m5 and likes m3, m5 (rated 1) and dislikes the other two, that is m1, m4 (rated 0) whereas the other two movies – m2, m6 are unrated. Now, using our RBM, we will recommend one of these movies for her to watch next. Say – m3, m5 are of ‘Drama’ genre. m1, m4 are of ‘Action’ genre. ‘Dicaprio’ played a role in m5. m3, m5 have won ‘Oscar.’ ‘Tarantino’ directed m4. m2 is of the ‘Action’ genre. m6 is of both the genres ‘Action’ and ‘Drama’, ‘Dicaprio’ acted in it and it has won an ‘Oscar’. We have the following observations – Mary likes m3, m5 and they are of genre ‘Drama,’ she probably likes ‘Drama’ movies. Mary dislikes m1, m4 and they are of action genre, she probably dislikes ‘Action’ movies. Mary likes m3, m5 and they have won an ‘Oscar’, she probably likes an ‘Oscar’ movie. Since ‘Dicaprio’ acted in m5 and Mary likes it, she will probably like a movie in which ‘Dicaprio’ acted. Mary does not like m4 which is directed by Tarantino, she probably dislikes any movie directed by ‘Tarantino’. Therefore, based on the observations and the details of m2, m6; our RBM recommends m6 to Mary (‘Drama’, ‘Dicaprio’ and ‘Oscar’ matches both Mary’s interests and m6). This is how an RBM works and hence is used in recommender systems. Working of RBM Thus, RBMs are used to build Recommender Systems. Deep Belief Networks (DBNs): Suppose we stack several RBMs on top of each other so that the first RBM outputs are the input to the second RBM and so on. Such networks are known as Deep Belief Networks. The connections within each layer are undirected (since each layer is an RBM). Simultaneously, those in between the layers are directed (except the top two layers – the connection between the top two layers is undirected). There are two ways to train the DBNs- Greedy Layer-wise Training Algorithm – The RBMs are trained layer by layer. Once the individual RBMs are trained (that is, the parameters – weights, biases are set), the direction is set up between the DBN layers.Wake-Sleep Algorithm – The DBN is trained all the way up (connections going up – wake) and then down the network (connections going down — sleep). Greedy Layer-wise Training Algorithm – The RBMs are trained layer by layer. Once the individual RBMs are trained (that is, the parameters – weights, biases are set), the direction is set up between the DBN layers. Wake-Sleep Algorithm – The DBN is trained all the way up (connections going up – wake) and then down the network (connections going down — sleep). Therefore, we stack the RBMs, train them, and once we have the parameters trained, we make sure that the connections between the layers only work downwards (except for the top two layers). Deep Boltzmann Machines (DBMs): DBMs are similar to DBNs except that apart from the connections within layers, the connections between the layers are also undirected (unlike DBN in which the connections between layers are directed). DBMs can extract more complex or sophisticated features and hence can be used for more complex tasks. singghakshay Machine Learning Mathematical Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Nov, 2021" }, { "code": null, "e": 138, "s": 52, "text": "Deep Learning models are broadly classified into supervised and unsupervised models. " }, { "code": null, "e": 160, "s": 138, "text": "Supervised DL models:" }, { "code": null, "e": 194, "s": 160, "text": "Artificial Neural Networks (ANNs)" }, { "code": null, "e": 227, "s": 194, "text": "Recurrent Neural Networks (RNNs)" }, { "code": null, "e": 264, "s": 227, "text": "Convolutional Neural Networks (CNNs)" }, { "code": null, "e": 288, "s": 264, "text": "Unsupervised DL models:" }, { "code": null, "e": 316, "s": 288, "text": "Self Organizing Maps (SOMs)" }, { "code": null, "e": 335, "s": 316, "text": "Boltzmann Machines" }, { "code": null, "e": 348, "s": 335, "text": "Autoencoders" }, { "code": null, "e": 545, "s": 348, "text": "Let us learn what exactly Boltzmann machines are, how they work and also implement a recommender system which recommends whether the user likes a movie or not based on the previous movies watched." }, { "code": null, "e": 1453, "s": 545, "text": "Boltzmann Machines is an unsupervised DL model in which every node is connected to every other node. That is, unlike the ANNs, CNNs, RNNs and SOMs, the Boltzmann Machines are undirected (or the connections are bidirectional). Boltzmann Machine is not a deterministic DL model but a stochastic or generative DL model. It is rather a representation of a certain system. There are two types of nodes in the Boltzmann Machine — Visible nodes — those nodes which we can and do measure, and the Hidden nodes – those nodes which we cannot or do not measure. Although the node types are different, the Boltzmann machine considers them as the same and everything works as one single system. The training data is fed into the Boltzmann Machine and the weights of the system are adjusted accordingly. Boltzmann machines help us understand abnormalities by learning about the working of the system in normal conditions." }, { "code": null, "e": 1471, "s": 1453, "text": "Boltzmann Machine" }, { "code": null, "e": 1492, "s": 1471, "text": "Energy-Based Models:" }, { "code": null, "e": 1635, "s": 1492, "text": "Boltzmann Distribution is used in the sampling distribution of the Boltzmann Machine. The Boltzmann distribution is governed by the equation –" }, { "code": null, "e": 1868, "s": 1635, "text": "Pi = e(-∈i/kT)/ ∑e(-∈j/kT) \nPi - probability of system being in state i\n∈i - Energy of system in state i\nT - Temperature of the system\nk - Boltzmann constant\n∑e(-∈j/kT) - Sum of values for all possible states of the system " }, { "code": null, "e": 2495, "s": 1868, "text": "Boltzmann Distribution describes different states of the system and thus Boltzmann machines create different states of the machine using this distribution. From the above equation, as the energy of system increases, the probability for the system to be in state ‘i’ decreases. Thus, the system is the most stable in its lowest energy state (a gas is most stable when it spreads). Here, in Boltzmann machines, the energy of the system is defined in terms of the weights of synapses. Once the system is trained and the weights are set, the system always tries to find the lowest energy state for itself by adjusting the weights." }, { "code": null, "e": 2524, "s": 2495, "text": "Types of Boltzmann Machines:" }, { "code": null, "e": 2561, "s": 2524, "text": "Restricted Boltzmann Machines (RBMs)" }, { "code": null, "e": 2589, "s": 2561, "text": "Deep Belief Networks (DBNs)" }, { "code": null, "e": 2620, "s": 2589, "text": "Deep Boltzmann Machines (DBMs)" }, { "code": null, "e": 2658, "s": 2620, "text": "Restricted Boltzmann Machines (RBMs):" }, { "code": null, "e": 2874, "s": 2658, "text": "In a full Boltzmann machine, each node is connected to every other node and hence the connections grow exponentially. This is the reason we use RBMs. The restrictions in the node connections in RBMs are as follows –" }, { "code": null, "e": 2923, "s": 2874, "text": "Hidden nodes cannot be connected to one another." }, { "code": null, "e": 2963, "s": 2923, "text": "Visible nodes connected to one another." }, { "code": null, "e": 3022, "s": 2963, "text": "Energy function example for Restricted Boltzmann Machine –" }, { "code": null, "e": 3254, "s": 3022, "text": "E(v, h) = -∑ aivi - ∑ bjhj - ∑∑ viwi,jhj\na, v - biases in the system - constants\nvi, hj - visible node, hidden node\nP(v, h) = Probability of being in a certain state\nP(v, h) = e(-E(v, h))/Z\nZ - sum if values for all possible states" }, { "code": null, "e": 3815, "s": 3254, "text": "Suppose that we are using our RBM for building a recommender system that works on six (6) movies. RBM learns how to allocate the hidden nodes to certain features. By the process of Contrastive Divergence, we make the RBM close to our set of movies that is our case or scenario. RBM identifies which features are important by the training process. The training data is either 0 or 1 or missing data based on whether a user liked that movie (1), disliked that movie (0) or did not watch the movie (missing data). RBM automatically identifies important features. " }, { "code": null, "e": 3839, "s": 3815, "text": "Contrastive Divergence:" }, { "code": null, "e": 4427, "s": 3839, "text": "RBM adjusts its weights by this method. Using some randomly assigned initial weights, RBM calculates the hidden nodes, which in turn use the same weights to reconstruct the input nodes. Each hidden node is constructed from all the visible nodes and each visible node is reconstructed from all the hidden node and hence, the input is different from the reconstructed input, though the weights are the same. The process continues until the reconstructed input matches the previous input. The process is said to be converged at this stage. This entire procedure is known as Gibbs Sampling. " }, { "code": null, "e": 4443, "s": 4427, "text": "Gibb’s Sampling" }, { "code": null, "e": 4609, "s": 4443, "text": "The Gradient Formula gives the gradient of the log probability of the certain state of the system with respect to the weights of the system. It is given as follows –" }, { "code": null, "e": 4852, "s": 4609, "text": "d/dwij(log(P(v0))) = <vi0 * hj0> - <vi∞ * hj∞>\nv - visible state, h- hidden state\n<vi0 * hj0> - initial state of the system\n<vi∞ * hj∞> - final state of the system\nP(v0) - probability that the system is in state v0\nwij - weights of the system" }, { "code": null, "e": 5490, "s": 4852, "text": "The above equations tell us – how the change in weights of the system will change the log probability of the system to be a particular state. The system tries to end up in the lowest possible energy state (most stable). Instead of continuing the adjusting of weights process until the current input matches the previous one, we can also consider the first few pauses only. It is sufficient to understand how to adjust our curve so as to get the lowest energy state. Therefore, we adjust the weights, redesign the system and energy curve such that we get the lowest energy for the current position. This is known as the Hinton’s shortcut." }, { "code": null, "e": 5508, "s": 5490, "text": "Hinton’s Shortcut" }, { "code": null, "e": 5548, "s": 5508, "text": "Working of RBM – Illustrative Example –" }, { "code": null, "e": 5894, "s": 5548, "text": "Consider – Mary watches four movies out of the six available movies and rates four of them. Say, she watched m1, m3, m4 and m5 and likes m3, m5 (rated 1) and dislikes the other two, that is m1, m4 (rated 0) whereas the other two movies – m2, m6 are unrated. Now, using our RBM, we will recommend one of these movies for her to watch next. Say – " }, { "code": null, "e": 5923, "s": 5894, "text": "m3, m5 are of ‘Drama’ genre." }, { "code": null, "e": 5953, "s": 5923, "text": "m1, m4 are of ‘Action’ genre." }, { "code": null, "e": 5985, "s": 5953, "text": "‘Dicaprio’ played a role in m5." }, { "code": null, "e": 6010, "s": 5985, "text": "m3, m5 have won ‘Oscar.’" }, { "code": null, "e": 6035, "s": 6010, "text": "‘Tarantino’ directed m4." }, { "code": null, "e": 6064, "s": 6035, "text": "m2 is of the ‘Action’ genre." }, { "code": null, "e": 6161, "s": 6064, "text": "m6 is of both the genres ‘Action’ and ‘Drama’, ‘Dicaprio’ acted in it and it has won an ‘Oscar’." }, { "code": null, "e": 6198, "s": 6161, "text": "We have the following observations –" }, { "code": null, "e": 6282, "s": 6198, "text": "Mary likes m3, m5 and they are of genre ‘Drama,’ she probably likes ‘Drama’ movies." }, { "code": null, "e": 6372, "s": 6282, "text": "Mary dislikes m1, m4 and they are of action genre, she probably dislikes ‘Action’ movies." }, { "code": null, "e": 6457, "s": 6372, "text": "Mary likes m3, m5 and they have won an ‘Oscar’, she probably likes an ‘Oscar’ movie." }, { "code": null, "e": 6563, "s": 6457, "text": "Since ‘Dicaprio’ acted in m5 and Mary likes it, she will probably like a movie in which ‘Dicaprio’ acted." }, { "code": null, "e": 6674, "s": 6563, "text": "Mary does not like m4 which is directed by Tarantino, she probably dislikes any movie directed by ‘Tarantino’." }, { "code": null, "e": 6907, "s": 6674, "text": "Therefore, based on the observations and the details of m2, m6; our RBM recommends m6 to Mary (‘Drama’, ‘Dicaprio’ and ‘Oscar’ matches both Mary’s interests and m6). This is how an RBM works and hence is used in recommender systems." }, { "code": null, "e": 6922, "s": 6907, "text": "Working of RBM" }, { "code": null, "e": 6972, "s": 6922, "text": "Thus, RBMs are used to build Recommender Systems." }, { "code": null, "e": 7001, "s": 6972, "text": "Deep Belief Networks (DBNs):" }, { "code": null, "e": 7435, "s": 7001, "text": "Suppose we stack several RBMs on top of each other so that the first RBM outputs are the input to the second RBM and so on. Such networks are known as Deep Belief Networks. The connections within each layer are undirected (since each layer is an RBM). Simultaneously, those in between the layers are directed (except the top two layers – the connection between the top two layers is undirected). There are two ways to train the DBNs-" }, { "code": null, "e": 7795, "s": 7435, "text": "Greedy Layer-wise Training Algorithm – The RBMs are trained layer by layer. Once the individual RBMs are trained (that is, the parameters – weights, biases are set), the direction is set up between the DBN layers.Wake-Sleep Algorithm – The DBN is trained all the way up (connections going up – wake) and then down the network (connections going down — sleep)." }, { "code": null, "e": 8009, "s": 7795, "text": "Greedy Layer-wise Training Algorithm – The RBMs are trained layer by layer. Once the individual RBMs are trained (that is, the parameters – weights, biases are set), the direction is set up between the DBN layers." }, { "code": null, "e": 8156, "s": 8009, "text": "Wake-Sleep Algorithm – The DBN is trained all the way up (connections going up – wake) and then down the network (connections going down — sleep)." }, { "code": null, "e": 8345, "s": 8156, "text": "Therefore, we stack the RBMs, train them, and once we have the parameters trained, we make sure that the connections between the layers only work downwards (except for the top two layers)." }, { "code": null, "e": 8377, "s": 8345, "text": "Deep Boltzmann Machines (DBMs):" }, { "code": null, "e": 8681, "s": 8377, "text": "DBMs are similar to DBNs except that apart from the connections within layers, the connections between the layers are also undirected (unlike DBN in which the connections between layers are directed). DBMs can extract more complex or sophisticated features and hence can be used for more complex tasks. " }, { "code": null, "e": 8694, "s": 8681, "text": "singghakshay" }, { "code": null, "e": 8711, "s": 8694, "text": "Machine Learning" }, { "code": null, "e": 8724, "s": 8711, "text": "Mathematical" }, { "code": null, "e": 8737, "s": 8724, "text": "Mathematical" }, { "code": null, "e": 8754, "s": 8737, "text": "Machine Learning" } ]
Bayes’ Theorem in Data Mining
04 Jul, 2021 Bayes’ Theorem describes the probability of an event, based on precedent knowledge of conditions which might be related to the event. In other words, Bayes’ Theorem is the add-on of Conditional Probability. With the help of Conditional Probability, one can find out the probability of X given H, and it is denoted by P(X | H). Now Bayes’ Theorem states that if we know Conditional Probability (P(X | H)) then we can find out P(H | X), given the condition that P(X) and P(H) are already known to us. Bayes’ Theorem is named after Thomas Bayes. He first makes use of conditional probability to provide an algorithm which uses evidence to calculate limits on an unknown parameter. Bayes’ Theorem has two types of probabilities : Prior Probability [P(H)]Posterior Probability [P(H/X)] Prior Probability [P(H)] Posterior Probability [P(H/X)] Where, X – X is a data tuple. H – H is some Hypothesis. Prior Probability is the probability of occurring an event before the collection of new data. It is the best logical evaluation of the probability of an outcome which is based on the present knowledge of the event before the inspection is performed. When new data or information is collected then the Prior Probability of an event will be revised to produce a more accurate measure of a possible outcome. This revised probability becomes the Posterior Probability and is calculated using Bayes’ theorem. So, the Posterior Probability is the probability of an event X occurring given that event H has occurred. For example Suppose, three bags have the labels A, B, and C. One bag has a red ball in it, while the other two do not. The prior probability of red ball found in bag B is one-third or 0.333. But when bag C is seen, and the result shows that there is no red ball in that bag, then the posterior probability of red ball found in bag A and B becomes 0.5, as each bag has one out of two chances. Bayes’ Theorem, can be mathematically represented by the equation given below : Where, H and X are the events and, P (X) ≠ 0 P(H/X) – Conditional probability of H. Given that X occurs. P(X/H) – Conditional probability of X. Given that H occurs. P(H) and P(X) – Prior Probabilities of occurring H and X independent of each other. This is called the marginal probability. According to conditional probability, we know that P(X|H) = P(X and H)/P(H) Therefore, P(X and H) = P(X|H) * P(H) ---------- [1] Similarly, P(H|X) = P(H and X)/P(X) = P(X and H)/P(X) [Order does not matter in Joint Probability] Therefore, P(X and H) = P(H|X) * P(X) --------- [2] Now from equation [1] and [2], P(X|H) * P(H) = P(H|X) * P(X) ⇒ P(X|H) = P(H|X) * P(X)/P(H) It means that if we know P(X|H), then we can find out P(H | X), given the condition that P(X) and P(H) are already known to us. Now, let us consider X1, X2, X3.....Xk be a group of events having probability P(Xi), i = 1, 2, 3.....k and for any event H where P(H) > 0. P(Xi|H) = P(Xi and H) / P(H) = P(H|Xi)*P(Xi) / ∑[P(H|Xi)*P(Xi) Tree representation of Bayes’ Theorem To find Reverse Probabilities : Bayes' Theorem P(X1|H) = P(H|X1)*P(X1) / P(H) Where - P(X1) and P(H) are called marginal probabilities. - P(X1) and P(H|X1) is already given. Therefore, P(H) can be calculated as given below : P(H) = P(H|X1)*P(X1) + P(H|X2)*P(X2) + P(H|X3)*P(X3) (This is also known as Total Probability) To find Reverse Probabilities : Bayes' Theorem P(X1|H') = P(H'|X1)*P(X1) / P(H') Now, P(H) can be calculated as P(H') = P(H'|X1)*P(X1) + P(H'|X2)*P(X2) + P(H'|X3)*P(X3) In the real world, there are plenty of applications of the Bayes’ Theorem. Some applications are given below : It can also be used as a building block and starting point for more complex methodologies, For example, The popular Bayesian networks. Used in classification problems and other probability-related questions. Bayesian inference, a particular approach to statistical inference. In genetics, Bayes’ theorem can be used to calculate the probability of an individual having a specific genotype. 1. SpamAssassin works as a mail filter to identify the spam in which users train the system. In emails, it considers patterns in the words which are marked as spam by the users. For Example, it may have learned that the word “release” is marked as spam in 30% of the emails. Concluding 0.8% of non-spam mails which includes the word “release” and 40% of all emails which are received by the user is spam. Find the probability that a mail is a spam if the word “release” seems in it. Solution : Given, P(Release | Spam) = 0.30 P(Release | Non Spam) = 0.008 P(Spam) = 0.40 => P(Non Spam) = 0.40 P(Spam | Release) = ? Now, using Bayes’ Theorem: P(Spam | Release) = P(Release | Spam) * P(Spam) / P(Release) = 0.30 * 0.40 / (0.40 * 0.30 + 0.30 * 0.008) = 0.980 Hence, the required probability is 0.980. 2. Bag1 contains 4 white and 8 black balls and Bag2 contains 5 white and 3 black balls. From one of the bag one ball is drawn at random and the ball which is drawn comes out as black. Find the probability that the ball is drawn from Bag1. Solution: Given, Let E1, E2 and A be the three events where, E1 = Event of selecting Bag1 E2 = Event of selecting Bag2 A = Event of drawing black ball Now, P(E1) = P(E2) = 1/2 P(drawing a black ball from Bag1) = P(A|E1) = 8/12 = 2/3 P(drawing a black ball from Bag2) = P(A|E2) = 3/8 By using Bayes' Theorem, the probability of drawing a black ball from Bag1, P(E1|A) = P(A|E1) * P(E1) / P(A|E1) * P(E1) + P(A|E2) * P(E2) [P(A|E1) * P(E1) + P(A|E2) * P(E2) = Total Probability] = (2/3 * 1/2) / (2/3 * 1/2 + 3/8 * 1/2) = 16/25 Hence, the probability that the ball is drawn from Bag1 is 16/25 datamining Picked Data Mining Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 236, "s": 28, "text": "Bayes’ Theorem describes the probability of an event, based on precedent knowledge of conditions which might be related to the event. In other words, Bayes’ Theorem is the add-on of Conditional Probability. " }, { "code": null, "e": 528, "s": 236, "text": "With the help of Conditional Probability, one can find out the probability of X given H, and it is denoted by P(X | H). Now Bayes’ Theorem states that if we know Conditional Probability (P(X | H)) then we can find out P(H | X), given the condition that P(X) and P(H) are already known to us." }, { "code": null, "e": 755, "s": 528, "text": "Bayes’ Theorem is named after Thomas Bayes. He first makes use of conditional probability to provide an algorithm which uses evidence to calculate limits on an unknown parameter. Bayes’ Theorem has two types of probabilities :" }, { "code": null, "e": 810, "s": 755, "text": "Prior Probability [P(H)]Posterior Probability [P(H/X)]" }, { "code": null, "e": 835, "s": 810, "text": "Prior Probability [P(H)]" }, { "code": null, "e": 866, "s": 835, "text": "Posterior Probability [P(H/X)]" }, { "code": null, "e": 873, "s": 866, "text": "Where," }, { "code": null, "e": 896, "s": 873, "text": "X – X is a data tuple." }, { "code": null, "e": 922, "s": 896, "text": "H – H is some Hypothesis." }, { "code": null, "e": 1172, "s": 922, "text": "Prior Probability is the probability of occurring an event before the collection of new data. It is the best logical evaluation of the probability of an outcome which is based on the present knowledge of the event before the inspection is performed." }, { "code": null, "e": 1532, "s": 1172, "text": "When new data or information is collected then the Prior Probability of an event will be revised to produce a more accurate measure of a possible outcome. This revised probability becomes the Posterior Probability and is calculated using Bayes’ theorem. So, the Posterior Probability is the probability of an event X occurring given that event H has occurred." }, { "code": null, "e": 1545, "s": 1532, "text": "For example " }, { "code": null, "e": 1925, "s": 1545, "text": "Suppose, three bags have the labels A, B, and C. One bag has a red ball in it, while the other two do not. The prior probability of red ball found in bag B is one-third or 0.333. But when bag C is seen, and the result shows that there is no red ball in that bag, then the posterior probability of red ball found in bag A and B becomes 0.5, as each bag has one out of two chances." }, { "code": null, "e": 2005, "s": 1925, "text": "Bayes’ Theorem, can be mathematically represented by the equation given below :" }, { "code": null, "e": 2012, "s": 2005, "text": "Where," }, { "code": null, "e": 2040, "s": 2012, "text": "H and X are the events and," }, { "code": null, "e": 2051, "s": 2040, "text": "P (X) ≠ 0" }, { "code": null, "e": 2090, "s": 2051, "text": "P(H/X) – Conditional probability of H." }, { "code": null, "e": 2137, "s": 2090, "text": " Given that X occurs." }, { "code": null, "e": 2176, "s": 2137, "text": "P(X/H) – Conditional probability of X." }, { "code": null, "e": 2223, "s": 2176, "text": " Given that H occurs." }, { "code": null, "e": 2307, "s": 2223, "text": "P(H) and P(X) – Prior Probabilities of occurring H and X independent of each other." }, { "code": null, "e": 2385, "s": 2307, "text": " This is called the marginal probability." }, { "code": null, "e": 2898, "s": 2385, "text": "According to conditional probability, we know that\nP(X|H) = P(X and H)/P(H)\n\nTherefore,\nP(X and H) = P(X|H) * P(H) ---------- [1]\n\nSimilarly,\nP(H|X) = P(H and X)/P(X)\n = P(X and H)/P(X) [Order does not matter in Joint Probability]\n\nTherefore,\nP(X and H) = P(H|X) * P(X) --------- [2]\n\nNow from equation [1] and [2],\nP(X|H) * P(H) = P(H|X) * P(X)\n\n⇒ P(X|H) = P(H|X) * P(X)/P(H)\n\nIt means that if we know P(X|H), then we can find out P(H | X), \ngiven the condition that P(X) and P(H) are already known to us." }, { "code": null, "e": 3040, "s": 2900, "text": "Now, let us consider X1, X2, X3.....Xk be a group of events having probability P(Xi), i = 1, 2, 3.....k and for any event H where P(H) > 0." }, { "code": null, "e": 3112, "s": 3040, "text": "P(Xi|H) = P(Xi and H) / P(H)\n = P(H|Xi)*P(Xi) / ∑[P(H|Xi)*P(Xi) " }, { "code": null, "e": 3152, "s": 3114, "text": "Tree representation of Bayes’ Theorem" }, { "code": null, "e": 3482, "s": 3152, "text": "To find Reverse Probabilities : Bayes' Theorem\nP(X1|H) = P(H|X1)*P(X1) / P(H)\n\nWhere \n- P(X1) and P(H) are called marginal probabilities.\n- P(X1) and P(H|X1) is already given.\n\nTherefore, P(H) can be calculated as given below :\nP(H) = P(H|X1)*P(X1) + P(H|X2)*P(X2) + P(H|X3)*P(X3)\n (This is also known as Total Probability)" }, { "code": null, "e": 3652, "s": 3482, "text": "To find Reverse Probabilities : Bayes' Theorem\nP(X1|H') = P(H'|X1)*P(X1) / P(H')\n\nNow, P(H) can be calculated as\nP(H') = P(H'|X1)*P(X1) + P(H'|X2)*P(X2) + P(H'|X3)*P(X3)" }, { "code": null, "e": 3764, "s": 3652, "text": "In the real world, there are plenty of applications of the Bayes’ Theorem. Some applications are given below : " }, { "code": null, "e": 3899, "s": 3764, "text": "It can also be used as a building block and starting point for more complex methodologies, For example, The popular Bayesian networks." }, { "code": null, "e": 3972, "s": 3899, "text": "Used in classification problems and other probability-related questions." }, { "code": null, "e": 4040, "s": 3972, "text": "Bayesian inference, a particular approach to statistical inference." }, { "code": null, "e": 4154, "s": 4040, "text": "In genetics, Bayes’ theorem can be used to calculate the probability of an individual having a specific genotype." }, { "code": null, "e": 4639, "s": 4154, "text": "1. SpamAssassin works as a mail filter to identify the spam in which users train the system. In emails, it considers patterns in the words which are marked as spam by the users. For Example, it may have learned that the word “release” is marked as spam in 30% of the emails. Concluding 0.8% of non-spam mails which includes the word “release” and 40% of all emails which are received by the user is spam. Find the probability that a mail is a spam if the word “release” seems in it." }, { "code": null, "e": 5029, "s": 4639, "text": "Solution :\n\nGiven,\nP(Release | Spam) = 0.30\nP(Release | Non Spam) = 0.008\nP(Spam) = 0.40 \n => P(Non Spam) = 0.40\n \nP(Spam | Release) = ?\n\nNow, using Bayes’ Theorem:\nP(Spam | Release) = P(Release | Spam) * P(Spam) / P(Release)\n = 0.30 * 0.40 / (0.40 * 0.30 + 0.30 * 0.008)\n = 0.980\n \nHence, the required probability is 0.980." }, { "code": null, "e": 5269, "s": 5029, "text": "2. Bag1 contains 4 white and 8 black balls and Bag2 contains 5 white and 3 black balls. From one of the bag one ball is drawn at random and the ball which is drawn comes out as black. Find the probability that the ball is drawn from Bag1." }, { "code": null, "e": 5906, "s": 5269, "text": "Solution:\n\nGiven,\nLet E1, E2 and A be the three events where,\nE1 = Event of selecting Bag1\nE2 = Event of selecting Bag2\nA = Event of drawing black ball\n\nNow, \nP(E1) = P(E2) = 1/2\nP(drawing a black ball from Bag1) = P(A|E1) = 8/12 = 2/3\nP(drawing a black ball from Bag2) = P(A|E2) = 3/8 \n\nBy using Bayes' Theorem, the probability of drawing a black ball from Bag1,\nP(E1|A) = P(A|E1) * P(E1) / P(A|E1) * P(E1) + P(A|E2) * P(E2) \n [P(A|E1) * P(E1) + P(A|E2) * P(E2) = Total Probability]\n = (2/3 * 1/2) / (2/3 * 1/2 + 3/8 * 1/2)\n = 16/25\n \nHence, the probability that the ball is drawn from Bag1 is 16/25" }, { "code": null, "e": 5920, "s": 5909, "text": "datamining" }, { "code": null, "e": 5927, "s": 5920, "text": "Picked" }, { "code": null, "e": 5939, "s": 5927, "text": "Data Mining" } ]
Scala List indexOf() method with example
29 Jul, 2019 The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Method Definition: def indexOf(elem: A, from: Int): Int Return Type: It returns the index of the element present in the argument. Example #1: // Scala program of indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying indexOf method val result = m1.indexOf(9) // Displays output println(result) }} 3 Example #2: // Scala program of indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying indexOf method val result = m1.indexOf(3) // Displays output println(result) }} 0 Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2019" }, { "code": null, "e": 151, "s": 28, "text": "The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument." }, { "code": null, "e": 207, "s": 151, "text": "Method Definition: def indexOf(elem: A, from: Int): Int" }, { "code": null, "e": 281, "s": 207, "text": "Return Type: It returns the index of the element present in the argument." }, { "code": null, "e": 293, "s": 281, "text": "Example #1:" }, { "code": "// Scala program of indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying indexOf method val result = m1.indexOf(9) // Displays output println(result) }} ", "e": 634, "s": 293, "text": null }, { "code": null, "e": 637, "s": 634, "text": "3\n" }, { "code": null, "e": 649, "s": 637, "text": "Example #2:" }, { "code": "// Scala program of indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying indexOf method val result = m1.indexOf(3) // Displays output println(result) }} ", "e": 990, "s": 649, "text": null }, { "code": null, "e": 993, "s": 990, "text": "0\n" }, { "code": null, "e": 999, "s": 993, "text": "Scala" }, { "code": null, "e": 1010, "s": 999, "text": "Scala-list" }, { "code": null, "e": 1023, "s": 1010, "text": "Scala-Method" }, { "code": null, "e": 1029, "s": 1023, "text": "Scala" } ]
Python | Pandas Series.argsort()
27 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.argsort() function returns the indices that would sort the underlying data of the given series object. Syntax: Series.argsort(axis=0, kind=’quicksort’, order=None) Parameter :axis : Has no effect but is accepted for compatibility with numpy.kind : {‘mergesort’, ‘quicksort’, ‘heapsort’}, default ‘quicksort’order : Has no effect but is accepted for compatibility with numpy. Returns : argsorted : Series, with -1 indicated where nan values are present Example #1: Use Series.argsort() function to return the sequence of index which will sort the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Coca Cola 34 Sprite 5 Coke 13 Fanta 32 Dew 4 ThumbsUp 15 dtype: int64 Now we will use Series.argsort() function to return a sequence of indices which will sort the underlying data of the given series object. # return the indices which will# sort the seriesresult = sr.argsort() # Print the resultprint(result) # Let's sort the series using the resultprint(sr[result]) Output : Coca Cola 4 Sprite 1 Coke 2 Fanta 5 Dew 3 ThumbsUp 0 dtype: int64 Dew 4 Sprite 5 Coke 13 ThumbsUp 15 Fanta 32 Coca Cola 34 dtype: int64 As we can see in the output, the Series.argsort() function has successfully returned a series object containing the indices which will sort the given series object. Example #2 : Use Series.argsort() function to return the sequence of index which will sort the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : 2010-12-31 08:45:00 11.0 2011-12-31 08:45:00 21.0 2012-12-31 08:45:00 8.0 2013-12-31 08:45:00 18.0 2014-12-31 08:45:00 65.0 2015-12-31 08:45:00 18.0 2016-12-31 08:45:00 32.0 2017-12-31 08:45:00 10.0 2018-12-31 08:45:00 5.0 2019-12-31 08:45:00 32.0 2020-12-31 08:45:00 NaN Freq: A-DEC, dtype: float64 Now we will use Series.argsort() function to return a sequence of indices which will sort the underlying data of the given series object. # return the indices which will# sort the seriesresult = sr.argsort() # Print the resultprint(result) # Let's sort the series using the resultprint(sr[result]) Output : 2010-12-31 08:45:00 8 2011-12-31 08:45:00 2 2012-12-31 08:45:00 7 2013-12-31 08:45:00 0 2014-12-31 08:45:00 3 2015-12-31 08:45:00 5 2016-12-31 08:45:00 1 2017-12-31 08:45:00 6 2018-12-31 08:45:00 9 2019-12-31 08:45:00 4 2020-12-31 08:45:00 -1 Freq: A-DEC, dtype: int64 2018-12-31 08:45:00 5.0 2012-12-31 08:45:00 8.0 2017-12-31 08:45:00 10.0 2010-12-31 08:45:00 11.0 2013-12-31 08:45:00 18.0 2015-12-31 08:45:00 18.0 2011-12-31 08:45:00 21.0 2016-12-31 08:45:00 32.0 2019-12-31 08:45:00 32.0 2014-12-31 08:45:00 65.0 2020-12-31 08:45:00 NaN dtype: float64 As we can see in the output, the Series.argsort() function has successfully returned a series object containing the indices which will sort the given series object. Notice the function has returned -1 as the index position for the missing values. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 402, "s": 285, "text": "Pandas Series.argsort() function returns the indices that would sort the underlying data of the given series object." }, { "code": null, "e": 463, "s": 402, "text": "Syntax: Series.argsort(axis=0, kind=’quicksort’, order=None)" }, { "code": null, "e": 674, "s": 463, "text": "Parameter :axis : Has no effect but is accepted for compatibility with numpy.kind : {‘mergesort’, ‘quicksort’, ‘heapsort’}, default ‘quicksort’order : Has no effect but is accepted for compatibility with numpy." }, { "code": null, "e": 751, "s": 674, "text": "Returns : argsorted : Series, with -1 indicated where nan values are present" }, { "code": null, "e": 889, "s": 751, "text": "Example #1: Use Series.argsort() function to return the sequence of index which will sort the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1145, "s": 889, "text": null }, { "code": null, "e": 1154, "s": 1145, "text": "Output :" }, { "code": null, "e": 1263, "s": 1154, "text": "Coca Cola 34\nSprite 5\nCoke 13\nFanta 32\nDew 4\nThumbsUp 15\ndtype: int64" }, { "code": null, "e": 1401, "s": 1263, "text": "Now we will use Series.argsort() function to return a sequence of indices which will sort the underlying data of the given series object." }, { "code": "# return the indices which will# sort the seriesresult = sr.argsort() # Print the resultprint(result) # Let's sort the series using the resultprint(sr[result])", "e": 1563, "s": 1401, "text": null }, { "code": null, "e": 1572, "s": 1563, "text": "Output :" }, { "code": null, "e": 1785, "s": 1572, "text": "Coca Cola 4\nSprite 1\nCoke 2\nFanta 5\nDew 3\nThumbsUp 0\ndtype: int64\n\nDew 4\nSprite 5\nCoke 13\nThumbsUp 15\nFanta 32\nCoca Cola 34\ndtype: int64" }, { "code": null, "e": 2089, "s": 1785, "text": "As we can see in the output, the Series.argsort() function has successfully returned a series object containing the indices which will sort the given series object. Example #2 : Use Series.argsort() function to return the sequence of index which will sort the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 2390, "s": 2089, "text": null }, { "code": null, "e": 2399, "s": 2390, "text": "Output :" }, { "code": null, "e": 2735, "s": 2399, "text": "2010-12-31 08:45:00 11.0\n2011-12-31 08:45:00 21.0\n2012-12-31 08:45:00 8.0\n2013-12-31 08:45:00 18.0\n2014-12-31 08:45:00 65.0\n2015-12-31 08:45:00 18.0\n2016-12-31 08:45:00 32.0\n2017-12-31 08:45:00 10.0\n2018-12-31 08:45:00 5.0\n2019-12-31 08:45:00 32.0\n2020-12-31 08:45:00 NaN\nFreq: A-DEC, dtype: float64" }, { "code": null, "e": 2873, "s": 2735, "text": "Now we will use Series.argsort() function to return a sequence of indices which will sort the underlying data of the given series object." }, { "code": "# return the indices which will# sort the seriesresult = sr.argsort() # Print the resultprint(result) # Let's sort the series using the resultprint(sr[result])", "e": 3035, "s": 2873, "text": null }, { "code": null, "e": 3044, "s": 3035, "text": "Output :" }, { "code": null, "e": 3669, "s": 3044, "text": "2010-12-31 08:45:00 8\n2011-12-31 08:45:00 2\n2012-12-31 08:45:00 7\n2013-12-31 08:45:00 0\n2014-12-31 08:45:00 3\n2015-12-31 08:45:00 5\n2016-12-31 08:45:00 1\n2017-12-31 08:45:00 6\n2018-12-31 08:45:00 9\n2019-12-31 08:45:00 4\n2020-12-31 08:45:00 -1\nFreq: A-DEC, dtype: int64\n\n2018-12-31 08:45:00 5.0\n2012-12-31 08:45:00 8.0\n2017-12-31 08:45:00 10.0\n2010-12-31 08:45:00 11.0\n2013-12-31 08:45:00 18.0\n2015-12-31 08:45:00 18.0\n2011-12-31 08:45:00 21.0\n2016-12-31 08:45:00 32.0\n2019-12-31 08:45:00 32.0\n2014-12-31 08:45:00 65.0\n2020-12-31 08:45:00 NaN\ndtype: float64" }, { "code": null, "e": 3916, "s": 3669, "text": "As we can see in the output, the Series.argsort() function has successfully returned a series object containing the indices which will sort the given series object. Notice the function has returned -1 as the index position for the missing values." }, { "code": null, "e": 3937, "s": 3916, "text": "Python pandas-series" }, { "code": null, "e": 3966, "s": 3937, "text": "Python pandas-series-methods" }, { "code": null, "e": 3980, "s": 3966, "text": "Python-pandas" }, { "code": null, "e": 3987, "s": 3980, "text": "Python" } ]
Using Leaflet.js to show maps in a webpage
08 May, 2020 Maps are incredibly helpful for showing locations on a website. Use cases of maps include showing the location of an office address, which is a better option than just showing an image or a text address. It can also be used for marking points of interest in a tourist location so that the visitor can plan by looking at all the nearby areas. Leaflet.js is a JavaScript library that makes it extremely easy to show maps on a webpage and interact with it. This guide would attempt to give a simple introduction to using Leaflet.js to display map and display the required area on the map. We will start by declaring the HTML needed to display the map. Using leaflet.js requires us to import a CSS file for the map styling and the JavaScript file for the functionality of the map. The latest version of both can be found at ” https://leafletjs.com/download.html ” We will start by defining the area where the map has to be displayed. We first create a div with an id of “map” so that it could be accessed by the script. We will then define the height and width of the map object. Otherwise, the map would not display. We can specify any dimension required here. <!DOCTYPE html><html> <head> <title>Leaflet.js Guide</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Get the leaflet CSS file --> <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /></head> <body> <h1>My Leafletjs Map</h1> <!-- Specify the map and it's dimensions --> <div id="map" style="width: 960px; height: 500px"></div> <!-- Get the leaflet JavaScript file --> <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script></body> </html> Mobile VersionThe map can be shown full screen on a mobile device, like a web application. This is possible by making the body element and the div containing the map fill both the height and width of the screen completely. This can be done by giving both these values as 100% or 100 view units. JavaScript portionWe will be writing the JavaScript portion of the implementation here. We will start by initializing the map with the map() method. The id we have to declare earlier is given to this method as a parameter. This initialized map is stored in a variable, which can be used later to add more functionalities.// Initialize the leaflet mapconst map = L.map('map'); // Initialize the leaflet mapconst map = L.map('map'); Running the code now would show an empty area with the map controls. This means that our plugin has been successfully initialized. The reason we don’t see any map information is that we have to specify tile information. The whole map of the world is not possible to be loaded at once. Hence, it is divided into multiple tiles. Only the tiles in the user’s current view are updated. This saves bandwidth and makes the entire process of loading maps faster. This is done through an API that keeps providing and updating the tile images for the given parameters. We will be using the OpenStreetMap API to get our tilemaps for the map. The L.tileLayer() method accepts a URL to the API and automatically gets the required tilemap for the current user position. Using OpenStreetMap requires one to attribute them for their work, hence we will be attributed for them in the attribution parameter of the method. This tile layer will be added to the map using the addTo() method in the end. The last step one has to do before setting up the map is setting a view, that is the area of the world that has to be displayed. This is done using the setView() method. This method takes in a pair of latitude and longitude and a zoom value. The zoom value determines how close the view is to the surface. Increasing this value gets the view more closer to the ground. Let us set the view to that of the Eiffel Tower which has the co-ordinates 48.8584 and 2.2945. The zoom value is set to 16 for a decent view.// Get the tile layer from OpenStreetMapsL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map); // Set the view of the map// with the latitude, longitude and the zoom valuemap.setView([48.8584, 2.2945], 16); // Get the tile layer from OpenStreetMapsL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map); // Set the view of the map// with the latitude, longitude and the zoom valuemap.setView([48.8584, 2.2945], 16); Reopening the webpage, we will finally see a map that has all the information for the current location, and the Eiffel Tower at the center of the map. The leaflet can also show the view based on the current location by using locate() method. It takes in an object that has setView property set to true and a maxZoom value set to a maximum value. This command will ask for the user’s location and automatically set the view to that location. // Ask for current location and navigate to that areamap.locate({setView: true, maxZoom: 16}); Showing markers on the map Leaflet can be used to mark points on the map. This is done using the marker() method. It accepts the coordinates where the marker would be shown. // Show a market at the position of the Eiffel Towerlet eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map); // Bind popup to the marker with a popupeiffelMarker.bindPopup("Eiffel Tower").openPopup(); We can also add a popup to the marker that would show the name of the marker by using the bindPopup() method. This popup can be opened by default using the openPopup() method. Hence, we have successfully created a map using the Leaflet.js library and learnt to view a specific position of the world. Final Output: Complete Code: <!DOCTYPE html><html><head><title>Leaflet.js Guide</title><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><!-- Get the leaflet CSS file --><link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /></head><body><h1>My Leafletjs Map</h1><!-- Specify the map and it's dimensions --><div id="map" style="width: 960px; height: 500px"></div> <!-- Get the leaflet JavaScript file --><script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script><script> // Initialize the map const map = L.map('map') // Get the tile layer from OpenStreetMaps L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); // Set the view of the map // with the latitude, longitude and the zoom value map.setView([48.8584, 2.2945], 16); // Set the map view to the user's location // Uncomment below to set map according to user location // map.locate({setView: true, maxZoom: 16}); // Show a market at the position of the Eiffel Tower let eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map); // Bind popup to the marker with a popup eiffelMarker.bindPopup("Eiffel Tower").openPopup();</script></body></html> Output: javascript-map JavaScript Write From Home 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 Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2020" }, { "code": null, "e": 370, "s": 28, "text": "Maps are incredibly helpful for showing locations on a website. Use cases of maps include showing the location of an office address, which is a better option than just showing an image or a text address. It can also be used for marking points of interest in a tourist location so that the visitor can plan by looking at all the nearby areas." }, { "code": null, "e": 614, "s": 370, "text": "Leaflet.js is a JavaScript library that makes it extremely easy to show maps on a webpage and interact with it. This guide would attempt to give a simple introduction to using Leaflet.js to display map and display the required area on the map." }, { "code": null, "e": 888, "s": 614, "text": "We will start by declaring the HTML needed to display the map. Using leaflet.js requires us to import a CSS file for the map styling and the JavaScript file for the functionality of the map. The latest version of both can be found at ” https://leafletjs.com/download.html ”" }, { "code": null, "e": 1186, "s": 888, "text": "We will start by defining the area where the map has to be displayed. We first create a div with an id of “map” so that it could be accessed by the script. We will then define the height and width of the map object. Otherwise, the map would not display. We can specify any dimension required here." }, { "code": "<!DOCTYPE html><html> <head> <title>Leaflet.js Guide</title> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- Get the leaflet CSS file --> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/dist/leaflet.css\"integrity=\"sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==\" crossorigin=\"\" /></head> <body> <h1>My Leafletjs Map</h1> <!-- Specify the map and it's dimensions --> <div id=\"map\" style=\"width: 960px; height: 500px\"></div> <!-- Get the leaflet JavaScript file --> <script src=\"https://unpkg.com/[email protected]/dist/leaflet.js\" integrity=\"sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==\" crossorigin=\"\"></script></body> </html>", "e": 1998, "s": 1186, "text": null }, { "code": null, "e": 2293, "s": 1998, "text": "Mobile VersionThe map can be shown full screen on a mobile device, like a web application. This is possible by making the body element and the div containing the map fill both the height and width of the screen completely. This can be done by giving both these values as 100% or 100 view units." }, { "code": null, "e": 2381, "s": 2293, "text": "JavaScript portionWe will be writing the JavaScript portion of the implementation here." }, { "code": null, "e": 2669, "s": 2381, "text": "We will start by initializing the map with the map() method. The id we have to declare earlier is given to this method as a parameter. This initialized map is stored in a variable, which can be used later to add more functionalities.// Initialize the leaflet mapconst map = L.map('map');" }, { "code": "// Initialize the leaflet mapconst map = L.map('map');", "e": 2724, "s": 2669, "text": null }, { "code": null, "e": 2944, "s": 2724, "text": "Running the code now would show an empty area with the map controls. This means that our plugin has been successfully initialized. The reason we don’t see any map information is that we have to specify tile information." }, { "code": null, "e": 3180, "s": 2944, "text": "The whole map of the world is not possible to be loaded at once. Hence, it is divided into multiple tiles. Only the tiles in the user’s current view are updated. This saves bandwidth and makes the entire process of loading maps faster." }, { "code": null, "e": 3356, "s": 3180, "text": "This is done through an API that keeps providing and updating the tile images for the given parameters. We will be using the OpenStreetMap API to get our tilemaps for the map." }, { "code": null, "e": 3481, "s": 3356, "text": "The L.tileLayer() method accepts a URL to the API and automatically gets the required tilemap for the current user position." }, { "code": null, "e": 3707, "s": 3481, "text": "Using OpenStreetMap requires one to attribute them for their work, hence we will be attributed for them in the attribution parameter of the method. This tile layer will be added to the map using the addTo() method in the end." }, { "code": null, "e": 4076, "s": 3707, "text": "The last step one has to do before setting up the map is setting a view, that is the area of the world that has to be displayed. This is done using the setView() method. This method takes in a pair of latitude and longitude and a zoom value. The zoom value determines how close the view is to the surface. Increasing this value gets the view more closer to the ground." }, { "code": null, "e": 4650, "s": 4076, "text": "Let us set the view to that of the Eiffel Tower which has the co-ordinates 48.8584 and 2.2945. The zoom value is set to 16 for a decent view.// Get the tile layer from OpenStreetMapsL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'}).addTo(map); // Set the view of the map// with the latitude, longitude and the zoom valuemap.setView([48.8584, 2.2945], 16);" }, { "code": "// Get the tile layer from OpenStreetMapsL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'}).addTo(map); // Set the view of the map// with the latitude, longitude and the zoom valuemap.setView([48.8584, 2.2945], 16);", "e": 5083, "s": 4650, "text": null }, { "code": null, "e": 5234, "s": 5083, "text": "Reopening the webpage, we will finally see a map that has all the information for the current location, and the Eiffel Tower at the center of the map." }, { "code": null, "e": 5524, "s": 5234, "text": "The leaflet can also show the view based on the current location by using locate() method. It takes in an object that has setView property set to true and a maxZoom value set to a maximum value. This command will ask for the user’s location and automatically set the view to that location." }, { "code": "// Ask for current location and navigate to that areamap.locate({setView: true, maxZoom: 16});", "e": 5619, "s": 5524, "text": null }, { "code": null, "e": 5646, "s": 5619, "text": "Showing markers on the map" }, { "code": null, "e": 5793, "s": 5646, "text": "Leaflet can be used to mark points on the map. This is done using the marker() method. It accepts the coordinates where the marker would be shown." }, { "code": "// Show a market at the position of the Eiffel Towerlet eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map); // Bind popup to the marker with a popupeiffelMarker.bindPopup(\"Eiffel Tower\").openPopup();", "e": 5996, "s": 5793, "text": null }, { "code": null, "e": 6172, "s": 5996, "text": "We can also add a popup to the marker that would show the name of the marker by using the bindPopup() method. This popup can be opened by default using the openPopup() method." }, { "code": null, "e": 6296, "s": 6172, "text": "Hence, we have successfully created a map using the Leaflet.js library and learnt to view a specific position of the world." }, { "code": null, "e": 6310, "s": 6296, "text": "Final Output:" }, { "code": null, "e": 6325, "s": 6310, "text": "Complete Code:" }, { "code": "<!DOCTYPE html><html><head><title>Leaflet.js Guide</title><meta charset=\"utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><!-- Get the leaflet CSS file --><link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/dist/leaflet.css\" integrity=\"sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==\" crossorigin=\"\" /></head><body><h1>My Leafletjs Map</h1><!-- Specify the map and it's dimensions --><div id=\"map\" style=\"width: 960px; height: 500px\"></div> <!-- Get the leaflet JavaScript file --><script src=\"https://unpkg.com/[email protected]/dist/leaflet.js\" integrity=\"sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==\" crossorigin=\"\"></script><script> // Initialize the map const map = L.map('map') // Get the tile layer from OpenStreetMaps L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // Specify the maximum zoom of the map maxZoom: 19, // Set the attribution for OpenStreetMaps attribution: '© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors' }).addTo(map); // Set the view of the map // with the latitude, longitude and the zoom value map.setView([48.8584, 2.2945], 16); // Set the map view to the user's location // Uncomment below to set map according to user location // map.locate({setView: true, maxZoom: 16}); // Show a market at the position of the Eiffel Tower let eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map); // Bind popup to the marker with a popup eiffelMarker.bindPopup(\"Eiffel Tower\").openPopup();</script></body></html>", "e": 8041, "s": 6325, "text": null }, { "code": null, "e": 8049, "s": 8041, "text": "Output:" }, { "code": null, "e": 8064, "s": 8049, "text": "javascript-map" }, { "code": null, "e": 8075, "s": 8064, "text": "JavaScript" }, { "code": null, "e": 8091, "s": 8075, "text": "Write From Home" }, { "code": null, "e": 8189, "s": 8091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8250, "s": 8189, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8290, "s": 8250, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8332, "s": 8290, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8373, "s": 8332, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 8395, "s": 8373, "text": "JavaScript | Promises" }, { "code": null, "e": 8431, "s": 8395, "text": "Convert integer to string in Python" }, { "code": null, "e": 8467, "s": 8431, "text": "Convert string to integer in Python" }, { "code": null, "e": 8528, "s": 8467, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 8544, "s": 8528, "text": "Python infinity" } ]