title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to Build an App in R Shiny | by Mate Pocs | Towards Data Science
|
Shiny is an R package that lets you build interactive web apps. All you need is R, no HTML, CSS, or JavaScript — although you certainly have the option to enhance your app with them. You can run the app on your computer, host on your own server, or use RStudio’s cloud service.
In this post, I am going to walk through the process of building a simple data analysis app from scratch. You can find a lot of excellent guides for the basics out there, my aim was to take it a few tiny steps further: we are going to do some dynamic UI updates, dynamic outputs, an action button, panel navigation, etc.
Please note that it’s not a “serious” data analysis app, my purpose was to showcase different functionalities of shiny that might come in handy. However, once we are finished, it should be pretty easy to add new functionalities to our code.
You can have a look at the app we are going to build on shinyapps.io: https://matepocs.shinyapps.io/data_analyser/.
The underlying code is on my GitHub.
Shiny is a very well documented package, with excellent guides on its website. In fact, it’s a bit too well documented, and it’s easy to get lost in the maze of getting started videos, tutorials, written guides, articles, etc.
I personally found Mastering Shiny by Hadley Wickham to be a very good and compact source, highly recommend it.
This is the high-level design sketch of what we want our app to be able to do.
The user:
imports a .csv file;
selects up to 2 numerical and 1 factor type variables from the columns.
Then the app:
draws a plot;
creates summary tables.
The funny part is that we want the outputs to be different based on what type of columns we selected — we want a different plot if it’s just a factor variable selected, and a more complicated one if we have numerical variables by a factor.
We are going to work in RStudio and R. To use shiny, you first need to install the package:
install.packages(“shiny”)
(The other packages we are also going to use: data.table, ggplot2, you might need to install them too. I assume familiarity with these packages going forward.)
Next, we need to create a folder with the name of the app. I called mine data_analyser. We will keep working inside this folder.
The framework of a shiny app is pretty simple: one R script that has to be called app.R. So we are going to put one inside our data_analyser folder.
(Note: you might find the framework confusing if you read some older guides. Instead of an app.R that contains the UI and the server functionalities, you used to need precisely two scripts: a server.R, and a ui.R. That old approach still works for legacy reasons, but I think it’s not recommended. Additionally, you can have different scripts in the folder, and source them in your app script. So you don’t have to put everything in one script like we are going to do now, you can store your server function in a separate server.R script and source it, just know that it’s not a requirement.)
The minimum Shiny app framework looks something like this:
library(shiny)ui <- fluidPage()server <- function(input, output){}shinyApp(ui = ui, server = server)
You can copy this to your app.R, and should be able to run it by either using a keyboard shortcut (like Cmd + Shift + Return) or by clicking on the Run App button in RStudio (which will automatically recognise that it’s a Shiny app):
(Another way of running the app locally is by simply typing runApp(.../data_analyser) to the console, adding the path to the folder of course.)
If you run the app, you should see an empty window popping up. Which is expected, but time to change that!
As the framework suggests, a Shiny app has two parts: the user interface, and the server.
The ui object is responsible for the layout of the app. It will decide what kind of pages or tabs to show, how to format the text that appears, what kind of inputs to require from the users, and where to put the outputs. (We don’t know what the outputs are exactly yet, but we know where each of them will go!)
The server is a function that defines the connection between the input and output data frames. It’s basically a list of observers, blocks of code looking for changes in input values or other observers (just to keep things funny) to determine whether an output showing on the screen should be updated or not.
We are going to concentrate on the layout first, which is defined in the ui object.
First, let’s get the pages and tabs in. When we started typing in the first prototype, we defined ui as a fluidPage. A lot of beginners’ guides I found used fluidPage, specifically a sidebarLayout, so let’s do something different this time!
We want to create separate pages for our app, like for a proper website, and we can use navbarPage for that purpose. This will create a header on top with links to the different pages. Let’s put in two pages:
ui <- navbarPage( title = "Data Analyser", main_page, about_page)
The code will not run just yet, we need to define the two pages. Both need to be a tabPanel object. They can’t be fluidPages. (And if you start to find this confusing and ad-hoc, you are not alone, but we are almost out of new page-building concepts.)
Let’s put in the two pages:
main_page <- tabPanel(title = “Analysis”)about_page <- tabPanel(title = “About”)
If you run the app now, you should see the navigation panel at the top.
You can put some general information on the About page. You have a number of options when formatting text, have a look here for the full list. This page only exists to showcase how different pages would work.
about_page <- tabPanel( title = “About”, titlePanel(“About”), “Created with R Shiny”, br(), “2021 April”)
(Note: You can use different titles on the page itself and on the navigation panel.)
The Analysis page is going to be more exciting. First, we want the inputs to be in a sidebar on the left. Then, we want a separate plot and table area on the right. In Shiny terms: our main page, the tabPanel is going to be a sidebarLayout, with an “Inputs” sidebarPanel on the left, and a mainPanel on the right, which will take the form of a tabsetPanel, with two tabPanels. Huhh.
I feel like there is no reason for me to summarise what these do, have a look at the links if you are curious, but the names should be self-explanatory.
This is the skeleton of the main page:
main_page <- tabPanel( title = "Analysis", titlePanel("Analysis"), sidebarLayout( sidebarPanel( title = "Inputs" ), mainPanel( tabsetPanel( tabPanel( title = "Plot" ), tabPanel( title = "Statistics", ) ) ) ))
And if you run the app now, this is what you should see:
(Note: it’s a good time to check what shiny is doing with these weird building blocks. If you simply type the main_page part of the script in the console, you will see how shiny converts it into HTML.)
Next, we are going to fill up the inputs section with different user input forms. Text or number inputs, sliders, dropdown selections, radio buttons, etc. are collectively called widgets in the Shiny universe. (You can find the comprehensive list here.)
Whenever you add an input widget, the first parameter is going to be its ID, that is how we can refer to that specific input later in the server part. The second parameter is the label — a text field that is placed around the interface, informing the user about its purpose.
Once again, we could list the details of the individual types, but it’s mostly quite straightforward. We will need fileInput, selectInput, and an actionButton, have a read at the official site for more details. We can insert the following code inside the “Inputs” sidebarPanel on main_page:
fileInput("csv_input","Select CSV File to Import",accept=".csv"),selectInput("num_var_1","Numerical Variable 1",choices=c(not_sel)),selectInput("num_var_2","Numerical Variable 2",choices=c(not_sel)),selectInput("fact_var","Factor Variable",choices=c(not_sel)),actionButton("run_button","Run Analysis",icon=icon("play"))
Notes:
Inputs separated by comma will be nicely arranged under each other.
Later, we will refer to these inputs as input$csv_input, input$num_var_1, etc.
In the selectInput field, I thought it would be nice to start with a selection that informs the user that nothing is selected yet. That’s why the not_sel = “Not Selected” global variable was born.
You can add an icon from the Font Awesome and Glyphicons libraries to the page. You don’t have to install anything extra for this functionality.
If you run your app now, this is what you should see:
All we have left to do is decide where the outputs are going to go, and we are done with the UI.
The outputs follow a similar logic to the inputs. At this point, all we determine is:
the position on the screen;
the type (shiny has to know in advance if it’s going to be a text, table, plot, etc);
and the ID.
Just like with the inputs, we can simply add the fields in the corresponding areas of the main_page, and shiny will intelligently fill up the available space.
On the Plot tab, all we want to add is a plotOutput:
plotOutput(“plot_1”)
The Statistic tab is going to be more complicated. We are going to utilise the fluidRow functionalities to place different items next to each other. (Note how so far every comma resulted in the next line being rendered underneath the first one. We want to avoid that with the small tables we are going to create, and put them next to each other.)
This is the Statistic tabPanel after the updates:
tabPanel( title = "Statistics", fluidRow( column(width = 4, strong(textOutput("num_var_1_title"))), column(width = 4, strong(textOutput("num_var_2_title"))), column(width = 4, strong(textOutput("fact_var_title"))) ), fluidRow( column(width = 4, tableOutput("num_var_1_summary_table")), column(width = 4, tableOutput("num_var_2_summary_table")), column(width = 4, tableOutput("fact_var_summary_table")) ), fluidRow( column(strong("Combined Statistics")) ), fluidRow( column(tableOutput("combined_summary_table")) )
In the first line, we are going to have three titles, for the three selectable variables. This needs to be an output because it dynamically changes as we select different columns.
Next, we put in the three 1-dimensional summary tables. We don’t have to worry about what they are yet, we just know there will be tables there under the titles.
And finally, we put in one combined summary table that will explore relationships between the selected variables.
Notes:
The width parameters of the columns show their relative size, following the Bootstrap grid system. (Shiny uses the same framework.)
Putting the text in strong() makes it bold.
All right, the outputs are placed. If you run the app now, you’ll see that... nothing has changed since last time. It’s time to connect the inputs and the outputs!
Before we dive into the steps of building our app, I think it would be beneficial to quickly summarise how reactive programming manifests in Shiny. For a more detailed guide, have a look at this page.
The server function is basically going to be a long list of expressions connecting inputs to outputs. Interestingly, the order of these expressions does not usually matter, although you probably want to keep some logic.
Most outputs shown on the screen will eventually come from a render function. You use renderText for a textOutput, renderPlot for a plotOutput, etc. The type of render function used will depend on the type of output. For example, if you have defined a textOutput in the ui with an ID of “book”, and want to show the text “Dune” there, this is how you do it:
output$book <- renderText(“Dune”)
Observe how you need to render the text “Dune”, even if it would seem to be pretty texty already!
Of course, you would probably want to keep the output dynamic — otherwise, you can just print the title on the page.
The next step is to connect this to an input. Let’s say you have a textInput field with the ID of “title”. If you add the following line:
output$book <- renderText(input$title)
whenever you update the title field, the book output will update too.
That’s the beauty of the whole system, you don’t have to determine what happens if the user updates the title field — you already established the connection, the book output is watching like a hawk for any changes.
As a next step, you can create so-called reactive expressions: these are a sort of intermediary steps between inputs and outputs. For example, if you want to keep the sum of two number inputs, you can keep them in one variable:
sum_of_numbers <- reactive(input$num_1 + input$num_2)
And then use sum_of_numbers as if it were an input. Note that sum_of_numbers is a function, so when you refer to its value in the code, you must put brackets after it (and this is definitely something one tends to forget):
output$sum <- renderText(sum_of_numbers())
This constant vigilance from the outputs part sounds great at first, but you soon realise the drawbacks: there are situations where you definitely DON’T want to update the output field every time the input changes. This can be achieved by an eventReactive function, which is a reactive expression with an extra input: it only runs if a value of a selected input field changes.
This might sound confusing at first but will become much clearer once we have a look at the practical steps.
Just one more formatting note: in the server function, most of the expressions follow this format:
variable_to_create <- some_reactive_function({ code_to_execute})
(This is also true for the whole server function.) The curly brackets are simply there to allow you to put codes in multiple rows. If you can fit the code in one row, you can omit them.
All right, now that we know the theory, let’s start applying it in a very roundabout way!
Recall that we have an input item called input$csv_input. Once populated, this is actually a data.frame, one of its elements being the datapath. (Have a look here for more info.) Once we know the path to the file, we can read it into a data.table, exactly like how we would normally read in a file, with fread.
However, we need one more ingredient. If we simply try to load in whatever is in the input field, the app will start by trying to load in an empty file and crash immediately. In order to prevent that, we need to add a req condition: Shiny’s way of making sure we actually have the input necessary.
So this is going to be our first block in the server function:
data_input <- reactive({ req(input$csv_input) fread(input$csv_input$datapath) })
Now, whenever we upload a .csv file, the app will automatically save its results in thedata.table called data_input. Well, not quite. More precisely, we have a data_input function, that returns a data.table. (This is very easy to mess up!)
(Note: I am not doing any validations on the data type just yet. If you try to import anything that is not a .csv file, the app will just unceremoniously drop dead. Have a look here for more info on how to ensure that it’s a .csv file. )
We have the data in, what do we want to do with it?
As a first step, we want to update the selections in the inputs section — as of now, the only option is “Not Selected”.
We are going to use two new concepts:
The whole thing is going to be wrapped up in an observeEvent. This function lets you execute a piece of code when a specific input field or reactive expression changes. The thing that we are going to look out for now is going to be the data_input reactive expression.
In order to dynamically change the selection, we use updateSelectInput. This function, as the name suggests, takes a selectInput field, and updates something about it, the choices in our case.
We also create a variable, choices, that is going to be a list of
“Not Selected”, which we always want at the top,
and the columns in the data.table.
The relevant code to be entered in the server function:
observeEvent(data_input(),{ choices <- c(not_sel,names(data_input())) updateSelectInput(inputId = “num_var_1”, choices = choices) updateSelectInput(inputId = “num_var_2”, choices = choices) updateSelectInput(inputId = “fact_var”, choices = choices)})
(Note: I initially used a very weird solution here to update the selections. There is an option to add output fields in your ui that will then be rendered as input widgets, with the help of the (very confusingly named) renderUI function. So you determine the position of the ui element in the ui section, but then it’s dynamically created as an output. I found this solution to be confusing, and not very logical, because the nice and clear distinction between layout and content became blurry, but it’s a possibility.)
We should see the impacts of importing a .csv file now, once it’s in, you should be able to select the column names in the dropdown lists:
Now that we can select which columns to use, time to connect them to the output.
Let’s try to imagine what we want to see when we change one of the dropdown selections. The answer is: we don’t actually want to see any changes. It would be quite annoying to see the plot jumping before we finished our selections. We need a barrier between the inputs and the outputs, and that is what the Run Analysis button is for.
We are going to use an eventReactive expression. It’s like a regular reactive expression, but only updates depending on the change of another input.
num_var_1 <- eventReactive(input$run_button,input$num_var_1)num_var_2 <- eventReactive(input$run_button,input$num_var_2)fact_var <- eventReactive(input$run_button,input$fact_var)
With this, we created three expressions, with names identical to the input sources (a naming convention you might find annoying, but I found it to be cleaner this way). The trick is that the num_var_1() expression will only update its value to the latest num_var_1 input when there is a change at the run_button input.
And a change to a button is going to be a click 10 times out of 10.
(Note: These values are going to be character values, but there is no need to use renderText, because we are not actually directly putting them on the screen.)
First, we are going to need to create a plot object. Just like the variables above, this will depend on the button click. Why can’t we just rely on the value updates? We are going to use 4 variables: data_input(), num_var_1(), num_var_2(), and fact_var(). The issue is that data_input() is not protected by a button click, and whenever we select a new file, the value updates.
So this is what we are going to have:
plot_1 <- eventReactive(input$run_button,{ draw_plot_1(data_input(), num_var_1(), num_var_2(), fact_var()) })
Where draw_plot_1 is a regular R function, and it can be defined outside of the server function. For a full version of the draw_plot_1 function, have a look at my GitHub. The more I tried to be clever with building theggplot block by block, the less readable the code got, so I stayed with an unelegant long if-else statement. The function starts like this:
draw_plot_1 <- function(data_input, num_var_1, num_var_2, fact_var){ if(num_var_1 != not_sel & num_var_2 != not_sel & fact_var != not_sel){ ggplot(data = data_input, aes_string(x = num_var_1,y = num_var_2,color = fact_var)) + geom_point() }
So the function takes three inputs, a data.table (observe that it is no longer a function inside the draw_plot_1 function, but really a regular table, so no need to use brackets!), and three column names, any of which can be “Not Selected”, in which case it should be ignored.
In the first branch shown above, all the variables are used. In this case, we want a scatter plot where the two axes are the two numerical variables, and they are split into groups by the factor variable.
Of course, you can change these plots however you see fit for your purposes!
Finally, we have to render the plot inside the server function:
output$plot_1 <- renderPlot(plot_1())
If you run the code now, you should be able to see updates to the plot depending on which variables you selected. If all three variables are selected, you should have a colourful scatter plot:
(Not that you would ever want to plot this many factors by colour!)
And if you only have one numerical variable, it should draw a violin plot:
The way we create the tables is going to use similar logic.
Recall that we put in some titles for the first three tables. We can define their values like so:
output$num_var_1_title <- renderText(paste("Num Var 1:",num_var_1()))output$num_var_2_title <- renderText(paste("Num Var 2:",num_var_2()))output$fact_var_title <- renderText(paste("Factor Var:",fact_var()))
No need to put these inside an eventReactive and make the update conditional on the action button, because the underlying variables are already only updating when the action button is clicked on. Just to reiterate, for example, the num_var_1() expression that we use in the formula above is this one:
num_var_1 <- eventReactive(input$run_button,input$num_var_1)
and not the input$num_var_1 itself.
If you run the app now, you should see the headers (recall that we put in “Combined Statistics” as a fixed text when we created the UI):
We have four tables to create, let’s see how the 1-dimensional numerical table is created, the rest follow a similar structure, check out the code in GitHub.
First, we use another eventReactive expression to run a function whenever the action button is clicked on:
num_var_1_summary_table <- eventReactive(input$run_button,{ create_num_var_table(data_input(), num_var_1()) })
Next, we define the create_num_var_table function:
create_num_var_table <- function(data_input, num_var){ if(num_var != not_sel){ col <- data_input[,get(num_var)] if(length(col)>5000) col_norm<-sample(col,5000) else col_norm<-col norm_test <- shapiro.test(col_norm) statistic <- c("mean", "median", "5th percentile", "95th percentile", "Shapiro statistic", "Shapiro p-value") value <- c(round(mean(col),2), round(median(col),2), round(quantile(col, 0.05),2), round(quantile(col, 0.95),2), norm_test$statistic, norm_test$p.value) data.table(statistic, value) }}
The result is going to be a data.table with two columns called statistic and value. I just put on a few statistics I could think of, along with a normality test, add whatever you feel like.
(Note: the built-in normality test has a 5,000 sample size limit, so I took a random sample if the imported .csv file turns out to be longer.)
Finally, we put the table on the screen by rendering it:
output$num_var_1_summary_table <- renderTable(num_var_1_summary_table(),colnames = FALSE)
I did not want to show the headers of the tables, this can be set in the colnames parameter.
You need to follow a similar structure for the other tables. In the combined table, just like we did with the plot, there are different branches, based on what kind of variables we have selected. If we have all three variables selected, the table will calculate the correlation between the two numerical variables in the different subgroups by the factor variable.
Needless to say, this is just one approach, you can literally put anything you want in these tables once the structure is done.
If you run the app, this is what you should see:
Aaand, we’re done, right? Almost!
As the everlasting advice says, never leave anything on default!
So we are going to change the default theme. There are several ways to do that, including using your own CSS template, we are going to take a very simple approach, and use shinythemes. You will need to install the package first. Then, all you need to do is pick a theme, and put it in the ui object like so:
theme = shinytheme('united')
And voila, we can see the same screen, but it’s orange now (or whatever you picked):
Now we’re done!
This guide turned out to be much longer than I anticipated, there are a few nuances that I did not feel I should mention, but for completeness’ sake, here they are:
As a default, the max file size you can upload is 5 MB. You can increase that by entering this code in the server function:options(shiny.maxRequestSize=10*1024^2)(this will be 10 MB)
If you want to use number fields as factors, R will generate the plot but add a continuous colour scale. In the draw_plot function, I started with this code to convert the column to a factor: if(fact_var!=not_sel){ data_input[,(fact_var):= as.factor(data_input[,get(fact_var)])] }
You might have noticed that we are using eventReactive a lot for the same button click. It might have been nicer to collect everything in a data.frame rather than keeping them in separate events. And the plot and table drawing functions also use an eventReactive, even though most of the variables are already “eventReactivated” inside. The reason why I did that was because data_input() updates every time a new .csv file is imported. It might be clearer to add another data_input_2() variable instead, which updates based on data_input() when you click on the button and then use that function in regular reactive expressions along with num_var_1() etc. This is just one example of how this reactive programming can be very dynamic but confusing at the same time.
When it comes to actually run the app, you have three options.
You can run it locally, for example by clicking on the Run App button in RStudio. You can also run it without opening the script itself with the runApp function.The second option is Shiny Server, with which you can host it on your own server. I have no experience with this option.Or you can use shinyapps.io, which is the cloud service.
You can run it locally, for example by clicking on the Run App button in RStudio. You can also run it without opening the script itself with the runApp function.
The second option is Shiny Server, with which you can host it on your own server. I have no experience with this option.
Or you can use shinyapps.io, which is the cloud service.
I used shinyapps.io to host the app, you can check it out here.
Using shinyapps.io is really straightforward, you sign up, create an account, get a token with which you can publish your app. With a free account, you get 5 apps and 25 active user hours per month.
matepocs.medium.com
Once again, I recommend Mastering Shiny by Hadley Wickham if you want to learn Shiny in a nice and structured way:
mastering-shiny.org
You can find some handy Shiny cheatsheets here:
www.rstudio.com
And this is a GitHub repo with a list of R packages that enhance Shiny’s default functionality:
|
[
{
"code": null,
"e": 450,
"s": 172,
"text": "Shiny is an R package that lets you build interactive web apps. All you need is R, no HTML, CSS, or JavaScript — although you certainly have the option to enhance your app with them. You can run the app on your computer, host on your own server, or use RStudio’s cloud service."
},
{
"code": null,
"e": 771,
"s": 450,
"text": "In this post, I am going to walk through the process of building a simple data analysis app from scratch. You can find a lot of excellent guides for the basics out there, my aim was to take it a few tiny steps further: we are going to do some dynamic UI updates, dynamic outputs, an action button, panel navigation, etc."
},
{
"code": null,
"e": 1012,
"s": 771,
"text": "Please note that it’s not a “serious” data analysis app, my purpose was to showcase different functionalities of shiny that might come in handy. However, once we are finished, it should be pretty easy to add new functionalities to our code."
},
{
"code": null,
"e": 1128,
"s": 1012,
"text": "You can have a look at the app we are going to build on shinyapps.io: https://matepocs.shinyapps.io/data_analyser/."
},
{
"code": null,
"e": 1165,
"s": 1128,
"text": "The underlying code is on my GitHub."
},
{
"code": null,
"e": 1392,
"s": 1165,
"text": "Shiny is a very well documented package, with excellent guides on its website. In fact, it’s a bit too well documented, and it’s easy to get lost in the maze of getting started videos, tutorials, written guides, articles, etc."
},
{
"code": null,
"e": 1504,
"s": 1392,
"text": "I personally found Mastering Shiny by Hadley Wickham to be a very good and compact source, highly recommend it."
},
{
"code": null,
"e": 1583,
"s": 1504,
"text": "This is the high-level design sketch of what we want our app to be able to do."
},
{
"code": null,
"e": 1593,
"s": 1583,
"text": "The user:"
},
{
"code": null,
"e": 1614,
"s": 1593,
"text": "imports a .csv file;"
},
{
"code": null,
"e": 1686,
"s": 1614,
"text": "selects up to 2 numerical and 1 factor type variables from the columns."
},
{
"code": null,
"e": 1700,
"s": 1686,
"text": "Then the app:"
},
{
"code": null,
"e": 1714,
"s": 1700,
"text": "draws a plot;"
},
{
"code": null,
"e": 1738,
"s": 1714,
"text": "creates summary tables."
},
{
"code": null,
"e": 1978,
"s": 1738,
"text": "The funny part is that we want the outputs to be different based on what type of columns we selected — we want a different plot if it’s just a factor variable selected, and a more complicated one if we have numerical variables by a factor."
},
{
"code": null,
"e": 2070,
"s": 1978,
"text": "We are going to work in RStudio and R. To use shiny, you first need to install the package:"
},
{
"code": null,
"e": 2096,
"s": 2070,
"text": "install.packages(“shiny”)"
},
{
"code": null,
"e": 2256,
"s": 2096,
"text": "(The other packages we are also going to use: data.table, ggplot2, you might need to install them too. I assume familiarity with these packages going forward.)"
},
{
"code": null,
"e": 2385,
"s": 2256,
"text": "Next, we need to create a folder with the name of the app. I called mine data_analyser. We will keep working inside this folder."
},
{
"code": null,
"e": 2534,
"s": 2385,
"text": "The framework of a shiny app is pretty simple: one R script that has to be called app.R. So we are going to put one inside our data_analyser folder."
},
{
"code": null,
"e": 3127,
"s": 2534,
"text": "(Note: you might find the framework confusing if you read some older guides. Instead of an app.R that contains the UI and the server functionalities, you used to need precisely two scripts: a server.R, and a ui.R. That old approach still works for legacy reasons, but I think it’s not recommended. Additionally, you can have different scripts in the folder, and source them in your app script. So you don’t have to put everything in one script like we are going to do now, you can store your server function in a separate server.R script and source it, just know that it’s not a requirement.)"
},
{
"code": null,
"e": 3186,
"s": 3127,
"text": "The minimum Shiny app framework looks something like this:"
},
{
"code": null,
"e": 3287,
"s": 3186,
"text": "library(shiny)ui <- fluidPage()server <- function(input, output){}shinyApp(ui = ui, server = server)"
},
{
"code": null,
"e": 3521,
"s": 3287,
"text": "You can copy this to your app.R, and should be able to run it by either using a keyboard shortcut (like Cmd + Shift + Return) or by clicking on the Run App button in RStudio (which will automatically recognise that it’s a Shiny app):"
},
{
"code": null,
"e": 3665,
"s": 3521,
"text": "(Another way of running the app locally is by simply typing runApp(.../data_analyser) to the console, adding the path to the folder of course.)"
},
{
"code": null,
"e": 3772,
"s": 3665,
"text": "If you run the app, you should see an empty window popping up. Which is expected, but time to change that!"
},
{
"code": null,
"e": 3862,
"s": 3772,
"text": "As the framework suggests, a Shiny app has two parts: the user interface, and the server."
},
{
"code": null,
"e": 4173,
"s": 3862,
"text": "The ui object is responsible for the layout of the app. It will decide what kind of pages or tabs to show, how to format the text that appears, what kind of inputs to require from the users, and where to put the outputs. (We don’t know what the outputs are exactly yet, but we know where each of them will go!)"
},
{
"code": null,
"e": 4481,
"s": 4173,
"text": "The server is a function that defines the connection between the input and output data frames. It’s basically a list of observers, blocks of code looking for changes in input values or other observers (just to keep things funny) to determine whether an output showing on the screen should be updated or not."
},
{
"code": null,
"e": 4565,
"s": 4481,
"text": "We are going to concentrate on the layout first, which is defined in the ui object."
},
{
"code": null,
"e": 4806,
"s": 4565,
"text": "First, let’s get the pages and tabs in. When we started typing in the first prototype, we defined ui as a fluidPage. A lot of beginners’ guides I found used fluidPage, specifically a sidebarLayout, so let’s do something different this time!"
},
{
"code": null,
"e": 5015,
"s": 4806,
"text": "We want to create separate pages for our app, like for a proper website, and we can use navbarPage for that purpose. This will create a header on top with links to the different pages. Let’s put in two pages:"
},
{
"code": null,
"e": 5086,
"s": 5015,
"text": "ui <- navbarPage( title = \"Data Analyser\", main_page, about_page)"
},
{
"code": null,
"e": 5338,
"s": 5086,
"text": "The code will not run just yet, we need to define the two pages. Both need to be a tabPanel object. They can’t be fluidPages. (And if you start to find this confusing and ad-hoc, you are not alone, but we are almost out of new page-building concepts.)"
},
{
"code": null,
"e": 5366,
"s": 5338,
"text": "Let’s put in the two pages:"
},
{
"code": null,
"e": 5447,
"s": 5366,
"text": "main_page <- tabPanel(title = “Analysis”)about_page <- tabPanel(title = “About”)"
},
{
"code": null,
"e": 5519,
"s": 5447,
"text": "If you run the app now, you should see the navigation panel at the top."
},
{
"code": null,
"e": 5728,
"s": 5519,
"text": "You can put some general information on the About page. You have a number of options when formatting text, have a look here for the full list. This page only exists to showcase how different pages would work."
},
{
"code": null,
"e": 5834,
"s": 5728,
"text": "about_page <- tabPanel( title = “About”, titlePanel(“About”), “Created with R Shiny”, br(), “2021 April”)"
},
{
"code": null,
"e": 5919,
"s": 5834,
"text": "(Note: You can use different titles on the page itself and on the navigation panel.)"
},
{
"code": null,
"e": 6302,
"s": 5919,
"text": "The Analysis page is going to be more exciting. First, we want the inputs to be in a sidebar on the left. Then, we want a separate plot and table area on the right. In Shiny terms: our main page, the tabPanel is going to be a sidebarLayout, with an “Inputs” sidebarPanel on the left, and a mainPanel on the right, which will take the form of a tabsetPanel, with two tabPanels. Huhh."
},
{
"code": null,
"e": 6455,
"s": 6302,
"text": "I feel like there is no reason for me to summarise what these do, have a look at the links if you are curious, but the names should be self-explanatory."
},
{
"code": null,
"e": 6494,
"s": 6455,
"text": "This is the skeleton of the main page:"
},
{
"code": null,
"e": 6780,
"s": 6494,
"text": "main_page <- tabPanel( title = \"Analysis\", titlePanel(\"Analysis\"), sidebarLayout( sidebarPanel( title = \"Inputs\" ), mainPanel( tabsetPanel( tabPanel( title = \"Plot\" ), tabPanel( title = \"Statistics\", ) ) ) ))"
},
{
"code": null,
"e": 6837,
"s": 6780,
"text": "And if you run the app now, this is what you should see:"
},
{
"code": null,
"e": 7039,
"s": 6837,
"text": "(Note: it’s a good time to check what shiny is doing with these weird building blocks. If you simply type the main_page part of the script in the console, you will see how shiny converts it into HTML.)"
},
{
"code": null,
"e": 7293,
"s": 7039,
"text": "Next, we are going to fill up the inputs section with different user input forms. Text or number inputs, sliders, dropdown selections, radio buttons, etc. are collectively called widgets in the Shiny universe. (You can find the comprehensive list here.)"
},
{
"code": null,
"e": 7568,
"s": 7293,
"text": "Whenever you add an input widget, the first parameter is going to be its ID, that is how we can refer to that specific input later in the server part. The second parameter is the label — a text field that is placed around the interface, informing the user about its purpose."
},
{
"code": null,
"e": 7859,
"s": 7568,
"text": "Once again, we could list the details of the individual types, but it’s mostly quite straightforward. We will need fileInput, selectInput, and an actionButton, have a read at the official site for more details. We can insert the following code inside the “Inputs” sidebarPanel on main_page:"
},
{
"code": null,
"e": 8179,
"s": 7859,
"text": "fileInput(\"csv_input\",\"Select CSV File to Import\",accept=\".csv\"),selectInput(\"num_var_1\",\"Numerical Variable 1\",choices=c(not_sel)),selectInput(\"num_var_2\",\"Numerical Variable 2\",choices=c(not_sel)),selectInput(\"fact_var\",\"Factor Variable\",choices=c(not_sel)),actionButton(\"run_button\",\"Run Analysis\",icon=icon(\"play\"))"
},
{
"code": null,
"e": 8186,
"s": 8179,
"text": "Notes:"
},
{
"code": null,
"e": 8254,
"s": 8186,
"text": "Inputs separated by comma will be nicely arranged under each other."
},
{
"code": null,
"e": 8333,
"s": 8254,
"text": "Later, we will refer to these inputs as input$csv_input, input$num_var_1, etc."
},
{
"code": null,
"e": 8530,
"s": 8333,
"text": "In the selectInput field, I thought it would be nice to start with a selection that informs the user that nothing is selected yet. That’s why the not_sel = “Not Selected” global variable was born."
},
{
"code": null,
"e": 8675,
"s": 8530,
"text": "You can add an icon from the Font Awesome and Glyphicons libraries to the page. You don’t have to install anything extra for this functionality."
},
{
"code": null,
"e": 8729,
"s": 8675,
"text": "If you run your app now, this is what you should see:"
},
{
"code": null,
"e": 8826,
"s": 8729,
"text": "All we have left to do is decide where the outputs are going to go, and we are done with the UI."
},
{
"code": null,
"e": 8912,
"s": 8826,
"text": "The outputs follow a similar logic to the inputs. At this point, all we determine is:"
},
{
"code": null,
"e": 8940,
"s": 8912,
"text": "the position on the screen;"
},
{
"code": null,
"e": 9026,
"s": 8940,
"text": "the type (shiny has to know in advance if it’s going to be a text, table, plot, etc);"
},
{
"code": null,
"e": 9038,
"s": 9026,
"text": "and the ID."
},
{
"code": null,
"e": 9197,
"s": 9038,
"text": "Just like with the inputs, we can simply add the fields in the corresponding areas of the main_page, and shiny will intelligently fill up the available space."
},
{
"code": null,
"e": 9250,
"s": 9197,
"text": "On the Plot tab, all we want to add is a plotOutput:"
},
{
"code": null,
"e": 9271,
"s": 9250,
"text": "plotOutput(“plot_1”)"
},
{
"code": null,
"e": 9618,
"s": 9271,
"text": "The Statistic tab is going to be more complicated. We are going to utilise the fluidRow functionalities to place different items next to each other. (Note how so far every comma resulted in the next line being rendered underneath the first one. We want to avoid that with the small tables we are going to create, and put them next to each other.)"
},
{
"code": null,
"e": 9668,
"s": 9618,
"text": "This is the Statistic tabPanel after the updates:"
},
{
"code": null,
"e": 10215,
"s": 9668,
"text": "tabPanel( title = \"Statistics\", fluidRow( column(width = 4, strong(textOutput(\"num_var_1_title\"))), column(width = 4, strong(textOutput(\"num_var_2_title\"))), column(width = 4, strong(textOutput(\"fact_var_title\"))) ), fluidRow( column(width = 4, tableOutput(\"num_var_1_summary_table\")), column(width = 4, tableOutput(\"num_var_2_summary_table\")), column(width = 4, tableOutput(\"fact_var_summary_table\")) ), fluidRow( column(strong(\"Combined Statistics\")) ), fluidRow( column(tableOutput(\"combined_summary_table\")) )"
},
{
"code": null,
"e": 10395,
"s": 10215,
"text": "In the first line, we are going to have three titles, for the three selectable variables. This needs to be an output because it dynamically changes as we select different columns."
},
{
"code": null,
"e": 10557,
"s": 10395,
"text": "Next, we put in the three 1-dimensional summary tables. We don’t have to worry about what they are yet, we just know there will be tables there under the titles."
},
{
"code": null,
"e": 10671,
"s": 10557,
"text": "And finally, we put in one combined summary table that will explore relationships between the selected variables."
},
{
"code": null,
"e": 10678,
"s": 10671,
"text": "Notes:"
},
{
"code": null,
"e": 10810,
"s": 10678,
"text": "The width parameters of the columns show their relative size, following the Bootstrap grid system. (Shiny uses the same framework.)"
},
{
"code": null,
"e": 10854,
"s": 10810,
"text": "Putting the text in strong() makes it bold."
},
{
"code": null,
"e": 11018,
"s": 10854,
"text": "All right, the outputs are placed. If you run the app now, you’ll see that... nothing has changed since last time. It’s time to connect the inputs and the outputs!"
},
{
"code": null,
"e": 11219,
"s": 11018,
"text": "Before we dive into the steps of building our app, I think it would be beneficial to quickly summarise how reactive programming manifests in Shiny. For a more detailed guide, have a look at this page."
},
{
"code": null,
"e": 11439,
"s": 11219,
"text": "The server function is basically going to be a long list of expressions connecting inputs to outputs. Interestingly, the order of these expressions does not usually matter, although you probably want to keep some logic."
},
{
"code": null,
"e": 11797,
"s": 11439,
"text": "Most outputs shown on the screen will eventually come from a render function. You use renderText for a textOutput, renderPlot for a plotOutput, etc. The type of render function used will depend on the type of output. For example, if you have defined a textOutput in the ui with an ID of “book”, and want to show the text “Dune” there, this is how you do it:"
},
{
"code": null,
"e": 11831,
"s": 11797,
"text": "output$book <- renderText(“Dune”)"
},
{
"code": null,
"e": 11929,
"s": 11831,
"text": "Observe how you need to render the text “Dune”, even if it would seem to be pretty texty already!"
},
{
"code": null,
"e": 12046,
"s": 11929,
"text": "Of course, you would probably want to keep the output dynamic — otherwise, you can just print the title on the page."
},
{
"code": null,
"e": 12184,
"s": 12046,
"text": "The next step is to connect this to an input. Let’s say you have a textInput field with the ID of “title”. If you add the following line:"
},
{
"code": null,
"e": 12223,
"s": 12184,
"text": "output$book <- renderText(input$title)"
},
{
"code": null,
"e": 12293,
"s": 12223,
"text": "whenever you update the title field, the book output will update too."
},
{
"code": null,
"e": 12508,
"s": 12293,
"text": "That’s the beauty of the whole system, you don’t have to determine what happens if the user updates the title field — you already established the connection, the book output is watching like a hawk for any changes."
},
{
"code": null,
"e": 12736,
"s": 12508,
"text": "As a next step, you can create so-called reactive expressions: these are a sort of intermediary steps between inputs and outputs. For example, if you want to keep the sum of two number inputs, you can keep them in one variable:"
},
{
"code": null,
"e": 12790,
"s": 12736,
"text": "sum_of_numbers <- reactive(input$num_1 + input$num_2)"
},
{
"code": null,
"e": 13013,
"s": 12790,
"text": "And then use sum_of_numbers as if it were an input. Note that sum_of_numbers is a function, so when you refer to its value in the code, you must put brackets after it (and this is definitely something one tends to forget):"
},
{
"code": null,
"e": 13056,
"s": 13013,
"text": "output$sum <- renderText(sum_of_numbers())"
},
{
"code": null,
"e": 13433,
"s": 13056,
"text": "This constant vigilance from the outputs part sounds great at first, but you soon realise the drawbacks: there are situations where you definitely DON’T want to update the output field every time the input changes. This can be achieved by an eventReactive function, which is a reactive expression with an extra input: it only runs if a value of a selected input field changes."
},
{
"code": null,
"e": 13542,
"s": 13433,
"text": "This might sound confusing at first but will become much clearer once we have a look at the practical steps."
},
{
"code": null,
"e": 13641,
"s": 13542,
"text": "Just one more formatting note: in the server function, most of the expressions follow this format:"
},
{
"code": null,
"e": 13710,
"s": 13641,
"text": "variable_to_create <- some_reactive_function({ code_to_execute})"
},
{
"code": null,
"e": 13896,
"s": 13710,
"text": "(This is also true for the whole server function.) The curly brackets are simply there to allow you to put codes in multiple rows. If you can fit the code in one row, you can omit them."
},
{
"code": null,
"e": 13986,
"s": 13896,
"text": "All right, now that we know the theory, let’s start applying it in a very roundabout way!"
},
{
"code": null,
"e": 14297,
"s": 13986,
"text": "Recall that we have an input item called input$csv_input. Once populated, this is actually a data.frame, one of its elements being the datapath. (Have a look here for more info.) Once we know the path to the file, we can read it into a data.table, exactly like how we would normally read in a file, with fread."
},
{
"code": null,
"e": 14595,
"s": 14297,
"text": "However, we need one more ingredient. If we simply try to load in whatever is in the input field, the app will start by trying to load in an empty file and crash immediately. In order to prevent that, we need to add a req condition: Shiny’s way of making sure we actually have the input necessary."
},
{
"code": null,
"e": 14658,
"s": 14595,
"text": "So this is going to be our first block in the server function:"
},
{
"code": null,
"e": 14746,
"s": 14658,
"text": "data_input <- reactive({ req(input$csv_input) fread(input$csv_input$datapath) })"
},
{
"code": null,
"e": 14986,
"s": 14746,
"text": "Now, whenever we upload a .csv file, the app will automatically save its results in thedata.table called data_input. Well, not quite. More precisely, we have a data_input function, that returns a data.table. (This is very easy to mess up!)"
},
{
"code": null,
"e": 15224,
"s": 14986,
"text": "(Note: I am not doing any validations on the data type just yet. If you try to import anything that is not a .csv file, the app will just unceremoniously drop dead. Have a look here for more info on how to ensure that it’s a .csv file. )"
},
{
"code": null,
"e": 15276,
"s": 15224,
"text": "We have the data in, what do we want to do with it?"
},
{
"code": null,
"e": 15396,
"s": 15276,
"text": "As a first step, we want to update the selections in the inputs section — as of now, the only option is “Not Selected”."
},
{
"code": null,
"e": 15434,
"s": 15396,
"text": "We are going to use two new concepts:"
},
{
"code": null,
"e": 15702,
"s": 15434,
"text": "The whole thing is going to be wrapped up in an observeEvent. This function lets you execute a piece of code when a specific input field or reactive expression changes. The thing that we are going to look out for now is going to be the data_input reactive expression."
},
{
"code": null,
"e": 15895,
"s": 15702,
"text": "In order to dynamically change the selection, we use updateSelectInput. This function, as the name suggests, takes a selectInput field, and updates something about it, the choices in our case."
},
{
"code": null,
"e": 15961,
"s": 15895,
"text": "We also create a variable, choices, that is going to be a list of"
},
{
"code": null,
"e": 16010,
"s": 15961,
"text": "“Not Selected”, which we always want at the top,"
},
{
"code": null,
"e": 16045,
"s": 16010,
"text": "and the columns in the data.table."
},
{
"code": null,
"e": 16101,
"s": 16045,
"text": "The relevant code to be entered in the server function:"
},
{
"code": null,
"e": 16356,
"s": 16101,
"text": "observeEvent(data_input(),{ choices <- c(not_sel,names(data_input())) updateSelectInput(inputId = “num_var_1”, choices = choices) updateSelectInput(inputId = “num_var_2”, choices = choices) updateSelectInput(inputId = “fact_var”, choices = choices)})"
},
{
"code": null,
"e": 16876,
"s": 16356,
"text": "(Note: I initially used a very weird solution here to update the selections. There is an option to add output fields in your ui that will then be rendered as input widgets, with the help of the (very confusingly named) renderUI function. So you determine the position of the ui element in the ui section, but then it’s dynamically created as an output. I found this solution to be confusing, and not very logical, because the nice and clear distinction between layout and content became blurry, but it’s a possibility.)"
},
{
"code": null,
"e": 17015,
"s": 16876,
"text": "We should see the impacts of importing a .csv file now, once it’s in, you should be able to select the column names in the dropdown lists:"
},
{
"code": null,
"e": 17096,
"s": 17015,
"text": "Now that we can select which columns to use, time to connect them to the output."
},
{
"code": null,
"e": 17431,
"s": 17096,
"text": "Let’s try to imagine what we want to see when we change one of the dropdown selections. The answer is: we don’t actually want to see any changes. It would be quite annoying to see the plot jumping before we finished our selections. We need a barrier between the inputs and the outputs, and that is what the Run Analysis button is for."
},
{
"code": null,
"e": 17580,
"s": 17431,
"text": "We are going to use an eventReactive expression. It’s like a regular reactive expression, but only updates depending on the change of another input."
},
{
"code": null,
"e": 17759,
"s": 17580,
"text": "num_var_1 <- eventReactive(input$run_button,input$num_var_1)num_var_2 <- eventReactive(input$run_button,input$num_var_2)fact_var <- eventReactive(input$run_button,input$fact_var)"
},
{
"code": null,
"e": 18078,
"s": 17759,
"text": "With this, we created three expressions, with names identical to the input sources (a naming convention you might find annoying, but I found it to be cleaner this way). The trick is that the num_var_1() expression will only update its value to the latest num_var_1 input when there is a change at the run_button input."
},
{
"code": null,
"e": 18146,
"s": 18078,
"text": "And a change to a button is going to be a click 10 times out of 10."
},
{
"code": null,
"e": 18306,
"s": 18146,
"text": "(Note: These values are going to be character values, but there is no need to use renderText, because we are not actually directly putting them on the screen.)"
},
{
"code": null,
"e": 18683,
"s": 18306,
"text": "First, we are going to need to create a plot object. Just like the variables above, this will depend on the button click. Why can’t we just rely on the value updates? We are going to use 4 variables: data_input(), num_var_1(), num_var_2(), and fact_var(). The issue is that data_input() is not protected by a button click, and whenever we select a new file, the value updates."
},
{
"code": null,
"e": 18721,
"s": 18683,
"text": "So this is what we are going to have:"
},
{
"code": null,
"e": 18835,
"s": 18721,
"text": "plot_1 <- eventReactive(input$run_button,{ draw_plot_1(data_input(), num_var_1(), num_var_2(), fact_var()) })"
},
{
"code": null,
"e": 19193,
"s": 18835,
"text": "Where draw_plot_1 is a regular R function, and it can be defined outside of the server function. For a full version of the draw_plot_1 function, have a look at my GitHub. The more I tried to be clever with building theggplot block by block, the less readable the code got, so I stayed with an unelegant long if-else statement. The function starts like this:"
},
{
"code": null,
"e": 19467,
"s": 19193,
"text": "draw_plot_1 <- function(data_input, num_var_1, num_var_2, fact_var){ if(num_var_1 != not_sel & num_var_2 != not_sel & fact_var != not_sel){ ggplot(data = data_input, aes_string(x = num_var_1,y = num_var_2,color = fact_var)) + geom_point() }"
},
{
"code": null,
"e": 19744,
"s": 19467,
"text": "So the function takes three inputs, a data.table (observe that it is no longer a function inside the draw_plot_1 function, but really a regular table, so no need to use brackets!), and three column names, any of which can be “Not Selected”, in which case it should be ignored."
},
{
"code": null,
"e": 19949,
"s": 19744,
"text": "In the first branch shown above, all the variables are used. In this case, we want a scatter plot where the two axes are the two numerical variables, and they are split into groups by the factor variable."
},
{
"code": null,
"e": 20026,
"s": 19949,
"text": "Of course, you can change these plots however you see fit for your purposes!"
},
{
"code": null,
"e": 20090,
"s": 20026,
"text": "Finally, we have to render the plot inside the server function:"
},
{
"code": null,
"e": 20128,
"s": 20090,
"text": "output$plot_1 <- renderPlot(plot_1())"
},
{
"code": null,
"e": 20321,
"s": 20128,
"text": "If you run the code now, you should be able to see updates to the plot depending on which variables you selected. If all three variables are selected, you should have a colourful scatter plot:"
},
{
"code": null,
"e": 20389,
"s": 20321,
"text": "(Not that you would ever want to plot this many factors by colour!)"
},
{
"code": null,
"e": 20464,
"s": 20389,
"text": "And if you only have one numerical variable, it should draw a violin plot:"
},
{
"code": null,
"e": 20524,
"s": 20464,
"text": "The way we create the tables is going to use similar logic."
},
{
"code": null,
"e": 20622,
"s": 20524,
"text": "Recall that we put in some titles for the first three tables. We can define their values like so:"
},
{
"code": null,
"e": 20835,
"s": 20622,
"text": "output$num_var_1_title <- renderText(paste(\"Num Var 1:\",num_var_1()))output$num_var_2_title <- renderText(paste(\"Num Var 2:\",num_var_2()))output$fact_var_title <- renderText(paste(\"Factor Var:\",fact_var()))"
},
{
"code": null,
"e": 21136,
"s": 20835,
"text": "No need to put these inside an eventReactive and make the update conditional on the action button, because the underlying variables are already only updating when the action button is clicked on. Just to reiterate, for example, the num_var_1() expression that we use in the formula above is this one:"
},
{
"code": null,
"e": 21197,
"s": 21136,
"text": "num_var_1 <- eventReactive(input$run_button,input$num_var_1)"
},
{
"code": null,
"e": 21233,
"s": 21197,
"text": "and not the input$num_var_1 itself."
},
{
"code": null,
"e": 21370,
"s": 21233,
"text": "If you run the app now, you should see the headers (recall that we put in “Combined Statistics” as a fixed text when we created the UI):"
},
{
"code": null,
"e": 21528,
"s": 21370,
"text": "We have four tables to create, let’s see how the 1-dimensional numerical table is created, the rest follow a similar structure, check out the code in GitHub."
},
{
"code": null,
"e": 21635,
"s": 21528,
"text": "First, we use another eventReactive expression to run a function whenever the action button is clicked on:"
},
{
"code": null,
"e": 21750,
"s": 21635,
"text": "num_var_1_summary_table <- eventReactive(input$run_button,{ create_num_var_table(data_input(), num_var_1()) })"
},
{
"code": null,
"e": 21801,
"s": 21750,
"text": "Next, we define the create_num_var_table function:"
},
{
"code": null,
"e": 22389,
"s": 21801,
"text": "create_num_var_table <- function(data_input, num_var){ if(num_var != not_sel){ col <- data_input[,get(num_var)] if(length(col)>5000) col_norm<-sample(col,5000) else col_norm<-col norm_test <- shapiro.test(col_norm) statistic <- c(\"mean\", \"median\", \"5th percentile\", \"95th percentile\", \"Shapiro statistic\", \"Shapiro p-value\") value <- c(round(mean(col),2), round(median(col),2), round(quantile(col, 0.05),2), round(quantile(col, 0.95),2), norm_test$statistic, norm_test$p.value) data.table(statistic, value) }}"
},
{
"code": null,
"e": 22579,
"s": 22389,
"text": "The result is going to be a data.table with two columns called statistic and value. I just put on a few statistics I could think of, along with a normality test, add whatever you feel like."
},
{
"code": null,
"e": 22722,
"s": 22579,
"text": "(Note: the built-in normality test has a 5,000 sample size limit, so I took a random sample if the imported .csv file turns out to be longer.)"
},
{
"code": null,
"e": 22779,
"s": 22722,
"text": "Finally, we put the table on the screen by rendering it:"
},
{
"code": null,
"e": 22869,
"s": 22779,
"text": "output$num_var_1_summary_table <- renderTable(num_var_1_summary_table(),colnames = FALSE)"
},
{
"code": null,
"e": 22962,
"s": 22869,
"text": "I did not want to show the headers of the tables, this can be set in the colnames parameter."
},
{
"code": null,
"e": 23327,
"s": 22962,
"text": "You need to follow a similar structure for the other tables. In the combined table, just like we did with the plot, there are different branches, based on what kind of variables we have selected. If we have all three variables selected, the table will calculate the correlation between the two numerical variables in the different subgroups by the factor variable."
},
{
"code": null,
"e": 23455,
"s": 23327,
"text": "Needless to say, this is just one approach, you can literally put anything you want in these tables once the structure is done."
},
{
"code": null,
"e": 23504,
"s": 23455,
"text": "If you run the app, this is what you should see:"
},
{
"code": null,
"e": 23538,
"s": 23504,
"text": "Aaand, we’re done, right? Almost!"
},
{
"code": null,
"e": 23603,
"s": 23538,
"text": "As the everlasting advice says, never leave anything on default!"
},
{
"code": null,
"e": 23911,
"s": 23603,
"text": "So we are going to change the default theme. There are several ways to do that, including using your own CSS template, we are going to take a very simple approach, and use shinythemes. You will need to install the package first. Then, all you need to do is pick a theme, and put it in the ui object like so:"
},
{
"code": null,
"e": 23940,
"s": 23911,
"text": "theme = shinytheme('united')"
},
{
"code": null,
"e": 24025,
"s": 23940,
"text": "And voila, we can see the same screen, but it’s orange now (or whatever you picked):"
},
{
"code": null,
"e": 24041,
"s": 24025,
"text": "Now we’re done!"
},
{
"code": null,
"e": 24206,
"s": 24041,
"text": "This guide turned out to be much longer than I anticipated, there are a few nuances that I did not feel I should mention, but for completeness’ sake, here they are:"
},
{
"code": null,
"e": 24389,
"s": 24206,
"text": "As a default, the max file size you can upload is 5 MB. You can increase that by entering this code in the server function:options(shiny.maxRequestSize=10*1024^2)(this will be 10 MB)"
},
{
"code": null,
"e": 24671,
"s": 24389,
"text": "If you want to use number fields as factors, R will generate the plot but add a continuous colour scale. In the draw_plot function, I started with this code to convert the column to a factor: if(fact_var!=not_sel){ data_input[,(fact_var):= as.factor(data_input[,get(fact_var)])] }"
},
{
"code": null,
"e": 25437,
"s": 24671,
"text": "You might have noticed that we are using eventReactive a lot for the same button click. It might have been nicer to collect everything in a data.frame rather than keeping them in separate events. And the plot and table drawing functions also use an eventReactive, even though most of the variables are already “eventReactivated” inside. The reason why I did that was because data_input() updates every time a new .csv file is imported. It might be clearer to add another data_input_2() variable instead, which updates based on data_input() when you click on the button and then use that function in regular reactive expressions along with num_var_1() etc. This is just one example of how this reactive programming can be very dynamic but confusing at the same time."
},
{
"code": null,
"e": 25500,
"s": 25437,
"text": "When it comes to actually run the app, you have three options."
},
{
"code": null,
"e": 25838,
"s": 25500,
"text": "You can run it locally, for example by clicking on the Run App button in RStudio. You can also run it without opening the script itself with the runApp function.The second option is Shiny Server, with which you can host it on your own server. I have no experience with this option.Or you can use shinyapps.io, which is the cloud service."
},
{
"code": null,
"e": 26000,
"s": 25838,
"text": "You can run it locally, for example by clicking on the Run App button in RStudio. You can also run it without opening the script itself with the runApp function."
},
{
"code": null,
"e": 26121,
"s": 26000,
"text": "The second option is Shiny Server, with which you can host it on your own server. I have no experience with this option."
},
{
"code": null,
"e": 26178,
"s": 26121,
"text": "Or you can use shinyapps.io, which is the cloud service."
},
{
"code": null,
"e": 26242,
"s": 26178,
"text": "I used shinyapps.io to host the app, you can check it out here."
},
{
"code": null,
"e": 26441,
"s": 26242,
"text": "Using shinyapps.io is really straightforward, you sign up, create an account, get a token with which you can publish your app. With a free account, you get 5 apps and 25 active user hours per month."
},
{
"code": null,
"e": 26461,
"s": 26441,
"text": "matepocs.medium.com"
},
{
"code": null,
"e": 26576,
"s": 26461,
"text": "Once again, I recommend Mastering Shiny by Hadley Wickham if you want to learn Shiny in a nice and structured way:"
},
{
"code": null,
"e": 26596,
"s": 26576,
"text": "mastering-shiny.org"
},
{
"code": null,
"e": 26644,
"s": 26596,
"text": "You can find some handy Shiny cheatsheets here:"
},
{
"code": null,
"e": 26660,
"s": 26644,
"text": "www.rstudio.com"
}
] |
Difference between mutable and immutable in python?
|
Python defines variety of data types of objects. These objects are stored in memory and object mutability depends upon the type, like Lists and Dictionaries are mutable it means that we can change their content without changing their identity. Other objects like Integers, Floats, Strings and Tuples have no provision to change there assigned value for an index.
List is mutable: Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. Lists are mutable, and hence, they can be altered even after their creation.
#Write a python program to print list of a number?
list=[1,2,3,4,5]
print(list)
[1,2,3,4,5]
List is a collection which is ordered and changeable. Allows duplicate members.
list=[1,2,3,4,5]
list[0] ='a'
print(list)
['a', 2, 3, 4, 5]
While running the program, assigning the zero based index with the value of '1' can be assigned a value of 'a' which is mutable(can be modified)
Tuple is immutable: A tuple is a collection which is ordered and unchangeable, does not allow duplicate members. In Python tuples ar written with round or inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.
#Write a python program to print tuple of a number?
Tuple=(10,20,30)
print(tuple)
(10,20,30)
Tuple is ordered and unchangeable(cannot be modified).
tuple=(10,20,30)
tuple[0]=50
print(tuple)
TypeError Traceback (most recent call last)
in
1 my_yuple = (10, 20, 30)
----> 2 my_yuple[0] = 50
3 print(my_yuple)
TypeError: 'tuple' object does not support item assignment
While assigning the zero based index with the value of '50' throws an exception, because it is already assigned a value of '10' which is immutable(cannot be modified).
|
[
{
"code": null,
"e": 1425,
"s": 1062,
"text": "Python defines variety of data types of objects. These objects are stored in memory and object mutability depends upon the type, like Lists and Dictionaries are mutable it means that we can change their content without changing their identity. Other objects like Integers, Floats, Strings and Tuples have no provision to change there assigned value for an index."
},
{
"code": null,
"e": 1664,
"s": 1425,
"text": "List is mutable: Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. Lists are mutable, and hence, they can be altered even after their creation."
},
{
"code": null,
"e": 1744,
"s": 1664,
"text": "#Write a python program to print list of a number?\nlist=[1,2,3,4,5]\nprint(list)"
},
{
"code": null,
"e": 1756,
"s": 1744,
"text": "[1,2,3,4,5]"
},
{
"code": null,
"e": 1836,
"s": 1756,
"text": "List is a collection which is ordered and changeable. Allows duplicate members."
},
{
"code": null,
"e": 1878,
"s": 1836,
"text": "list=[1,2,3,4,5]\nlist[0] ='a'\nprint(list)"
},
{
"code": null,
"e": 1896,
"s": 1878,
"text": "['a', 2, 3, 4, 5]"
},
{
"code": null,
"e": 2041,
"s": 1896,
"text": "While running the program, assigning the zero based index with the value of '1' can be assigned a value of 'a' which is mutable(can be modified)"
},
{
"code": null,
"e": 2314,
"s": 2041,
"text": "Tuple is immutable: A tuple is a collection which is ordered and unchangeable, does not allow duplicate members. In Python tuples ar written with round or inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them."
},
{
"code": null,
"e": 2396,
"s": 2314,
"text": "#Write a python program to print tuple of a number?\nTuple=(10,20,30)\nprint(tuple)"
},
{
"code": null,
"e": 2407,
"s": 2396,
"text": "(10,20,30)"
},
{
"code": null,
"e": 2462,
"s": 2407,
"text": "Tuple is ordered and unchangeable(cannot be modified)."
},
{
"code": null,
"e": 2504,
"s": 2462,
"text": "tuple=(10,20,30)\ntuple[0]=50\nprint(tuple)"
},
{
"code": null,
"e": 2680,
"s": 2504,
"text": "TypeError Traceback (most recent call last)\nin\n1 my_yuple = (10, 20, 30)\n----> 2 my_yuple[0] = 50\n3 print(my_yuple)\n\nTypeError: 'tuple' object does not support item assignment"
},
{
"code": null,
"e": 2848,
"s": 2680,
"text": "While assigning the zero based index with the value of '50' throws an exception, because it is already assigned a value of '10' which is immutable(cannot be modified)."
}
] |
Jython - Installation
|
Before installation of Jython 2.7, ensure that the system has JDK 7 or more installed. Jython is available in the form of an executable jar file. Download it from - http://www.jython.org/downloads.html and either double click on its icon or run the following command −
java -jar jython_installer-2.7.0.jar
An installation wizard will commence with which installation options have to be given. Here is the systematic installation procedure.
The first step in the wizard asks you to select the language.
The second step prompts you to accept the licence agreement.
In the next step, choose the installation type. It is recommended to choose the Standard installation.
The next screen asks your confirmation about your options and proceeds to complete the installation.
The installation procedure might take some time to complete.
After the installation is complete, invoke jython.exe from the bin directory inside the destination directory. Assuming that Jython is installed in C:\jython27, execute the following from the command line.
C:\jython27\bin\jython
A Python prompt (>>>) will appear, in front of which any Python statement or Python script can be executed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2350,
"s": 2081,
"text": "Before installation of Jython 2.7, ensure that the system has JDK 7 or more installed. Jython is available in the form of an executable jar file. Download it from - http://www.jython.org/downloads.html and either double click on its icon or run the following command −"
},
{
"code": null,
"e": 2388,
"s": 2350,
"text": "java -jar jython_installer-2.7.0.jar\n"
},
{
"code": null,
"e": 2522,
"s": 2388,
"text": "An installation wizard will commence with which installation options have to be given. Here is the systematic installation procedure."
},
{
"code": null,
"e": 2584,
"s": 2522,
"text": "The first step in the wizard asks you to select the language."
},
{
"code": null,
"e": 2645,
"s": 2584,
"text": "The second step prompts you to accept the licence agreement."
},
{
"code": null,
"e": 2748,
"s": 2645,
"text": "In the next step, choose the installation type. It is recommended to choose the Standard installation."
},
{
"code": null,
"e": 2849,
"s": 2748,
"text": "The next screen asks your confirmation about your options and proceeds to complete the installation."
},
{
"code": null,
"e": 2910,
"s": 2849,
"text": "The installation procedure might take some time to complete."
},
{
"code": null,
"e": 3116,
"s": 2910,
"text": "After the installation is complete, invoke jython.exe from the bin directory inside the destination directory. Assuming that Jython is installed in C:\\jython27, execute the following from the command line."
},
{
"code": null,
"e": 3140,
"s": 3116,
"text": "C:\\jython27\\bin\\jython\n"
},
{
"code": null,
"e": 3248,
"s": 3140,
"text": "A Python prompt (>>>) will appear, in front of which any Python statement or Python script can be executed."
},
{
"code": null,
"e": 3255,
"s": 3248,
"text": " Print"
},
{
"code": null,
"e": 3266,
"s": 3255,
"text": " Add Notes"
}
] |
Remove nodes on root to leaf paths of length < K - GeeksforGeeks
|
02 May, 2022
Given a Binary Tree and a number k, remove all nodes that lie only on root to leaf path(s) of length smaller than k. If a node X lies on multiple root-to-leaf paths and if any of the paths has path length >= k, then X is not deleted from Binary Tree. In other words a node is deleted if all paths going through it have lengths smaller than k.Consider the following example Binary Tree
1
/ \
2 3
/ \ \
4 5 6
/ /
7 8
Input: Root of above Binary Tree
k = 4
Output: The tree should be changed to following
1
/ \
2 3
/ \
4 6
/ /
7 8
There are 3 paths
i) 1->2->4->7 path length = 4
ii) 1->2->5 path length = 3
iii) 1->3->6->8 path length = 4
There is only one path " 1->2->5 " of length smaller than 4.
The node 5 is the only node that lies only on this path, so
node 5 is removed.
Nodes 2 and 1 are not removed as they are parts of other paths
of length 4 as well.
If k is 5 or greater than 5, then whole tree is deleted.
If k is 3 or less than 3, then nothing is deleted.
We strongly recommend to minimize your browser and try this yourself firstThe idea here is to use post order traversal of the tree. Before removing a node we need to check that all the children of that node in the shorter path are already removed. There are 2 cases: i) This node becomes a leaf node in which case it needs to be deleted. ii) This node has other child on a path with path length >= k. In that case it needs not to be deleted.The implementation of above approach is as below :
C++
Java
Python3
C#
Javascript
// C++ program to remove nodes on root to leaf paths of length < K#include<bits/stdc++.h>using namespace std; struct Node{ int data; Node *left, *right;}; //New node of a treeNode *newNode(int data){ Node *node = new Node; node->data = data; node->left = node->right = NULL; return node;} // Utility method that actually removes the nodes which are not// on the pathLen >= k. This method can change the root as well.Node *removeShortPathNodesUtil(Node *root, int level, int k){ //Base condition if (root == NULL) return NULL; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. root->left = removeShortPathNodesUtil(root->left, level + 1, k); root->right = removeShortPathNodesUtil(root->right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (root->left == NULL && root->right == NULL && level < k) { delete root; return NULL; } // Return root; return root;} // Method which calls the utility method to remove the short path// nodes.Node *removeShortPathNodes(Node *root, int k){ int pathLen = 0; return removeShortPathNodesUtil(root, 1, k);} //Method to print the tree in inorder fashion.void printInorder(Node *root){ if (root) { printInorder(root->left); cout << root->data << " "; printInorder(root->right); }} // Driver method.int main(){ int k = 4; Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(7); root->right->right = newNode(6); root->right->right->left = newNode(8); cout << "Inorder Traversal of Original tree" << endl; printInorder(root); cout << endl; cout << "Inorder Traversal of Modified tree" << endl; Node *res = removeShortPathNodes(root, k); printInorder(res); return 0;}
// Java program to remove nodes on root to leaf paths of length < k /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. Node removeShortPathNodesUtil(Node node, int level, int k) { //Base condition if (node == null) return null; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) return null; // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. Node removeShortPathNodes(Node node, int k) { int pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. void printInorder(Node node) { if (node != null) { printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } } // Driver program to test for samples public static void main(String args[]) { BinaryTree tree = new BinaryTree(); int k = 4; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(7); tree.root.right.right = new Node(6); tree.root.right.right.left = new Node(8); System.out.println("The inorder traversal of original tree is : "); tree.printInorder(tree.root); Node res = tree.removeShortPathNodes(tree.root, k); System.out.println(""); System.out.println("The inorder traversal of modified tree is : "); tree.printInorder(res); }} // This code has been contributed by Mayank Jaiswal
# Python3 program to remove nodes on root# to leaf paths of length < K # New node of a treeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Utility method that actually removes# the nodes which are not on the pathLen >= k.# This method can change the root as well.def removeShortPathNodesUtil(root, level, k) : # Base condition if (root == None) : return None # Traverse the tree in postorder fashion # so that if a leaf node path length is # shorter than k, then that node and all # of its descendants till the node which # are not on some other path are removed. root.left = removeShortPathNodesUtil(root.left, level + 1, k) root.right = removeShortPathNodesUtil(root.right, level + 1, k) # If root is a leaf node and it's level # is less than k then remove this node. # This goes up and check for the ancestor # nodes also for the same condition till # it finds a node which is a part of other # path(s) too. if (root.left == None and root.right == None and level < k) : return None # Return root return root # Method which calls the utility method# to remove the short path nodes.def removeShortPathNodes(root, k) : pathLen = 0 return removeShortPathNodesUtil(root, 1, k) # Method to print the tree in# inorder fashion.def printInorder(root) : if (root) : printInorder(root.left) print(root.data, end = " " ) printInorder(root.right) # Driver Codeif __name__ == '__main__': k = 4 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.left.left = newNode(7) root.right.right = newNode(6) root.right.right.left = newNode(8) print("Inorder Traversal of Original tree" ) printInorder(root) print() print("Inorder Traversal of Modified tree" ) res = removeShortPathNodes(root, k) printInorder(res) # This code is contributed# by SHUBHAMSINGH10
using System; // C# program to remove nodes on root to leaf paths of length < k /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. public virtual Node removeShortPathNodesUtil(Node node, int level, int k) { //Base condition if (node == null) { return null; } // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) { return null; } // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. public virtual Node removeShortPathNodes(Node node, int k) { int pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. public virtual void printInorder(Node node) { if (node != null) { printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } } // Driver program to test for samples public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int k = 4; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(7); tree.root.right.right = new Node(6); tree.root.right.right.left = new Node(8); Console.WriteLine("The inorder traversal of original tree is : "); tree.printInorder(tree.root); Node res = tree.removeShortPathNodes(tree.root, k); Console.WriteLine(""); Console.WriteLine("The inorder traversal of modified tree is : "); tree.printInorder(res); }} // This code is contributed by Shrikant13
<script> // JavaScript program to remove nodes on // root to leaf paths of length < k class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. function removeShortPathNodesUtil(node, level, k) { //Base condition if (node == null) return null; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) return null; // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. function removeShortPathNodes(node, k) { let pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. function printInorder(node) { if (node != null) { printInorder(node.left); document.write(node.data + " "); printInorder(node.right); } } let k = 4; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(7); root.right.right = new Node(6); root.right.right.left = new Node(8); document.write("The inorder traversal of Original tree is : " + "</br>"); printInorder(root); let res = removeShortPathNodes(root, k); document.write("</br>"); document.write("The inorder traversal of Modified tree is : " + "</br>"); printInorder(res); </script>
Output:
Inorder Traversal of Original tree
7 4 2 5 1 3 8 6
Inorder Traversal of Modified tree
7 4 2 1 3 8 6
Time complexity of the above solution is O(n) where n is number of nodes in given Binary Tree.
YouTubeGeeksforGeeks507K subscribersRemove nodes on root to leaf paths of length less than K | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bGD7nHS-5Q8" 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 Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
SHUBHAMSINGH10
mukesh07
adnanirshad158
simmytarika5
tree-traversal
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 2 (Properties)
Decision Tree
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
BFS vs DFS for Binary Tree
Deletion in a Binary Tree
Binary Tree (Array implementation)
Segment Tree | Set 1 (Sum of given range)
|
[
{
"code": null,
"e": 26445,
"s": 26417,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 26832,
"s": 26445,
"text": "Given a Binary Tree and a number k, remove all nodes that lie only on root to leaf path(s) of length smaller than k. If a node X lies on multiple root-to-leaf paths and if any of the paths has path length >= k, then X is not deleted from Binary Tree. In other words a node is deleted if all paths going through it have lengths smaller than k.Consider the following example Binary Tree "
},
{
"code": null,
"e": 27683,
"s": 26832,
"text": " 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / /\n 7 8 \nInput: Root of above Binary Tree\n k = 4\n\nOutput: The tree should be changed to following \n 1\n / \\\n 2 3\n / \\\n 4 6\n / /\n7 8\nThere are 3 paths \ni) 1->2->4->7 path length = 4\nii) 1->2->5 path length = 3\niii) 1->3->6->8 path length = 4 \nThere is only one path \" 1->2->5 \" of length smaller than 4. \nThe node 5 is the only node that lies only on this path, so \nnode 5 is removed.\nNodes 2 and 1 are not removed as they are parts of other paths\nof length 4 as well.\n\nIf k is 5 or greater than 5, then whole tree is deleted. \n\nIf k is 3 or less than 3, then nothing is deleted."
},
{
"code": null,
"e": 28177,
"s": 27683,
"text": "We strongly recommend to minimize your browser and try this yourself firstThe idea here is to use post order traversal of the tree. Before removing a node we need to check that all the children of that node in the shorter path are already removed. There are 2 cases: i) This node becomes a leaf node in which case it needs to be deleted. ii) This node has other child on a path with path length >= k. In that case it needs not to be deleted.The implementation of above approach is as below : "
},
{
"code": null,
"e": 28181,
"s": 28177,
"text": "C++"
},
{
"code": null,
"e": 28186,
"s": 28181,
"text": "Java"
},
{
"code": null,
"e": 28194,
"s": 28186,
"text": "Python3"
},
{
"code": null,
"e": 28197,
"s": 28194,
"text": "C#"
},
{
"code": null,
"e": 28208,
"s": 28197,
"text": "Javascript"
},
{
"code": "// C++ program to remove nodes on root to leaf paths of length < K#include<bits/stdc++.h>using namespace std; struct Node{ int data; Node *left, *right;}; //New node of a treeNode *newNode(int data){ Node *node = new Node; node->data = data; node->left = node->right = NULL; return node;} // Utility method that actually removes the nodes which are not// on the pathLen >= k. This method can change the root as well.Node *removeShortPathNodesUtil(Node *root, int level, int k){ //Base condition if (root == NULL) return NULL; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. root->left = removeShortPathNodesUtil(root->left, level + 1, k); root->right = removeShortPathNodesUtil(root->right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (root->left == NULL && root->right == NULL && level < k) { delete root; return NULL; } // Return root; return root;} // Method which calls the utility method to remove the short path// nodes.Node *removeShortPathNodes(Node *root, int k){ int pathLen = 0; return removeShortPathNodesUtil(root, 1, k);} //Method to print the tree in inorder fashion.void printInorder(Node *root){ if (root) { printInorder(root->left); cout << root->data << \" \"; printInorder(root->right); }} // Driver method.int main(){ int k = 4; Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(7); root->right->right = newNode(6); root->right->right->left = newNode(8); cout << \"Inorder Traversal of Original tree\" << endl; printInorder(root); cout << endl; cout << \"Inorder Traversal of Modified tree\" << endl; Node *res = removeShortPathNodes(root, k); printInorder(res); return 0;}",
"e": 30456,
"s": 28208,
"text": null
},
{
"code": "// Java program to remove nodes on root to leaf paths of length < k /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. Node removeShortPathNodesUtil(Node node, int level, int k) { //Base condition if (node == null) return null; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) return null; // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. Node removeShortPathNodes(Node node, int k) { int pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. void printInorder(Node node) { if (node != null) { printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } } // Driver program to test for samples public static void main(String args[]) { BinaryTree tree = new BinaryTree(); int k = 4; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(7); tree.root.right.right = new Node(6); tree.root.right.right.left = new Node(8); System.out.println(\"The inorder traversal of original tree is : \"); tree.printInorder(tree.root); Node res = tree.removeShortPathNodes(tree.root, k); System.out.println(\"\"); System.out.println(\"The inorder traversal of modified tree is : \"); tree.printInorder(res); }} // This code has been contributed by Mayank Jaiswal",
"e": 33154,
"s": 30456,
"text": null
},
{
"code": "# Python3 program to remove nodes on root# to leaf paths of length < K # New node of a treeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Utility method that actually removes# the nodes which are not on the pathLen >= k.# This method can change the root as well.def removeShortPathNodesUtil(root, level, k) : # Base condition if (root == None) : return None # Traverse the tree in postorder fashion # so that if a leaf node path length is # shorter than k, then that node and all # of its descendants till the node which # are not on some other path are removed. root.left = removeShortPathNodesUtil(root.left, level + 1, k) root.right = removeShortPathNodesUtil(root.right, level + 1, k) # If root is a leaf node and it's level # is less than k then remove this node. # This goes up and check for the ancestor # nodes also for the same condition till # it finds a node which is a part of other # path(s) too. if (root.left == None and root.right == None and level < k) : return None # Return root return root # Method which calls the utility method# to remove the short path nodes.def removeShortPathNodes(root, k) : pathLen = 0 return removeShortPathNodesUtil(root, 1, k) # Method to print the tree in# inorder fashion.def printInorder(root) : if (root) : printInorder(root.left) print(root.data, end = \" \" ) printInorder(root.right) # Driver Codeif __name__ == '__main__': k = 4 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.left.left = newNode(7) root.right.right = newNode(6) root.right.right.left = newNode(8) print(\"Inorder Traversal of Original tree\" ) printInorder(root) print() print(\"Inorder Traversal of Modified tree\" ) res = removeShortPathNodes(root, k) printInorder(res) # This code is contributed# by SHUBHAMSINGH10",
"e": 35291,
"s": 33154,
"text": null
},
{
"code": "using System; // C# program to remove nodes on root to leaf paths of length < k /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. public virtual Node removeShortPathNodesUtil(Node node, int level, int k) { //Base condition if (node == null) { return null; } // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) { return null; } // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. public virtual Node removeShortPathNodes(Node node, int k) { int pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. public virtual void printInorder(Node node) { if (node != null) { printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } } // Driver program to test for samples public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int k = 4; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(7); tree.root.right.right = new Node(6); tree.root.right.right.left = new Node(8); Console.WriteLine(\"The inorder traversal of original tree is : \"); tree.printInorder(tree.root); Node res = tree.removeShortPathNodes(tree.root, k); Console.WriteLine(\"\"); Console.WriteLine(\"The inorder traversal of modified tree is : \"); tree.printInorder(res); }} // This code is contributed by Shrikant13",
"e": 38083,
"s": 35291,
"text": null
},
{
"code": "<script> // JavaScript program to remove nodes on // root to leaf paths of length < k class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; // Utility method that actually removes the nodes which are not // on the pathLen >= k. This method can change the root as well. function removeShortPathNodesUtil(node, level, k) { //Base condition if (node == null) return null; // Traverse the tree in postorder fashion so that if a leaf // node path length is shorter than k, then that node and // all of its descendants till the node which are not // on some other path are removed. node.left = removeShortPathNodesUtil(node.left, level + 1, k); node.right = removeShortPathNodesUtil(node.right, level + 1, k); // If root is a leaf node and it's level is less than k then // remove this node. // This goes up and check for the ancestor nodes also for the // same condition till it finds a node which is a part of other // path(s) too. if (node.left == null && node.right == null && level < k) return null; // Return root; return node; } // Method which calls the utility method to remove the short path // nodes. function removeShortPathNodes(node, k) { let pathLen = 0; return removeShortPathNodesUtil(node, 1, k); } //Method to print the tree in inorder fashion. function printInorder(node) { if (node != null) { printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right); } } let k = 4; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(7); root.right.right = new Node(6); root.right.right.left = new Node(8); document.write(\"The inorder traversal of Original tree is : \" + \"</br>\"); printInorder(root); let res = removeShortPathNodes(root, k); document.write(\"</br>\"); document.write(\"The inorder traversal of Modified tree is : \" + \"</br>\"); printInorder(res); </script>",
"e": 40447,
"s": 38083,
"text": null
},
{
"code": null,
"e": 40456,
"s": 40447,
"text": "Output: "
},
{
"code": null,
"e": 40556,
"s": 40456,
"text": "Inorder Traversal of Original tree\n7 4 2 5 1 3 8 6\nInorder Traversal of Modified tree\n7 4 2 1 3 8 6"
},
{
"code": null,
"e": 40652,
"s": 40556,
"text": "Time complexity of the above solution is O(n) where n is number of nodes in given Binary Tree. "
},
{
"code": null,
"e": 41507,
"s": 40652,
"text": "YouTubeGeeksforGeeks507K subscribersRemove nodes on root to leaf paths of length less than K | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bGD7nHS-5Q8\" 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": 41677,
"s": 41507,
"text": "This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 41689,
"s": 41677,
"text": "shrikanth13"
},
{
"code": null,
"e": 41704,
"s": 41689,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 41713,
"s": 41704,
"text": "mukesh07"
},
{
"code": null,
"e": 41728,
"s": 41713,
"text": "adnanirshad158"
},
{
"code": null,
"e": 41741,
"s": 41728,
"text": "simmytarika5"
},
{
"code": null,
"e": 41756,
"s": 41741,
"text": "tree-traversal"
},
{
"code": null,
"e": 41761,
"s": 41756,
"text": "Tree"
},
{
"code": null,
"e": 41766,
"s": 41761,
"text": "Tree"
},
{
"code": null,
"e": 41864,
"s": 41766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41897,
"s": 41864,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 41911,
"s": 41897,
"text": "Decision Tree"
},
{
"code": null,
"e": 41969,
"s": 41911,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 42005,
"s": 41969,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 42088,
"s": 42005,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 42104,
"s": 42088,
"text": "Expression Tree"
},
{
"code": null,
"e": 42131,
"s": 42104,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 42157,
"s": 42131,
"text": "Deletion in a Binary Tree"
},
{
"code": null,
"e": 42192,
"s": 42157,
"text": "Binary Tree (Array implementation)"
}
] |
Different ways to concatenate two strings in Golang - GeeksforGeeks
|
09 Aug, 2019
In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator.
Example:
// Go program to illustrate// how to concatenate stringspackage main import "fmt" func main() { // Creating and initializing strings // using var keyword var str1 string str1 = "Welcome!" var str2 string str2 = "GeeksforGeeks" // Concatenating strings // Using + operator fmt.Println("New string 1: ", str1+str2) // Creating and initializing strings // Using shorthand declaration str3 := "Geeks" str4 := "Geeks" // Concatenating strings // Using + operator result := str3 + "for" + str4 fmt.Println("New string 2: ", result) }
Output:
New string 1: Welcome!GeeksforGeeks
New string 2: GeeksforGeeks
Using bytes.Buffer: You can also create a string by concatenating the bytes of the strings using bytes.Buffer with WriteString() method. It is defined under bytes package. It prevents the generation of the unnecessary string object, means it doesn’t generate a new string like in + operator from two or more strings.Example:// Go program to illustrate how to concatenate strings// Using bytes.Buffer with WriteString() functionpackage main import ( "bytes" "fmt") func main() { // Creating and initializing strings // Using bytes.Buffer with // WriteString() function var b bytes.Buffer b.WriteString("G") b.WriteString("e") b.WriteString("e") b.WriteString("k") b.WriteString("s") fmt.Println("String: ", b.String()) b.WriteString("f") b.WriteString("o") b.WriteString("r") b.WriteString("G") b.WriteString("e") b.WriteString("e") b.WriteString("k") b.WriteString("s") fmt.Println("String: ", b.String()) }Output:String: Geeks
String: GeeksforGeeks
Example:
// Go program to illustrate how to concatenate strings// Using bytes.Buffer with WriteString() functionpackage main import ( "bytes" "fmt") func main() { // Creating and initializing strings // Using bytes.Buffer with // WriteString() function var b bytes.Buffer b.WriteString("G") b.WriteString("e") b.WriteString("e") b.WriteString("k") b.WriteString("s") fmt.Println("String: ", b.String()) b.WriteString("f") b.WriteString("o") b.WriteString("r") b.WriteString("G") b.WriteString("e") b.WriteString("e") b.WriteString("k") b.WriteString("s") fmt.Println("String: ", b.String()) }
Output:
String: Geeks
String: GeeksforGeeks
Using Sprintf: In Go language, you can also concatenate string using Sprintf() method.Example:// Go program to illustrate how to concatenate strings// Using Sprintf functionpackage main import "fmt" func main() { // Creating and initializing strings str1 := "Tutorial" str2 := "of" str3 := "Go" str4 := "Language" // Concatenating strings using // Sprintf() function result := fmt.Sprintf("%s%s%s%s", str1, str2, str3, str4) fmt.Println(result)}Output:TutorialofGoLanguage
Example:
// Go program to illustrate how to concatenate strings// Using Sprintf functionpackage main import "fmt" func main() { // Creating and initializing strings str1 := "Tutorial" str2 := "of" str3 := "Go" str4 := "Language" // Concatenating strings using // Sprintf() function result := fmt.Sprintf("%s%s%s%s", str1, str2, str3, str4) fmt.Println(result)}
Output:
TutorialofGoLanguage
Using += operator or String append: In Go strings, you are allowed to append a string using += operator. This operator adds a new or given string to the end of the specified string.Example:// Go program to illustrate how// to concatenate strings// Using += operatorpackage main import "fmt" func main() { // Creating and initializing strings str1 := "Welcome" str2 := "GeeksforGeeks" // Using += operator str1 += str2 fmt.Println("String: ", str1) str1 += "This is the tutorial of Go language" fmt.Println("String: ", str1) str2 += "Portal" fmt.Println("String: ", str2) }Output:String: WelcomeGeeksforGeeks
String: WelcomeGeeksforGeeksThis is the tutorial of Go language
String: GeeksforGeeksPortal
Example:
// Go program to illustrate how// to concatenate strings// Using += operatorpackage main import "fmt" func main() { // Creating and initializing strings str1 := "Welcome" str2 := "GeeksforGeeks" // Using += operator str1 += str2 fmt.Println("String: ", str1) str1 += "This is the tutorial of Go language" fmt.Println("String: ", str1) str2 += "Portal" fmt.Println("String: ", str2) }
Output:
String: WelcomeGeeksforGeeks
String: WelcomeGeeksforGeeksThis is the tutorial of Go language
String: GeeksforGeeksPortal
Using Join() function: This function concatenates all the elements present in the slice of string into a single string. This function is available in string package.Syntax:func Join(str []string, sep string) stringHere, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string.Example:// Go program to illustrate how to// concatenate all the elements// present in the slice of the stringpackage main import ( "fmt" "strings") func main() { // Creating and initializing slice of string myslice := []string{"Welcome", "To", "GeeksforGeeks", "Portal"} // Concatenating the elements // present in the slice // Using join() function result := strings.Join(myslice, "-") fmt.Println(result)}Output:Welcome-To-GeeksforGeeks-Portal
Syntax:
func Join(str []string, sep string) string
Here, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string.
Example:
// Go program to illustrate how to// concatenate all the elements// present in the slice of the stringpackage main import ( "fmt" "strings") func main() { // Creating and initializing slice of string myslice := []string{"Welcome", "To", "GeeksforGeeks", "Portal"} // Concatenating the elements // present in the slice // Using join() function result := strings.Join(myslice, "-") fmt.Println(result)}
Output:
Welcome-To-GeeksforGeeks-Portal
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
6 Best Books to Learn Go Programming Language
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 26002,
"s": 25653,
"text": "In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator."
},
{
"code": null,
"e": 26011,
"s": 26002,
"text": "Example:"
},
{
"code": "// Go program to illustrate// how to concatenate stringspackage main import \"fmt\" func main() { // Creating and initializing strings // using var keyword var str1 string str1 = \"Welcome!\" var str2 string str2 = \"GeeksforGeeks\" // Concatenating strings // Using + operator fmt.Println(\"New string 1: \", str1+str2) // Creating and initializing strings // Using shorthand declaration str3 := \"Geeks\" str4 := \"Geeks\" // Concatenating strings // Using + operator result := str3 + \"for\" + str4 fmt.Println(\"New string 2: \", result) }",
"e": 26605,
"s": 26011,
"text": null
},
{
"code": null,
"e": 26613,
"s": 26605,
"text": "Output:"
},
{
"code": null,
"e": 26680,
"s": 26613,
"text": "New string 1: Welcome!GeeksforGeeks\nNew string 2: GeeksforGeeks\n"
},
{
"code": null,
"e": 27722,
"s": 26680,
"text": "Using bytes.Buffer: You can also create a string by concatenating the bytes of the strings using bytes.Buffer with WriteString() method. It is defined under bytes package. It prevents the generation of the unnecessary string object, means it doesn’t generate a new string like in + operator from two or more strings.Example:// Go program to illustrate how to concatenate strings// Using bytes.Buffer with WriteString() functionpackage main import ( \"bytes\" \"fmt\") func main() { // Creating and initializing strings // Using bytes.Buffer with // WriteString() function var b bytes.Buffer b.WriteString(\"G\") b.WriteString(\"e\") b.WriteString(\"e\") b.WriteString(\"k\") b.WriteString(\"s\") fmt.Println(\"String: \", b.String()) b.WriteString(\"f\") b.WriteString(\"o\") b.WriteString(\"r\") b.WriteString(\"G\") b.WriteString(\"e\") b.WriteString(\"e\") b.WriteString(\"k\") b.WriteString(\"s\") fmt.Println(\"String: \", b.String()) }Output:String: Geeks\nString: GeeksforGeeks\n"
},
{
"code": null,
"e": 27731,
"s": 27722,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to concatenate strings// Using bytes.Buffer with WriteString() functionpackage main import ( \"bytes\" \"fmt\") func main() { // Creating and initializing strings // Using bytes.Buffer with // WriteString() function var b bytes.Buffer b.WriteString(\"G\") b.WriteString(\"e\") b.WriteString(\"e\") b.WriteString(\"k\") b.WriteString(\"s\") fmt.Println(\"String: \", b.String()) b.WriteString(\"f\") b.WriteString(\"o\") b.WriteString(\"r\") b.WriteString(\"G\") b.WriteString(\"e\") b.WriteString(\"e\") b.WriteString(\"k\") b.WriteString(\"s\") fmt.Println(\"String: \", b.String()) }",
"e": 28404,
"s": 27731,
"text": null
},
{
"code": null,
"e": 28412,
"s": 28404,
"text": "Output:"
},
{
"code": null,
"e": 28451,
"s": 28412,
"text": "String: Geeks\nString: GeeksforGeeks\n"
},
{
"code": null,
"e": 28990,
"s": 28451,
"text": "Using Sprintf: In Go language, you can also concatenate string using Sprintf() method.Example:// Go program to illustrate how to concatenate strings// Using Sprintf functionpackage main import \"fmt\" func main() { // Creating and initializing strings str1 := \"Tutorial\" str2 := \"of\" str3 := \"Go\" str4 := \"Language\" // Concatenating strings using // Sprintf() function result := fmt.Sprintf(\"%s%s%s%s\", str1, str2, str3, str4) fmt.Println(result)}Output:TutorialofGoLanguage"
},
{
"code": null,
"e": 28999,
"s": 28990,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to concatenate strings// Using Sprintf functionpackage main import \"fmt\" func main() { // Creating and initializing strings str1 := \"Tutorial\" str2 := \"of\" str3 := \"Go\" str4 := \"Language\" // Concatenating strings using // Sprintf() function result := fmt.Sprintf(\"%s%s%s%s\", str1, str2, str3, str4) fmt.Println(result)}",
"e": 29417,
"s": 28999,
"text": null
},
{
"code": null,
"e": 29425,
"s": 29417,
"text": "Output:"
},
{
"code": null,
"e": 29446,
"s": 29425,
"text": "TutorialofGoLanguage"
},
{
"code": null,
"e": 30191,
"s": 29446,
"text": "Using += operator or String append: In Go strings, you are allowed to append a string using += operator. This operator adds a new or given string to the end of the specified string.Example:// Go program to illustrate how// to concatenate strings// Using += operatorpackage main import \"fmt\" func main() { // Creating and initializing strings str1 := \"Welcome\" str2 := \"GeeksforGeeks\" // Using += operator str1 += str2 fmt.Println(\"String: \", str1) str1 += \"This is the tutorial of Go language\" fmt.Println(\"String: \", str1) str2 += \"Portal\" fmt.Println(\"String: \", str2) }Output:String: WelcomeGeeksforGeeks\nString: WelcomeGeeksforGeeksThis is the tutorial of Go language\nString: GeeksforGeeksPortal\n"
},
{
"code": null,
"e": 30200,
"s": 30191,
"text": "Example:"
},
{
"code": "// Go program to illustrate how// to concatenate strings// Using += operatorpackage main import \"fmt\" func main() { // Creating and initializing strings str1 := \"Welcome\" str2 := \"GeeksforGeeks\" // Using += operator str1 += str2 fmt.Println(\"String: \", str1) str1 += \"This is the tutorial of Go language\" fmt.Println(\"String: \", str1) str2 += \"Portal\" fmt.Println(\"String: \", str2) }",
"e": 30625,
"s": 30200,
"text": null
},
{
"code": null,
"e": 30633,
"s": 30625,
"text": "Output:"
},
{
"code": null,
"e": 30758,
"s": 30633,
"text": "String: WelcomeGeeksforGeeks\nString: WelcomeGeeksforGeeksThis is the tutorial of Go language\nString: GeeksforGeeksPortal\n"
},
{
"code": null,
"e": 31611,
"s": 30758,
"text": "Using Join() function: This function concatenates all the elements present in the slice of string into a single string. This function is available in string package.Syntax:func Join(str []string, sep string) stringHere, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string.Example:// Go program to illustrate how to// concatenate all the elements// present in the slice of the stringpackage main import ( \"fmt\" \"strings\") func main() { // Creating and initializing slice of string myslice := []string{\"Welcome\", \"To\", \"GeeksforGeeks\", \"Portal\"} // Concatenating the elements // present in the slice // Using join() function result := strings.Join(myslice, \"-\") fmt.Println(result)}Output:Welcome-To-GeeksforGeeks-Portal"
},
{
"code": null,
"e": 31619,
"s": 31611,
"text": "Syntax:"
},
{
"code": null,
"e": 31662,
"s": 31619,
"text": "func Join(str []string, sep string) string"
},
{
"code": null,
"e": 31808,
"s": 31662,
"text": "Here, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string."
},
{
"code": null,
"e": 31817,
"s": 31808,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to// concatenate all the elements// present in the slice of the stringpackage main import ( \"fmt\" \"strings\") func main() { // Creating and initializing slice of string myslice := []string{\"Welcome\", \"To\", \"GeeksforGeeks\", \"Portal\"} // Concatenating the elements // present in the slice // Using join() function result := strings.Join(myslice, \"-\") fmt.Println(result)}",
"e": 32265,
"s": 31817,
"text": null
},
{
"code": null,
"e": 32273,
"s": 32265,
"text": "Output:"
},
{
"code": null,
"e": 32305,
"s": 32273,
"text": "Welcome-To-GeeksforGeeks-Portal"
},
{
"code": null,
"e": 32312,
"s": 32305,
"text": "Golang"
},
{
"code": null,
"e": 32326,
"s": 32312,
"text": "Golang-String"
},
{
"code": null,
"e": 32338,
"s": 32326,
"text": "Go Language"
},
{
"code": null,
"e": 32436,
"s": 32338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32449,
"s": 32436,
"text": "Arrays in Go"
},
{
"code": null,
"e": 32495,
"s": 32449,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 32507,
"s": 32495,
"text": "Golang Maps"
},
{
"code": null,
"e": 32524,
"s": 32507,
"text": "Slices in Golang"
},
{
"code": null,
"e": 32578,
"s": 32524,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 32600,
"s": 32578,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 32621,
"s": 32600,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 32653,
"s": 32621,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 32685,
"s": 32653,
"text": "How to compare times in Golang?"
}
] |
GATE | Gate IT 2008 | Question 40 - GeeksforGeeks
|
29 Mar, 2018
The two numbers given below are multiplied using the Booth’s algorithm.
Multiplicand : 0101 1010 1110 1110Multiplier: 0111 0111 1011 1101
How many additions/Subtractions are required for the multiplication of the above two numbers?(A) 6(B) 8(C) 10(D) 12Answer: (B)Explanation: Booth’s algorithm: first take 2’s complement of given number if number is negative, then append 0 into LSB.
Then, for each pair from LSB to MSB (add 1 bit at a time):
00 = 0, 01 = +1, 10 = -1, 11 = 0
Booth’s algorithm is based on Multiplier which is already given in binary representation: 0111 0111 1011 1101
= Now, append 0 into LSB of (0111 0111 1011 1101) = 0111 0111 1011 1101 0
Now Booth's code (add 1 bit at a time, from LSB to MSB):
= 01, 11, 11, 10, 01, 11, 11, 11, 10, 01, 11, 11, 11, 10, 01, 10
= +1 0 0 -1 +1 0 0 0 -1 +1 0 0 0 -1 +1 -1
Therefore, 4 subtractions and 4 additions, total 8 additions/Subtractions are required.
So, option (B) is correct.Quiz of this Question
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25885,
"s": 25857,
"text": "\n29 Mar, 2018"
},
{
"code": null,
"e": 25957,
"s": 25885,
"text": "The two numbers given below are multiplied using the Booth’s algorithm."
},
{
"code": null,
"e": 26023,
"s": 25957,
"text": "Multiplicand : 0101 1010 1110 1110Multiplier: 0111 0111 1011 1101"
},
{
"code": null,
"e": 26270,
"s": 26023,
"text": "How many additions/Subtractions are required for the multiplication of the above two numbers?(A) 6(B) 8(C) 10(D) 12Answer: (B)Explanation: Booth’s algorithm: first take 2’s complement of given number if number is negative, then append 0 into LSB."
},
{
"code": null,
"e": 26362,
"s": 26270,
"text": "Then, for each pair from LSB to MSB (add 1 bit at a time):\n00 = 0, 01 = +1, 10 = -1, 11 = 0"
},
{
"code": null,
"e": 26472,
"s": 26362,
"text": "Booth’s algorithm is based on Multiplier which is already given in binary representation: 0111 0111 1011 1101"
},
{
"code": null,
"e": 26710,
"s": 26472,
"text": "= Now, append 0 into LSB of (0111 0111 1011 1101) = 0111 0111 1011 1101 0\nNow Booth's code (add 1 bit at a time, from LSB to MSB):\n= 01, 11, 11, 10, 01, 11, 11, 11, 10, 01, 11, 11, 11, 10, 01, 10\n= +1 0 0 -1 +1 0 0 0 -1 +1 0 0 0 -1 +1 -1"
},
{
"code": null,
"e": 26798,
"s": 26710,
"text": "Therefore, 4 subtractions and 4 additions, total 8 additions/Subtractions are required."
},
{
"code": null,
"e": 26846,
"s": 26798,
"text": "So, option (B) is correct.Quiz of this Question"
},
{
"code": null,
"e": 26859,
"s": 26846,
"text": "Gate IT 2008"
},
{
"code": null,
"e": 26877,
"s": 26859,
"text": "GATE-Gate IT 2008"
},
{
"code": null,
"e": 26882,
"s": 26877,
"text": "GATE"
},
{
"code": null,
"e": 26980,
"s": 26882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27014,
"s": 26980,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27048,
"s": 27014,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27082,
"s": 27048,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27115,
"s": 27082,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27151,
"s": 27115,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27185,
"s": 27151,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27221,
"s": 27185,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27255,
"s": 27221,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27289,
"s": 27255,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Rust - Switch Case - GeeksforGeeks
|
19 Jul, 2021
Switch statement is basically nested if statement, though it does not support expression, it matches an int, string, or boolean data type variable with a given set of cases that are provided by the programmer. It is mainly used in a menu-driven program where the user selects which function they want to run. A switch case in Rust is achieved by the keyword match. Let’s see a few examples to see how it works.
Unlike C or Java, only the case corresponding to the match is executed, so we need not worry about fall through. Thereby saving our effort to write a break statement after each case. Default case, where no match is found, is handled by the case ‘_’ (underscore). There is something special in Rust, the cases can have more than one value.
Example:
Rust
fn main() { let num=3; match num{ 1=>println!("One"), 2=>println!("Two"), 3=>println!("Three"), _=>println!("Rest of the number"), }
Output
Three
Several values can be included in a single case by separating them via ‘|’.
Example:
Rust
fn main() { let num=2; match num{ 1|3|5|7|9=>println!("Odd"), 2|4|6|8=>println!("Even"), _=>println!("Only one digit allowed"), } }
Output
Even
It’s not the end we can also include a range of values in each case.
A range is inclusive in this case that means both the ends are also included.
Example:
Rust
fn main() { let num=19; match num{ 13..=19=>println!("Teenage"), _=>println!("Not Teenage"), } }
Output
Teenage
As stated in the beginning we can also use boolean values to match cases, we will now go for it. One more thing is that match can be used in an expression.
Example:
Rust
fn main() { let head = false; let coin_side = match head{ false => "tail", true => "head", }; println!("Coin Side={}", coin_side)}
Output
Coin Side=tail
At last, we will see how strings are used in matches.
Example:
Rust
fn main() { let coin = "head"; match coin{ "head" =>println!("head"), "tail"=> println!("tail"), _=>println!("False coin"), };}
Output
head
rust-control-flow
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Generate Random Numbers in Rust Language?
Rust - Casting
Rust - For and Range
Rust - Generic Function
Rust - Creating a Library
Rust - References & Borrowing
Rust - Concept of Structures
Rust - Box Smart Pointer
Rust - Concept of Smart Pointers
Rust - While Loop
|
[
{
"code": null,
"e": 24879,
"s": 24851,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 25290,
"s": 24879,
"text": "Switch statement is basically nested if statement, though it does not support expression, it matches an int, string, or boolean data type variable with a given set of cases that are provided by the programmer. It is mainly used in a menu-driven program where the user selects which function they want to run. A switch case in Rust is achieved by the keyword match. Let’s see a few examples to see how it works."
},
{
"code": null,
"e": 25630,
"s": 25290,
"text": "Unlike C or Java, only the case corresponding to the match is executed, so we need not worry about fall through. Thereby saving our effort to write a break statement after each case. Default case, where no match is found, is handled by the case ‘_’ (underscore). There is something special in Rust, the cases can have more than one value. "
},
{
"code": null,
"e": 25639,
"s": 25630,
"text": "Example:"
},
{
"code": null,
"e": 25644,
"s": 25639,
"text": "Rust"
},
{
"code": "fn main() { let num=3; match num{ 1=>println!(\"One\"), 2=>println!(\"Two\"), 3=>println!(\"Three\"), _=>println!(\"Rest of the number\"), }",
"e": 25784,
"s": 25644,
"text": null
},
{
"code": null,
"e": 25791,
"s": 25784,
"text": "Output"
},
{
"code": null,
"e": 25797,
"s": 25791,
"text": "Three"
},
{
"code": null,
"e": 25873,
"s": 25797,
"text": "Several values can be included in a single case by separating them via ‘|’."
},
{
"code": null,
"e": 25882,
"s": 25873,
"text": "Example:"
},
{
"code": null,
"e": 25887,
"s": 25882,
"text": "Rust"
},
{
"code": "fn main() { let num=2; match num{ 1|3|5|7|9=>println!(\"Odd\"), 2|4|6|8=>println!(\"Even\"), _=>println!(\"Only one digit allowed\"), } }",
"e": 26027,
"s": 25887,
"text": null
},
{
"code": null,
"e": 26034,
"s": 26027,
"text": "Output"
},
{
"code": null,
"e": 26039,
"s": 26034,
"text": "Even"
},
{
"code": null,
"e": 26110,
"s": 26039,
"text": " It’s not the end we can also include a range of values in each case. "
},
{
"code": null,
"e": 26189,
"s": 26110,
"text": " A range is inclusive in this case that means both the ends are also included."
},
{
"code": null,
"e": 26198,
"s": 26189,
"text": "Example:"
},
{
"code": null,
"e": 26203,
"s": 26198,
"text": "Rust"
},
{
"code": "fn main() { let num=19; match num{ 13..=19=>println!(\"Teenage\"), _=>println!(\"Not Teenage\"), } }",
"e": 26306,
"s": 26203,
"text": null
},
{
"code": null,
"e": 26313,
"s": 26306,
"text": "Output"
},
{
"code": null,
"e": 26321,
"s": 26313,
"text": "Teenage"
},
{
"code": null,
"e": 26477,
"s": 26321,
"text": "As stated in the beginning we can also use boolean values to match cases, we will now go for it. One more thing is that match can be used in an expression."
},
{
"code": null,
"e": 26486,
"s": 26477,
"text": "Example:"
},
{
"code": null,
"e": 26491,
"s": 26486,
"text": "Rust"
},
{
"code": "fn main() { let head = false; let coin_side = match head{ false => \"tail\", true => \"head\", }; println!(\"Coin Side={}\", coin_side)}",
"e": 26646,
"s": 26491,
"text": null
},
{
"code": null,
"e": 26653,
"s": 26646,
"text": "Output"
},
{
"code": null,
"e": 26668,
"s": 26653,
"text": "Coin Side=tail"
},
{
"code": null,
"e": 26722,
"s": 26668,
"text": "At last, we will see how strings are used in matches."
},
{
"code": null,
"e": 26731,
"s": 26722,
"text": "Example:"
},
{
"code": null,
"e": 26736,
"s": 26731,
"text": "Rust"
},
{
"code": "fn main() { let coin = \"head\"; match coin{ \"head\" =>println!(\"head\"), \"tail\"=> println!(\"tail\"), _=>println!(\"False coin\"), };}",
"e": 26892,
"s": 26736,
"text": null
},
{
"code": null,
"e": 26899,
"s": 26892,
"text": "Output"
},
{
"code": null,
"e": 26904,
"s": 26899,
"text": "head"
},
{
"code": null,
"e": 26922,
"s": 26904,
"text": "rust-control-flow"
},
{
"code": null,
"e": 26927,
"s": 26922,
"text": "Rust"
},
{
"code": null,
"e": 27025,
"s": 26927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27074,
"s": 27025,
"text": "How to Generate Random Numbers in Rust Language?"
},
{
"code": null,
"e": 27089,
"s": 27074,
"text": "Rust - Casting"
},
{
"code": null,
"e": 27110,
"s": 27089,
"text": "Rust - For and Range"
},
{
"code": null,
"e": 27134,
"s": 27110,
"text": "Rust - Generic Function"
},
{
"code": null,
"e": 27160,
"s": 27134,
"text": "Rust - Creating a Library"
},
{
"code": null,
"e": 27190,
"s": 27160,
"text": "Rust - References & Borrowing"
},
{
"code": null,
"e": 27219,
"s": 27190,
"text": "Rust - Concept of Structures"
},
{
"code": null,
"e": 27244,
"s": 27219,
"text": "Rust - Box Smart Pointer"
},
{
"code": null,
"e": 27277,
"s": 27244,
"text": "Rust - Concept of Smart Pointers"
}
] |
SMS Verification in Android using SMS User Consent API - GeeksforGeeks
|
19 Nov, 2021
Nowadays, SMS verification is that the best manner that’s getting used by mobile applications for login purposes. All you would like to try and do is simply enter your mobile number, get a One-Time arcanum and eventually enter that OTP in your application and verify. However, the matter that arises here is that to own the OTP for your application, you need to look at all of your messages, and additionally at a similar time you need to input the OTP on your own. No doubt, there are sure libraries on Github that may do the automated code completion for you but here we tend to are having the SMS User Consent API, which may create our task terribly easy. In this article, we’ll learn our SMS User Consent API and see however this may be simply used for SMS verification. So, let’s get started.
SMS Client Consent API is utilized to recover the SMS by appearing a incite to the client to allow get to to the substance of a single SMS message. When the consent is allowed by the client at that point the application will examine the whole message and consequently fill the OTP or SMS confirmation code within the wanted put. Taking after is the stream of SMS Client Assent API. Here, on the off chance that the client presses the Permit button, at that point, the SMS confirmation code will be naturally filled up.
The SMS User Consent API’s operation can be broken down into three steps:
Step 1: Begin: To use the SMS User Consent API, you must first begin. However, there is one stipulation: the API must be started before delivering the message or OTP to the server.
Step 2: Prompt: When you start the API, Google Play Services will read the message and prompt your users to authorize permission to receive the message containing the OTP or verification code. The user has the option to accept or reject the request to read the message.
Step 3: Finally, if your application has the authorization to view messages, it will automatically enter the One Time Code for you via the API.
Before using the SMS User Consent API, you must meet the following requirements:
Contains One Time Code: Your message must include some sort of One Time Code.The One Time Code should be 4–10 digits long, with at least one digit being a number.Contacts: You should not get the mail containing the One Time Code from any of your contacts.Timing: For a maximum of 5 minutes, the API will seek the One Time Code.
Contains One Time Code: Your message must include some sort of One Time Code.
The One Time Code should be 4–10 digits long, with at least one digit being a number.
Contacts: You should not get the mail containing the One Time Code from any of your contacts.
Timing: For a maximum of 5 minutes, the API will seek the One Time Code.
We’ll use the SMS User Consent API by following the three steps listed above, but first, we’ll install the library in our app. Add the following lines to the app-level build.gradle file:
implementation "com.google.android.gms:play-services-auth:LATESST_VER"
implementation "com.google.android.gms:play-services-auth-api-phone:LATEST_VER"
Kotlin
private val SOME_RANDOM_REQUEST = 123private fun getHint() { val solReq = HintRequest.Builder() .setPhoneNumberIdentifierSupported(true) .build() val hinterHint = Credentials.getClient(this) val intent = credentialsClient.getHintPickerIntent(hintRequest) startIntentSenderForResult( intent.intentSender, CREDENTIAL_PICKER_REQUEST, null, 0, 0, 0}
The next step is to listen to the communications that have arrived. You can start listening for inbound messages by using the smartSmsUserConsent() method. You can pass the number of the sender who is sending the SMS verification in the method if you know it, or you can pass NULL if you don’t.
Kotlin
val someRandomTask = gfgSMSRetriver.getClient(context).startSmsUserConsent(goerNumber)
So, we’ve completed the first stage, namely, we’ve launched the SMS User Consent API, and our next task is to deliver the SMS verification code. You can utilize your verification code sender to send the One Time Code to the user’s phone number from here. So, if your SMS meets all four of the API’s Message criteria, the prompt will be displayed to the user. As a result, you’ll require a broadcast receiver that responds to SMS RECEIVED ACTION intents to handle these broadcasts.
Kotlin
// Set to an unused request codeprivate val GFG_REQUEST = 2 private val smsVerificationReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) { val extras = intent.extras val gfgRetrieverSMS = extras?.get(SmsRetriever.EXTRA_STATUS) as Status when (gfgRetrieverSMS.statusCode) { FamousgfgCodes.SUCCESS -> { val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT) try { startActivityForResult(consentIntent, GFG_REQUEST) } catch (e: ActivityNotFoundException) { } } FamousgfgCodes.TIMEOUT -> { } } } }} override fun onCreate(savedInstanceState: Bundle?) { val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) registerReceiver(smsVerificationReceiver, intentFilter)}
You can also include the option of manually entering the SMS verification code for a better user experience because if the code is received on another device, the user can manually enter the code in your app.
We learned how to use the SMS User Consent API in our Android application in this article. So, in general, there are three steps: Start, Prompt, and Read Message. Before sending the code, we first start the API, then show the user a prompt to grant permission for code reading from the message, and finally, if permission is granted, the API extracts the code from your message, which you can use.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Android Listview in Java with Example
How to Save Data to the Firebase Realtime Database in Android?
Flexbox-Layout in Android
Fragment Lifecycle in Android
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 27179,
"s": 26381,
"text": "Nowadays, SMS verification is that the best manner that’s getting used by mobile applications for login purposes. All you would like to try and do is simply enter your mobile number, get a One-Time arcanum and eventually enter that OTP in your application and verify. However, the matter that arises here is that to own the OTP for your application, you need to look at all of your messages, and additionally at a similar time you need to input the OTP on your own. No doubt, there are sure libraries on Github that may do the automated code completion for you but here we tend to are having the SMS User Consent API, which may create our task terribly easy. In this article, we’ll learn our SMS User Consent API and see however this may be simply used for SMS verification. So, let’s get started."
},
{
"code": null,
"e": 27698,
"s": 27179,
"text": "SMS Client Consent API is utilized to recover the SMS by appearing a incite to the client to allow get to to the substance of a single SMS message. When the consent is allowed by the client at that point the application will examine the whole message and consequently fill the OTP or SMS confirmation code within the wanted put. Taking after is the stream of SMS Client Assent API. Here, on the off chance that the client presses the Permit button, at that point, the SMS confirmation code will be naturally filled up."
},
{
"code": null,
"e": 27772,
"s": 27698,
"text": "The SMS User Consent API’s operation can be broken down into three steps:"
},
{
"code": null,
"e": 27953,
"s": 27772,
"text": "Step 1: Begin: To use the SMS User Consent API, you must first begin. However, there is one stipulation: the API must be started before delivering the message or OTP to the server."
},
{
"code": null,
"e": 28223,
"s": 27953,
"text": "Step 2: Prompt: When you start the API, Google Play Services will read the message and prompt your users to authorize permission to receive the message containing the OTP or verification code. The user has the option to accept or reject the request to read the message."
},
{
"code": null,
"e": 28367,
"s": 28223,
"text": "Step 3: Finally, if your application has the authorization to view messages, it will automatically enter the One Time Code for you via the API."
},
{
"code": null,
"e": 28448,
"s": 28367,
"text": "Before using the SMS User Consent API, you must meet the following requirements:"
},
{
"code": null,
"e": 28776,
"s": 28448,
"text": "Contains One Time Code: Your message must include some sort of One Time Code.The One Time Code should be 4–10 digits long, with at least one digit being a number.Contacts: You should not get the mail containing the One Time Code from any of your contacts.Timing: For a maximum of 5 minutes, the API will seek the One Time Code."
},
{
"code": null,
"e": 28854,
"s": 28776,
"text": "Contains One Time Code: Your message must include some sort of One Time Code."
},
{
"code": null,
"e": 28940,
"s": 28854,
"text": "The One Time Code should be 4–10 digits long, with at least one digit being a number."
},
{
"code": null,
"e": 29034,
"s": 28940,
"text": "Contacts: You should not get the mail containing the One Time Code from any of your contacts."
},
{
"code": null,
"e": 29107,
"s": 29034,
"text": "Timing: For a maximum of 5 minutes, the API will seek the One Time Code."
},
{
"code": null,
"e": 29294,
"s": 29107,
"text": "We’ll use the SMS User Consent API by following the three steps listed above, but first, we’ll install the library in our app. Add the following lines to the app-level build.gradle file:"
},
{
"code": null,
"e": 29445,
"s": 29294,
"text": "implementation \"com.google.android.gms:play-services-auth:LATESST_VER\"\nimplementation \"com.google.android.gms:play-services-auth-api-phone:LATEST_VER\""
},
{
"code": null,
"e": 29452,
"s": 29445,
"text": "Kotlin"
},
{
"code": "private val SOME_RANDOM_REQUEST = 123private fun getHint() { val solReq = HintRequest.Builder() .setPhoneNumberIdentifierSupported(true) .build() val hinterHint = Credentials.getClient(this) val intent = credentialsClient.getHintPickerIntent(hintRequest) startIntentSenderForResult( intent.intentSender, CREDENTIAL_PICKER_REQUEST, null, 0, 0, 0}",
"e": 29845,
"s": 29452,
"text": null
},
{
"code": null,
"e": 30140,
"s": 29845,
"text": "The next step is to listen to the communications that have arrived. You can start listening for inbound messages by using the smartSmsUserConsent() method. You can pass the number of the sender who is sending the SMS verification in the method if you know it, or you can pass NULL if you don’t."
},
{
"code": null,
"e": 30147,
"s": 30140,
"text": "Kotlin"
},
{
"code": "val someRandomTask = gfgSMSRetriver.getClient(context).startSmsUserConsent(goerNumber)",
"e": 30234,
"s": 30147,
"text": null
},
{
"code": null,
"e": 30715,
"s": 30234,
"text": "So, we’ve completed the first stage, namely, we’ve launched the SMS User Consent API, and our next task is to deliver the SMS verification code. You can utilize your verification code sender to send the One Time Code to the user’s phone number from here. So, if your SMS meets all four of the API’s Message criteria, the prompt will be displayed to the user. As a result, you’ll require a broadcast receiver that responds to SMS RECEIVED ACTION intents to handle these broadcasts."
},
{
"code": null,
"e": 30722,
"s": 30715,
"text": "Kotlin"
},
{
"code": "// Set to an unused request codeprivate val GFG_REQUEST = 2 private val smsVerificationReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) { val extras = intent.extras val gfgRetrieverSMS = extras?.get(SmsRetriever.EXTRA_STATUS) as Status when (gfgRetrieverSMS.statusCode) { FamousgfgCodes.SUCCESS -> { val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT) try { startActivityForResult(consentIntent, GFG_REQUEST) } catch (e: ActivityNotFoundException) { } } FamousgfgCodes.TIMEOUT -> { } } } }} override fun onCreate(savedInstanceState: Bundle?) { val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) registerReceiver(smsVerificationReceiver, intentFilter)}",
"e": 31763,
"s": 30722,
"text": null
},
{
"code": null,
"e": 31972,
"s": 31763,
"text": "You can also include the option of manually entering the SMS verification code for a better user experience because if the code is received on another device, the user can manually enter the code in your app."
},
{
"code": null,
"e": 32370,
"s": 31972,
"text": "We learned how to use the SMS User Consent API in our Android application in this article. So, in general, there are three steps: Start, Prompt, and Read Message. Before sending the code, we first start the API, then show the user a prompt to grant permission for code reading from the message, and finally, if permission is granted, the API extracts the code from your message, which you can use."
},
{
"code": null,
"e": 32377,
"s": 32370,
"text": "Picked"
},
{
"code": null,
"e": 32385,
"s": 32377,
"text": "Android"
},
{
"code": null,
"e": 32393,
"s": 32385,
"text": "Android"
},
{
"code": null,
"e": 32491,
"s": 32393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32529,
"s": 32491,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32568,
"s": 32529,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32618,
"s": 32568,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32669,
"s": 32618,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32711,
"s": 32669,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32751,
"s": 32711,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 32789,
"s": 32751,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32852,
"s": 32789,
"text": "How to Save Data to the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 32878,
"s": 32852,
"text": "Flexbox-Layout in Android"
}
] |
Todo list app using Flask | Python - GeeksforGeeks
|
15 May, 2020
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to write applications without writing the low-level codes such as protocols, thread management, etc.
In this article, we will learn how to make a todo list app using the Flask framework. In this app, you can add your todo items and mark them as complete or incomplete.
Installation:
pip install Flask
Basic setup :Step 1: First make basic folders
mkdir app && cd app && mkdir static && mkdir templates
Step 2: Make some basic python files to write the code and name it as you desire.
Step 3: Run the below command to start the server
touch run.py the app
Step 4: Change directory to app–
cd app
Step 5: create models.py for database, routes.py for urls/views and __init__ file to package our app
touch models.py routes.py __init__.py
Step 6: Goto templates/ directory and create index.html file
cd templates && touch index.html
Step 7: Goto static/ directory and create main.css
cd static && touch main.css
Now, open the project folder using a text editor. The directory structure should look like this :
run.py file
from app import app if __name__ == '__main__': app.run(debug=True)
app/__init__.py file
from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyimport os file_path = os.path.abspath(os.getcwd())+"/todo.db" app = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+file_pathdb = SQLAlchemy(app) from app import routes
app/routes.py file
from flask import render_template, request, redirect, url_forfrom app import appfrom app.models import Todofrom app import db @app.route('/')def index(): incomplete = Todo.query.filter_by(complete=False).all() complete = Todo.query.filter_by(complete=True).all() return render_template('index.html', incomplete=incomplete, complete=complete) @app.route('/add', methods=['POST'])def add(): todo = Todo(text=request.form['todoitem'], complete=False) db.session.add(todo) db.session.commit() return redirect(url_for('index')) @app.route('/complete/<id>')def complete(id): todo = Todo.query.filter_by(id=int(id)).first() todo.complete = True db.session.commit() return redirect(url_for('index'))
app/models.py file
from app import db class Todo(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(200)) complete = db.Column(db.Boolean) def __repr__(self): return self.text
app/main.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Todo App</title> <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='main.css')}}"> </head> <body> <h1>Todo List</h1> <div>Add a new todo item: <form action="{{ url_for('add') }}" method="POST"> <input type="text" name="todoitem"> <input type="submit" value="Add Item" class="button"> </form> </div> <div> <h2>Incomplete Items</h2> <ul> {% for todo in incomplete %} <li style="font-size: 30pt" class='mark'>{{ todo.text }} <a href="{{ url_for('complete', id=todo.id) }}">Mark As Complete</a></li> {% endfor %} </ul> <h2>Completed Items</h2> <ul> {% for todo in complete %} <li style="font-size: 30pt">{{ todo.text }}</li> {% endfor %} </ul> </div> </body> </html>
app/main.css
body{ background:black; color:red; margin-top: 5px; } .button{ color:green; } .mark{font-size: 10px;}
Run the todo app using the below command
python run.py
itsvinayak
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 25975,
"s": 25581,
"text": "There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to write applications without writing the low-level codes such as protocols, thread management, etc."
},
{
"code": null,
"e": 26143,
"s": 25975,
"text": "In this article, we will learn how to make a todo list app using the Flask framework. In this app, you can add your todo items and mark them as complete or incomplete."
},
{
"code": null,
"e": 26157,
"s": 26143,
"text": "Installation:"
},
{
"code": null,
"e": 26176,
"s": 26157,
"text": " pip install Flask"
},
{
"code": null,
"e": 26222,
"s": 26176,
"text": "Basic setup :Step 1: First make basic folders"
},
{
"code": null,
"e": 26277,
"s": 26222,
"text": "mkdir app && cd app && mkdir static && mkdir templates"
},
{
"code": null,
"e": 26359,
"s": 26277,
"text": "Step 2: Make some basic python files to write the code and name it as you desire."
},
{
"code": null,
"e": 26409,
"s": 26359,
"text": "Step 3: Run the below command to start the server"
},
{
"code": null,
"e": 26430,
"s": 26409,
"text": "touch run.py the app"
},
{
"code": null,
"e": 26463,
"s": 26430,
"text": "Step 4: Change directory to app–"
},
{
"code": null,
"e": 26471,
"s": 26463,
"text": " cd app"
},
{
"code": null,
"e": 26572,
"s": 26471,
"text": "Step 5: create models.py for database, routes.py for urls/views and __init__ file to package our app"
},
{
"code": null,
"e": 26612,
"s": 26572,
"text": " touch models.py routes.py __init__.py "
},
{
"code": null,
"e": 26673,
"s": 26612,
"text": "Step 6: Goto templates/ directory and create index.html file"
},
{
"code": null,
"e": 26708,
"s": 26673,
"text": " cd templates && touch index.html "
},
{
"code": null,
"e": 26759,
"s": 26708,
"text": "Step 7: Goto static/ directory and create main.css"
},
{
"code": null,
"e": 26788,
"s": 26759,
"text": " cd static && touch main.css"
},
{
"code": null,
"e": 26886,
"s": 26788,
"text": "Now, open the project folder using a text editor. The directory structure should look like this :"
},
{
"code": null,
"e": 26898,
"s": 26886,
"text": "run.py file"
},
{
"code": "from app import app if __name__ == '__main__': app.run(debug=True)",
"e": 26969,
"s": 26898,
"text": null
},
{
"code": null,
"e": 26990,
"s": 26969,
"text": "app/__init__.py file"
},
{
"code": "from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyimport os file_path = os.path.abspath(os.getcwd())+\"/todo.db\" app = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+file_pathdb = SQLAlchemy(app) from app import routes",
"e": 27246,
"s": 26990,
"text": null
},
{
"code": null,
"e": 27265,
"s": 27246,
"text": "app/routes.py file"
},
{
"code": "from flask import render_template, request, redirect, url_forfrom app import appfrom app.models import Todofrom app import db @app.route('/')def index(): incomplete = Todo.query.filter_by(complete=False).all() complete = Todo.query.filter_by(complete=True).all() return render_template('index.html', incomplete=incomplete, complete=complete) @app.route('/add', methods=['POST'])def add(): todo = Todo(text=request.form['todoitem'], complete=False) db.session.add(todo) db.session.commit() return redirect(url_for('index')) @app.route('/complete/<id>')def complete(id): todo = Todo.query.filter_by(id=int(id)).first() todo.complete = True db.session.commit() return redirect(url_for('index'))",
"e": 28007,
"s": 27265,
"text": null
},
{
"code": null,
"e": 28026,
"s": 28007,
"text": "app/models.py file"
},
{
"code": "from app import db class Todo(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(200)) complete = db.Column(db.Boolean) def __repr__(self): return self.text",
"e": 28237,
"s": 28026,
"text": null
},
{
"code": null,
"e": 28251,
"s": 28237,
"text": "app/main.html"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Todo App</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{url_for('static', filename='main.css')}}\"> </head> <body> <h1>Todo List</h1> <div>Add a new todo item: <form action=\"{{ url_for('add') }}\" method=\"POST\"> <input type=\"text\" name=\"todoitem\"> <input type=\"submit\" value=\"Add Item\" class=\"button\"> </form> </div> <div> <h2>Incomplete Items</h2> <ul> {% for todo in incomplete %} <li style=\"font-size: 30pt\" class='mark'>{{ todo.text }} <a href=\"{{ url_for('complete', id=todo.id) }}\">Mark As Complete</a></li> {% endfor %} </ul> <h2>Completed Items</h2> <ul> {% for todo in complete %} <li style=\"font-size: 30pt\">{{ todo.text }}</li> {% endfor %} </ul> </div> </body> </html> ",
"e": 29207,
"s": 28251,
"text": null
},
{
"code": null,
"e": 29220,
"s": 29207,
"text": "app/main.css"
},
{
"code": "body{ background:black; color:red; margin-top: 5px; } .button{ color:green; } .mark{font-size: 10px;} ",
"e": 29339,
"s": 29220,
"text": null
},
{
"code": null,
"e": 29380,
"s": 29339,
"text": "Run the todo app using the below command"
},
{
"code": null,
"e": 29394,
"s": 29380,
"text": "python run.py"
},
{
"code": null,
"e": 29405,
"s": 29394,
"text": "itsvinayak"
},
{
"code": null,
"e": 29412,
"s": 29405,
"text": "Python"
},
{
"code": null,
"e": 29510,
"s": 29412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29542,
"s": 29510,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29584,
"s": 29542,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29626,
"s": 29584,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29682,
"s": 29626,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29709,
"s": 29682,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29740,
"s": 29709,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29779,
"s": 29740,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29808,
"s": 29779,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29830,
"s": 29808,
"text": "Defaultdict in Python"
}
] |
Pulling a random word or string from a line in a text file in Python - GeeksforGeeks
|
11 Dec, 2020
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python’s random module to pick a random word.
There are various ways to perform this operation:
This is the text file we will read from:
Method 1: Using random.choice()
Steps:
Using with function, open the file in read mode. The with function takes care of closing the file automatically.Read all the text from the file and store in a stringSplit the string into words separated by space.Use random.choice() to pick a word or string.
Using with function, open the file in read mode. The with function takes care of closing the file automatically.
Read all the text from the file and store in a string
Split the string into words separated by space.
Use random.choice() to pick a word or string.
Python
# Python code to pick a random# word from a text fileimport random # Open the file in read modewith open("MyFile.txt", "r") as file: allText = file.read() words = list(map(str, allText.split())) # print random string print(random.choice(words))
Note: The split() function, by default, splits by white space. If you want any other delimiter like newline character you can specify that as an argument.
Output:
Output for two sample runs
The above can be achieved with just a single line of code like this :
Python
# import required moduleimport random # print random wordprint(random.choice(open("myFile.txt","r").readline().split()))
Method 2: Using random.randint()
Steps:
Open the file in read mode using with functionStore all data from the file in a string and split the string into words.Count the total number of words.Use random.randint() to generate a random number between 0 and the word_count.Print the word at that position.
Open the file in read mode using with function
Store all data from the file in a string and split the string into words.
Count the total number of words.
Use random.randint() to generate a random number between 0 and the word_count.
Print the word at that position.
Python
# using randint()import random # open filewith open("myFile.txt", "r") as file: data = file.read() words = data.split() # Generating a random number for word position word_pos = random.randint(0, len(words)-1) print("Position:", word_pos) print("Word at position:", words[word_pos])
Output:
Output for two sample runs
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25481,
"s": 25453,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 25720,
"s": 25481,
"text": "File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python’s random module to pick a random word. "
},
{
"code": null,
"e": 25770,
"s": 25720,
"text": "There are various ways to perform this operation:"
},
{
"code": null,
"e": 25811,
"s": 25770,
"text": "This is the text file we will read from:"
},
{
"code": null,
"e": 25843,
"s": 25811,
"text": "Method 1: Using random.choice()"
},
{
"code": null,
"e": 25850,
"s": 25843,
"text": "Steps:"
},
{
"code": null,
"e": 26108,
"s": 25850,
"text": "Using with function, open the file in read mode. The with function takes care of closing the file automatically.Read all the text from the file and store in a stringSplit the string into words separated by space.Use random.choice() to pick a word or string."
},
{
"code": null,
"e": 26221,
"s": 26108,
"text": "Using with function, open the file in read mode. The with function takes care of closing the file automatically."
},
{
"code": null,
"e": 26275,
"s": 26221,
"text": "Read all the text from the file and store in a string"
},
{
"code": null,
"e": 26323,
"s": 26275,
"text": "Split the string into words separated by space."
},
{
"code": null,
"e": 26369,
"s": 26323,
"text": "Use random.choice() to pick a word or string."
},
{
"code": null,
"e": 26376,
"s": 26369,
"text": "Python"
},
{
"code": "# Python code to pick a random# word from a text fileimport random # Open the file in read modewith open(\"MyFile.txt\", \"r\") as file: allText = file.read() words = list(map(str, allText.split())) # print random string print(random.choice(words))",
"e": 26636,
"s": 26376,
"text": null
},
{
"code": null,
"e": 26791,
"s": 26636,
"text": "Note: The split() function, by default, splits by white space. If you want any other delimiter like newline character you can specify that as an argument."
},
{
"code": null,
"e": 26799,
"s": 26791,
"text": "Output:"
},
{
"code": null,
"e": 26826,
"s": 26799,
"text": "Output for two sample runs"
},
{
"code": null,
"e": 26897,
"s": 26826,
"text": "The above can be achieved with just a single line of code like this : "
},
{
"code": null,
"e": 26904,
"s": 26897,
"text": "Python"
},
{
"code": "# import required moduleimport random # print random wordprint(random.choice(open(\"myFile.txt\",\"r\").readline().split()))",
"e": 27026,
"s": 26904,
"text": null
},
{
"code": null,
"e": 27060,
"s": 27026,
"text": "Method 2: Using random.randint() "
},
{
"code": null,
"e": 27067,
"s": 27060,
"text": "Steps:"
},
{
"code": null,
"e": 27329,
"s": 27067,
"text": "Open the file in read mode using with functionStore all data from the file in a string and split the string into words.Count the total number of words.Use random.randint() to generate a random number between 0 and the word_count.Print the word at that position."
},
{
"code": null,
"e": 27376,
"s": 27329,
"text": "Open the file in read mode using with function"
},
{
"code": null,
"e": 27450,
"s": 27376,
"text": "Store all data from the file in a string and split the string into words."
},
{
"code": null,
"e": 27483,
"s": 27450,
"text": "Count the total number of words."
},
{
"code": null,
"e": 27562,
"s": 27483,
"text": "Use random.randint() to generate a random number between 0 and the word_count."
},
{
"code": null,
"e": 27595,
"s": 27562,
"text": "Print the word at that position."
},
{
"code": null,
"e": 27602,
"s": 27595,
"text": "Python"
},
{
"code": "# using randint()import random # open filewith open(\"myFile.txt\", \"r\") as file: data = file.read() words = data.split() # Generating a random number for word position word_pos = random.randint(0, len(words)-1) print(\"Position:\", word_pos) print(\"Word at position:\", words[word_pos])",
"e": 27910,
"s": 27602,
"text": null
},
{
"code": null,
"e": 27918,
"s": 27910,
"text": "Output:"
},
{
"code": null,
"e": 27945,
"s": 27918,
"text": "Output for two sample runs"
},
{
"code": null,
"e": 27975,
"s": 27945,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 27996,
"s": 27975,
"text": "python-file-handling"
},
{
"code": null,
"e": 28020,
"s": 27996,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28027,
"s": 28020,
"text": "Python"
},
{
"code": null,
"e": 28046,
"s": 28027,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28144,
"s": 28046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28162,
"s": 28144,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28197,
"s": 28162,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28229,
"s": 28197,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28251,
"s": 28229,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28293,
"s": 28251,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28323,
"s": 28293,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28349,
"s": 28323,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28378,
"s": 28349,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28422,
"s": 28378,
"text": "Reading and Writing to text files in Python"
}
] |
How to Sort a Slice of Strings in Golang? - GeeksforGeeks
|
26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort the elements of the slice according to its type. So, a string type slice is sorted by using the following functions. These functions are defined under the sort package so, you have to import sort package in your program for accessing these functions:
1. Strings: This function is used to only sorts a slice of strings and it sorts the elements of the slice in increasing order.
Syntax:
func Strings(scl []string)
Here, slc represent a slice of strings. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how// to sort the slice of stringspackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []string{"abc", "rwp", "def", "por", "ber", "erj"} scl2 := []string{"Rabbit", "Fish", "Dog", "Parrot", "Cat", "Hamster"} // Displaying slices fmt.Println("Slices(Before):") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) // Sorting the slice of strings // Using Strings function sort.Strings(scl1) sort.Strings(scl2) // Displaying the result fmt.Println("\nSlices(After):") fmt.Println("Slice 1 : ", scl1) fmt.Println("Slice 2 : ", scl2)}
Output:
Slices(Before):
Slice 1: [abc rwp def por ber erj]
Slice 2: [Rabbit Fish Dog Parrot Cat Hamster]
Slices(After):
Slice 1 : [abc ber def erj por rwp]
Slice 2 : [Cat Dog Fish Hamster Parrot Rabbit]
2. StringsAreSorted: This function is used to check whether the given slice of strings is in sorted form(in increasing order) or not. This method returns true if the slice is in sorted form, or return false if the slice is not in the sorted form.
Syntax:
func StringsAreSorted(scl []string) bool
Here, scl represents a slice of strings. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to check// whether the given slice of strings// is in sorted form or notpackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []string{"abc", "ber", "def", "erj", "por", "rwp"} scl2 := []string{"Rabbit", "Fish", "Dog", "Parrot", "Cat", "Hamster"} // Displaying slices fmt.Println("Slices:") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) // Checking the slice is in sorted form or not // Using StringsAreSorted function res1 := sort.StringsAreSorted(scl1) res2 := sort.StringsAreSorted(scl2) // Displaying the result fmt.Println("\nResult:") fmt.Println("Is Slice 1 is sorted?: ", res1) fmt.Println("Is Slice 2 is sorted?: ", res2)}
Output:
Slices:
Slice 1: [abc ber def erj por rwp]
Slice 2: [Rabbit Fish Dog Parrot Cat Hamster]
Result:
Is Slice 1 is sorted?: true
Is Slice 2 is sorted?: false
Golang
Golang-Slices
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
|
[
{
"code": null,
"e": 25671,
"s": 25643,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 26221,
"s": 25671,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort the elements of the slice according to its type. So, a string type slice is sorted by using the following functions. These functions are defined under the sort package so, you have to import sort package in your program for accessing these functions:"
},
{
"code": null,
"e": 26348,
"s": 26221,
"text": "1. Strings: This function is used to only sorts a slice of strings and it sorts the elements of the slice in increasing order."
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Syntax:"
},
{
"code": null,
"e": 26383,
"s": 26356,
"text": "func Strings(scl []string)"
},
{
"code": null,
"e": 26480,
"s": 26383,
"text": "Here, slc represent a slice of strings. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 26489,
"s": 26480,
"text": "Example:"
},
{
"code": "// Go program to illustrate how// to sort the slice of stringspackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []string{\"abc\", \"rwp\", \"def\", \"por\", \"ber\", \"erj\"} scl2 := []string{\"Rabbit\", \"Fish\", \"Dog\", \"Parrot\", \"Cat\", \"Hamster\"} // Displaying slices fmt.Println(\"Slices(Before):\") fmt.Println(\"Slice 1: \", scl1) fmt.Println(\"Slice 2: \", scl2) // Sorting the slice of strings // Using Strings function sort.Strings(scl1) sort.Strings(scl2) // Displaying the result fmt.Println(\"\\nSlices(After):\") fmt.Println(\"Slice 1 : \", scl1) fmt.Println(\"Slice 2 : \", scl2)}",
"e": 27222,
"s": 26489,
"text": null
},
{
"code": null,
"e": 27230,
"s": 27222,
"text": "Output:"
},
{
"code": null,
"e": 27431,
"s": 27230,
"text": "Slices(Before):\nSlice 1: [abc rwp def por ber erj]\nSlice 2: [Rabbit Fish Dog Parrot Cat Hamster]\n\nSlices(After):\nSlice 1 : [abc ber def erj por rwp]\nSlice 2 : [Cat Dog Fish Hamster Parrot Rabbit]\n"
},
{
"code": null,
"e": 27678,
"s": 27431,
"text": "2. StringsAreSorted: This function is used to check whether the given slice of strings is in sorted form(in increasing order) or not. This method returns true if the slice is in sorted form, or return false if the slice is not in the sorted form."
},
{
"code": null,
"e": 27686,
"s": 27678,
"text": "Syntax:"
},
{
"code": null,
"e": 27727,
"s": 27686,
"text": "func StringsAreSorted(scl []string) bool"
},
{
"code": null,
"e": 27825,
"s": 27727,
"text": "Here, scl represents a slice of strings. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 27834,
"s": 27825,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to check// whether the given slice of strings// is in sorted form or notpackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and initializing slices // Using shorthand declaration scl1 := []string{\"abc\", \"ber\", \"def\", \"erj\", \"por\", \"rwp\"} scl2 := []string{\"Rabbit\", \"Fish\", \"Dog\", \"Parrot\", \"Cat\", \"Hamster\"} // Displaying slices fmt.Println(\"Slices:\") fmt.Println(\"Slice 1: \", scl1) fmt.Println(\"Slice 2: \", scl2) // Checking the slice is in sorted form or not // Using StringsAreSorted function res1 := sort.StringsAreSorted(scl1) res2 := sort.StringsAreSorted(scl2) // Displaying the result fmt.Println(\"\\nResult:\") fmt.Println(\"Is Slice 1 is sorted?: \", res1) fmt.Println(\"Is Slice 2 is sorted?: \", res2)}",
"e": 28682,
"s": 27834,
"text": null
},
{
"code": null,
"e": 28690,
"s": 28682,
"text": "Output:"
},
{
"code": null,
"e": 28850,
"s": 28690,
"text": "Slices:\nSlice 1: [abc ber def erj por rwp]\nSlice 2: [Rabbit Fish Dog Parrot Cat Hamster]\n\nResult:\nIs Slice 1 is sorted?: true\nIs Slice 2 is sorted?: false\n"
},
{
"code": null,
"e": 28857,
"s": 28850,
"text": "Golang"
},
{
"code": null,
"e": 28871,
"s": 28857,
"text": "Golang-Slices"
},
{
"code": null,
"e": 28885,
"s": 28871,
"text": "Golang-String"
},
{
"code": null,
"e": 28897,
"s": 28885,
"text": "Go Language"
},
{
"code": null,
"e": 28995,
"s": 28897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29041,
"s": 28995,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 29054,
"s": 29041,
"text": "Arrays in Go"
},
{
"code": null,
"e": 29087,
"s": 29054,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 29104,
"s": 29087,
"text": "Slices in Golang"
},
{
"code": null,
"e": 29116,
"s": 29104,
"text": "Golang Maps"
},
{
"code": null,
"e": 29138,
"s": 29116,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 29192,
"s": 29138,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 29213,
"s": 29192,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 29245,
"s": 29213,
"text": "How to Trim a String in Golang?"
}
] |
Python program to print current year, month and day - GeeksforGeeks
|
29 Dec, 2020
In this article, the task is to write a Python Program to print the current year, month, and day.
Approach:
In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date class
Create an object of the date class
Call the today( ) function of date class to fetch todays date.
By using the object created, we can print the year, month, day(attribute of date class) of today.
Python3
# importing date class from datetime modulefrom datetime import date # creating the date object of today's datetodays_date = date.today() # printing todays dateprint("Current date: ", todays_date) # fetching the current year, month and day of todayprint("Current year:", todays_date.year)print("Current month:", todays_date.month)print("Current day:", todays_date.day)
Output:
Current date: 2020-12-10
Current year: 2020
Current month: 12
Current day: 10
Python datetime-program
Python-datetime
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 26158,
"s": 26130,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 26256,
"s": 26158,
"text": "In this article, the task is to write a Python Program to print the current year, month, and day."
},
{
"code": null,
"e": 26266,
"s": 26256,
"text": "Approach:"
},
{
"code": null,
"e": 26426,
"s": 26266,
"text": "In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date class"
},
{
"code": null,
"e": 26461,
"s": 26426,
"text": "Create an object of the date class"
},
{
"code": null,
"e": 26524,
"s": 26461,
"text": "Call the today( ) function of date class to fetch todays date."
},
{
"code": null,
"e": 26622,
"s": 26524,
"text": "By using the object created, we can print the year, month, day(attribute of date class) of today."
},
{
"code": null,
"e": 26630,
"s": 26622,
"text": "Python3"
},
{
"code": "# importing date class from datetime modulefrom datetime import date # creating the date object of today's datetodays_date = date.today() # printing todays dateprint(\"Current date: \", todays_date) # fetching the current year, month and day of todayprint(\"Current year:\", todays_date.year)print(\"Current month:\", todays_date.month)print(\"Current day:\", todays_date.day)",
"e": 27002,
"s": 26630,
"text": null
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Output:"
},
{
"code": null,
"e": 27089,
"s": 27010,
"text": "Current date: 2020-12-10\nCurrent year: 2020\nCurrent month: 12\nCurrent day: 10"
},
{
"code": null,
"e": 27113,
"s": 27089,
"text": "Python datetime-program"
},
{
"code": null,
"e": 27129,
"s": 27113,
"text": "Python-datetime"
},
{
"code": null,
"e": 27153,
"s": 27129,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27160,
"s": 27153,
"text": "Python"
},
{
"code": null,
"e": 27176,
"s": 27160,
"text": "Python Programs"
},
{
"code": null,
"e": 27195,
"s": 27176,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27293,
"s": 27195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27311,
"s": 27293,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27343,
"s": 27311,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27365,
"s": 27343,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27407,
"s": 27365,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27433,
"s": 27407,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27455,
"s": 27433,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27494,
"s": 27455,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27540,
"s": 27494,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27578,
"s": 27540,
"text": "Python | Convert a list to dictionary"
}
] |
Check whether a given point lies inside a rectangle or not - GeeksforGeeks
|
07 Nov, 2021
Given four points of a rectangle, and one more point P. Write a function to check whether P lies within the given rectangle or not.Examples:
Input : R = [(10, 10), (10, -10),
(-10, -10), (-10, 10)]
P = (0, 0)
Output : yes
Illustration :
Input : R = [(10, 10), (10, -10),
(-10, -10), (-10, 10)],
P = (20, 20)
Output : no
Illustration :
Prerequisite: Check whether a given point lies inside a triangle or notApproach : Let the coordinates of four corners be A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4). And coordinates of the given point P be (x, y)1) Calculate area of the given rectangle, i.e., area of the rectangle ABCD as area of triangle ABC + area of triangle ACD. Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2 + [ x1(y4 – y3) + x4(y3 – y1) + x3(y1-y4)]/2 2) Calculate area of the triangle PAB as A1. 3) Calculate area of the triangle PBC as A2. 4) Calculate area of the triangle PCD as A3. 5) Calculate area of the triangle PAD as A4. 6) If P lies inside the triangle, then A1 + A2 + A3 + A4 must be equal to A.
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */float area(int x1, int y1, int x2, int y2, int x3, int y3){ return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);} /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */bool check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y){ /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4);} /* Driver program to test above function */int main(){ /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) cout << "yes"; else cout << "no"; return 0;}
class GFG{ /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */ static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */ static boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3)+ area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4); } // Driver code public static void main (String[] args) { /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) System.out.print("yes"); else System.out.print("no"); }} // This code is contributed by Anant Agarwal.
# A utility function to calculate # area of triangle formed by (x1, y1), # (x2, y2) and (x3, y3) def area(x1, y1, x2, y2, x3, y3): return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0) # A function to check whether point # P(x, y) lies inside the rectangle # formed by A(x1, y1), B(x2, y2), # C(x3, y3) and D(x4, y4) def check(x1, y1, x2, y2, x3, y3, x4, y4, x, y): # Calculate area of rectangle ABCD A = (area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3)) # Calculate area of triangle PAB A1 = area(x, y, x1, y1, x2, y2) # Calculate area of triangle PBC A2 = area(x, y, x2, y2, x3, y3) # Calculate area of triangle PCD A3 = area(x, y, x3, y3, x4, y4) # Calculate area of triangle PAD A4 = area(x, y, x1, y1, x4, y4); # Check if sum of A1, A2, A3 # and A4 is same as A return (A == A1 + A2 + A3 + A4) # Driver Codeif __name__ == '__main__': # Let us check whether the point # P(10, 15) lies inside the # rectangle formed by A(0, 10), # B(10, 0) C(0, -10) D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)): print("yes") else: print("no") # This code is contributed by# Surendra_Gangwar
// C# program to Check whether a given // point lies inside a rectangle or notusing System; class GFG { // A utility function to calculate area // of triangle formed by (x1, y1), // (x2, y2) and (x3, y3) static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.Abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } // A function to check whether point P(x, y) // lies inside the rectangle formed by A(x1, y1), // B(x2, y2), C(x3, y3) and D(x4, y4) static bool check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { // Calculate area of rectangle ABCD float A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); // Calculate area of triangle PAB float A1 = area(x, y, x1, y1, x2, y2); // Calculate area of triangle PBC float A2 = area(x, y, x2, y2, x3, y3); // Calculate area of triangle PCD float A3 = area(x, y, x3, y3, x4, y4); // Calculate area of triangle PAD float A4 = area(x, y, x1, y1, x4, y4); // Check if sum of A1, A2, A3 // and A4is same as A return (A == A1 + A2 + A3 + A4); } // Driver code public static void Main () { // Let us check whether the point // P(10, 15) lies inside the rectangle // formed by A(0, 10), B(10, 0), // C(0, -10), D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) Console.Write("yes"); else Console.Write("no"); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to check whether a // given point lies inside a // rectangle or not // A utility function to // calculate area of // triangle formed by // (x1, y1), (x2, y2) // and (x3, y3)function area($x1, $y1, $x2, $y2, $x3, $y3){ return abs(($x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2)) / 2.0);} /* A function to check whether point P(x, y) lies inside the rectangleformed by A(x1, y1), B(x2, y2), C(x3, y3)and D(x4, y4) */function check($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4, $x, $y){ // Calculate area of rectangle ABCD $A = area($x1, $y1, $x2, $y2, $x3, $y3) + area($x1, $y1, $x4, $y4, $x3, $y3); // Calculate area of triangle PAB $A1 = area($x, $y, $x1, $y1, $x2, $y2); // Calculate area of triangle PBC $A2 = area($x, $y, $x2, $y2, $x3, $y3); // Calculate area of triangle PCD $A3 = area($x, $y, $x3, $y3, $x4, $y4); // Calculate area of triangle PAD $A4 = area($x, $y, $x1, $y1, $x4, $y4); // Check if sum of A1, A2, // A3 and A4 is same as A return ($A == $A1 + $A2 + $A3 + $A4);} // Driver Code // Let us check whether // the point P(10, 15)// lies inside the rectangle// formed by A(0, 10),// B(10, 0) C(0, -10) // D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) echo "yes"; else echo "no"; // This code is contributed by vt_m.?>
<script> /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */function area(x1, y1, x2, y2, x3, y3) { return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */function check(x1, y1, x2, y2, x3, y3, x4, y4, x, y) { /* Calculate area of rectangle ABCD */ let A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ let A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ let A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ let A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ let A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4); } /* Driver program to test above function */ /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) document.write("yes"); else document.write("no"); // This code is contributed by Mayank Tyagi </script>
Output:
no
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
SURENDRA_GANGWAR
mayanktyagi1709
square-rectangle
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Optimum location of point to minimize total distance
Closest Pair of Points | O(nlogn) Implementation
Polygon Clipping | Sutherland–Hodgman Algorithm
Given n line segments, find if any two segments intersect
Program for Point of Intersection of Two Lines
Program to find area of a triangle
Window to Viewport Transformation in Computer Graphics with Implementation
Find K Closest Points to the Origin
|
[
{
"code": null,
"e": 26203,
"s": 26175,
"text": "\n07 Nov, 2021"
},
{
"code": null,
"e": 26346,
"s": 26203,
"text": "Given four points of a rectangle, and one more point P. Write a function to check whether P lies within the given rectangle or not.Examples: "
},
{
"code": null,
"e": 26465,
"s": 26346,
"text": "Input : R = [(10, 10), (10, -10), \n (-10, -10), (-10, 10)]\n P = (0, 0)\nOutput : yes\nIllustration : "
},
{
"code": null,
"e": 26586,
"s": 26465,
"text": "Input : R = [(10, 10), (10, -10),\n (-10, -10), (-10, 10)],\n P = (20, 20)\nOutput : no\nIllustration :\n "
},
{
"code": null,
"e": 27280,
"s": 26588,
"text": "Prerequisite: Check whether a given point lies inside a triangle or notApproach : Let the coordinates of four corners be A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4). And coordinates of the given point P be (x, y)1) Calculate area of the given rectangle, i.e., area of the rectangle ABCD as area of triangle ABC + area of triangle ACD. Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2 + [ x1(y4 – y3) + x4(y3 – y1) + x3(y1-y4)]/2 2) Calculate area of the triangle PAB as A1. 3) Calculate area of the triangle PBC as A2. 4) Calculate area of the triangle PCD as A3. 5) Calculate area of the triangle PAD as A4. 6) If P lies inside the triangle, then A1 + A2 + A3 + A4 must be equal to A. "
},
{
"code": null,
"e": 27286,
"s": 27282,
"text": "C++"
},
{
"code": null,
"e": 27291,
"s": 27286,
"text": "Java"
},
{
"code": null,
"e": 27299,
"s": 27291,
"text": "Python3"
},
{
"code": null,
"e": 27302,
"s": 27299,
"text": "C#"
},
{
"code": null,
"e": 27306,
"s": 27302,
"text": "PHP"
},
{
"code": null,
"e": 27317,
"s": 27306,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */float area(int x1, int y1, int x2, int y2, int x3, int y3){ return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);} /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */bool check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y){ /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4);} /* Driver program to test above function */int main(){ /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) cout << \"yes\"; else cout << \"no\"; return 0;}",
"e": 28755,
"s": 27317,
"text": null
},
{
"code": "class GFG{ /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */ static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */ static boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3)+ area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4); } // Driver code public static void main (String[] args) { /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) System.out.print(\"yes\"); else System.out.print(\"no\"); }} // This code is contributed by Anant Agarwal.",
"e": 30403,
"s": 28755,
"text": null
},
{
"code": "# A utility function to calculate # area of triangle formed by (x1, y1), # (x2, y2) and (x3, y3) def area(x1, y1, x2, y2, x3, y3): return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0) # A function to check whether point # P(x, y) lies inside the rectangle # formed by A(x1, y1), B(x2, y2), # C(x3, y3) and D(x4, y4) def check(x1, y1, x2, y2, x3, y3, x4, y4, x, y): # Calculate area of rectangle ABCD A = (area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3)) # Calculate area of triangle PAB A1 = area(x, y, x1, y1, x2, y2) # Calculate area of triangle PBC A2 = area(x, y, x2, y2, x3, y3) # Calculate area of triangle PCD A3 = area(x, y, x3, y3, x4, y4) # Calculate area of triangle PAD A4 = area(x, y, x1, y1, x4, y4); # Check if sum of A1, A2, A3 # and A4 is same as A return (A == A1 + A2 + A3 + A4) # Driver Codeif __name__ == '__main__': # Let us check whether the point # P(10, 15) lies inside the # rectangle formed by A(0, 10), # B(10, 0) C(0, -10) D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)): print(\"yes\") else: print(\"no\") # This code is contributed by# Surendra_Gangwar",
"e": 31717,
"s": 30403,
"text": null
},
{
"code": "// C# program to Check whether a given // point lies inside a rectangle or notusing System; class GFG { // A utility function to calculate area // of triangle formed by (x1, y1), // (x2, y2) and (x3, y3) static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.Abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } // A function to check whether point P(x, y) // lies inside the rectangle formed by A(x1, y1), // B(x2, y2), C(x3, y3) and D(x4, y4) static bool check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { // Calculate area of rectangle ABCD float A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); // Calculate area of triangle PAB float A1 = area(x, y, x1, y1, x2, y2); // Calculate area of triangle PBC float A2 = area(x, y, x2, y2, x3, y3); // Calculate area of triangle PCD float A3 = area(x, y, x3, y3, x4, y4); // Calculate area of triangle PAD float A4 = area(x, y, x1, y1, x4, y4); // Check if sum of A1, A2, A3 // and A4is same as A return (A == A1 + A2 + A3 + A4); } // Driver code public static void Main () { // Let us check whether the point // P(10, 15) lies inside the rectangle // formed by A(0, 10), B(10, 0), // C(0, -10), D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) Console.Write(\"yes\"); else Console.Write(\"no\"); }} // This code is contributed by Nitin Mittal.",
"e": 33550,
"s": 31717,
"text": null
},
{
"code": "<?php// PHP program to check whether a // given point lies inside a // rectangle or not // A utility function to // calculate area of // triangle formed by // (x1, y1), (x2, y2) // and (x3, y3)function area($x1, $y1, $x2, $y2, $x3, $y3){ return abs(($x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2)) / 2.0);} /* A function to check whether point P(x, y) lies inside the rectangleformed by A(x1, y1), B(x2, y2), C(x3, y3)and D(x4, y4) */function check($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4, $x, $y){ // Calculate area of rectangle ABCD $A = area($x1, $y1, $x2, $y2, $x3, $y3) + area($x1, $y1, $x4, $y4, $x3, $y3); // Calculate area of triangle PAB $A1 = area($x, $y, $x1, $y1, $x2, $y2); // Calculate area of triangle PBC $A2 = area($x, $y, $x2, $y2, $x3, $y3); // Calculate area of triangle PCD $A3 = area($x, $y, $x3, $y3, $x4, $y4); // Calculate area of triangle PAD $A4 = area($x, $y, $x1, $y1, $x4, $y4); // Check if sum of A1, A2, // A3 and A4 is same as A return ($A == $A1 + $A2 + $A3 + $A4);} // Driver Code // Let us check whether // the point P(10, 15)// lies inside the rectangle// formed by A(0, 10),// B(10, 0) C(0, -10) // D(-10, 0) if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) echo \"yes\"; else echo \"no\"; // This code is contributed by vt_m.?>",
"e": 34986,
"s": 33550,
"text": null
},
{
"code": "<script> /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */function area(x1, y1, x2, y2, x3, y3) { return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */function check(x1, y1, x2, y2, x3, y3, x4, y4, x, y) { /* Calculate area of rectangle ABCD */ let A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ let A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ let A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ let A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ let A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4); } /* Driver program to test above function */ /* Let us check whether the point P(10, 15) lies inside the rectangle formed by A(0, 10), B(10, 0) C(0, -10) D(-10, 0) */ if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)) document.write(\"yes\"); else document.write(\"no\"); // This code is contributed by Mayank Tyagi </script>",
"e": 36383,
"s": 34986,
"text": null
},
{
"code": null,
"e": 36392,
"s": 36383,
"text": "Output: "
},
{
"code": null,
"e": 36395,
"s": 36392,
"text": "no"
},
{
"code": null,
"e": 36831,
"s": 36395,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36844,
"s": 36831,
"text": "nitin mittal"
},
{
"code": null,
"e": 36849,
"s": 36844,
"text": "vt_m"
},
{
"code": null,
"e": 36866,
"s": 36849,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36882,
"s": 36866,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 36899,
"s": 36882,
"text": "square-rectangle"
},
{
"code": null,
"e": 36909,
"s": 36899,
"text": "Geometric"
},
{
"code": null,
"e": 36919,
"s": 36909,
"text": "Geometric"
},
{
"code": null,
"e": 37017,
"s": 36919,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37066,
"s": 37017,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 37117,
"s": 37066,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 37170,
"s": 37117,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 37219,
"s": 37170,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 37267,
"s": 37219,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 37325,
"s": 37267,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 37372,
"s": 37325,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 37407,
"s": 37372,
"text": "Program to find area of a triangle"
},
{
"code": null,
"e": 37482,
"s": 37407,
"text": "Window to Viewport Transformation in Computer Graphics with Implementation"
}
] |
How to create Grouped box plot in Plotly? - GeeksforGeeks
|
05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A grouped box plot is a box plot where categorized are organized in groups and sub-groups. Origin supports plotting grouped Box charts from both Indexed Data or Raw Data. The group box plot is more understandable and efficient in presentation and take less space in the layout.
It can be created using the add_trace() method of figure class. The add_trace() method allow us to add multiple traces in a single graph. Let’s see the below examples
Example 1: Vertical grouping of the box plot
Python3
import plotly.graph_objects as go fig = go.Figure() # Defining x axisx = ['a', 'a', 'a', 'b', 'b', 'b'] fig.add_trace(go.Box( # defining y axis in corresponding # to x-axis y=[1, 2, 6, 4, 5, 6], x=x, name='A', marker_color='green')) fig.add_trace(go.Box( y=[2, 3, 4, 1, 2, 6], x=x, name='B', marker_color='yellow')) fig.add_trace(go.Box( y=[2, 5, 6, 7, 8, 1], x=x, name='C', marker_color='blue')) fig.update_layout( # group together boxes of the different # traces for each value of x boxmode='group')fig.show()
Output:
Example 2: Horizontal grouping of the box plot
Python3
import plotly.graph_objects as go fig = go.Figure() # Defining y axisy = ['a', 'a', 'a', 'b', 'b', 'b'] fig.add_trace(go.Box( # defining x axis in corresponding # to y-axis y=y, x=[1, 2, 6, 4, 5, 6], name='A', marker_color='green')) fig.add_trace(go.Box( y=y, x=[2, 3, 4, 1, 2, 6], name='B', marker_color='yellow')) fig.add_trace(go.Box( y=y, x=[2, 5, 6, 7, 8, 1], name='C', marker_color='blue')) fig.update_layout( # group together boxes of the different # traces for each value of y boxmode='group') # changing the orientation to horizontalfig.update_traces(orientation='h') fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 25858,
"s": 25555,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. "
},
{
"code": null,
"e": 26136,
"s": 25858,
"text": "A grouped box plot is a box plot where categorized are organized in groups and sub-groups. Origin supports plotting grouped Box charts from both Indexed Data or Raw Data. The group box plot is more understandable and efficient in presentation and take less space in the layout."
},
{
"code": null,
"e": 26303,
"s": 26136,
"text": "It can be created using the add_trace() method of figure class. The add_trace() method allow us to add multiple traces in a single graph. Let’s see the below examples"
},
{
"code": null,
"e": 26348,
"s": 26303,
"text": "Example 1: Vertical grouping of the box plot"
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure() # Defining x axisx = ['a', 'a', 'a', 'b', 'b', 'b'] fig.add_trace(go.Box( # defining y axis in corresponding # to x-axis y=[1, 2, 6, 4, 5, 6], x=x, name='A', marker_color='green')) fig.add_trace(go.Box( y=[2, 3, 4, 1, 2, 6], x=x, name='B', marker_color='yellow')) fig.add_trace(go.Box( y=[2, 5, 6, 7, 8, 1], x=x, name='C', marker_color='blue')) fig.update_layout( # group together boxes of the different # traces for each value of x boxmode='group')fig.show()",
"e": 26931,
"s": 26356,
"text": null
},
{
"code": null,
"e": 26939,
"s": 26931,
"text": "Output:"
},
{
"code": null,
"e": 26986,
"s": 26939,
"text": "Example 2: Horizontal grouping of the box plot"
},
{
"code": null,
"e": 26994,
"s": 26986,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure() # Defining y axisy = ['a', 'a', 'a', 'b', 'b', 'b'] fig.add_trace(go.Box( # defining x axis in corresponding # to y-axis y=y, x=[1, 2, 6, 4, 5, 6], name='A', marker_color='green')) fig.add_trace(go.Box( y=y, x=[2, 3, 4, 1, 2, 6], name='B', marker_color='yellow')) fig.add_trace(go.Box( y=y, x=[2, 5, 6, 7, 8, 1], name='C', marker_color='blue')) fig.update_layout( # group together boxes of the different # traces for each value of y boxmode='group') # changing the orientation to horizontalfig.update_traces(orientation='h') fig.show()",
"e": 27647,
"s": 26994,
"text": null
},
{
"code": null,
"e": 27655,
"s": 27647,
"text": "Output:"
},
{
"code": null,
"e": 27669,
"s": 27655,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27676,
"s": 27669,
"text": "Python"
},
{
"code": null,
"e": 27774,
"s": 27676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27806,
"s": 27774,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27848,
"s": 27806,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27890,
"s": 27848,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27946,
"s": 27890,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27973,
"s": 27946,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28004,
"s": 27973,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28043,
"s": 28004,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28072,
"s": 28043,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28094,
"s": 28072,
"text": "Defaultdict in Python"
}
] |
Python time.perf_counter_ns() Function - GeeksforGeeks
|
05 Nov, 2021
Python time.perf_counter_ns() function gives the integer value of time in nanoseconds.
Syntax:
from time import perf_counter_ns
We can find the elapsed time by using start and stop functions. We can also find the elapsed time during the whole program by subtracting stoptime and starttime
Example 1:
Python3
# import perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / counterstart = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / counterstop = perf_counter_ns() print("Elapsed time:", stop, 'ns', start, 'ns') print("Elapsed time during the whole program", stop-start, 'ns')
Output:
Example 2:
Python3
# import perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / counterstart = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / counterstop = perf_counter_ns() print("Elapsed time:", stop, 'ns', start, 'ns') print("Elapsed time during the whole program", stop-start, 'ns')
Output:
Picked
Python time-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 25624,
"s": 25537,
"text": "Python time.perf_counter_ns() function gives the integer value of time in nanoseconds."
},
{
"code": null,
"e": 25632,
"s": 25624,
"text": "Syntax:"
},
{
"code": null,
"e": 25665,
"s": 25632,
"text": "from time import perf_counter_ns"
},
{
"code": null,
"e": 25826,
"s": 25665,
"text": "We can find the elapsed time by using start and stop functions. We can also find the elapsed time during the whole program by subtracting stoptime and starttime"
},
{
"code": null,
"e": 25837,
"s": 25826,
"text": "Example 1:"
},
{
"code": null,
"e": 25845,
"s": 25837,
"text": "Python3"
},
{
"code": "# import perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / counterstart = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / counterstop = perf_counter_ns() print(\"Elapsed time:\", stop, 'ns', start, 'ns') print(\"Elapsed time during the whole program\", stop-start, 'ns')",
"e": 26323,
"s": 25845,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26323,
"text": "Output:"
},
{
"code": null,
"e": 26342,
"s": 26331,
"text": "Example 2:"
},
{
"code": null,
"e": 26350,
"s": 26342,
"text": "Python3"
},
{
"code": "# import perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / counterstart = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / counterstop = perf_counter_ns() print(\"Elapsed time:\", stop, 'ns', start, 'ns') print(\"Elapsed time during the whole program\", stop-start, 'ns')",
"e": 26828,
"s": 26350,
"text": null
},
{
"code": null,
"e": 26836,
"s": 26828,
"text": "Output:"
},
{
"code": null,
"e": 26843,
"s": 26836,
"text": "Picked"
},
{
"code": null,
"e": 26862,
"s": 26843,
"text": "Python time-module"
},
{
"code": null,
"e": 26869,
"s": 26862,
"text": "Python"
},
{
"code": null,
"e": 26967,
"s": 26869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26999,
"s": 26967,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27041,
"s": 26999,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27083,
"s": 27041,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27110,
"s": 27083,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27166,
"s": 27110,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27188,
"s": 27166,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27227,
"s": 27188,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27258,
"s": 27227,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27287,
"s": 27258,
"text": "Create a directory in Python"
}
] |
PostgreSQL - TRUNCATE TABLE - GeeksforGeeks
|
28 Aug, 2020
PostgreSQL supports the TRUNCATE TABLE statement to remove all data from large tables quickly. To remove all data from a table, you use the DELETE statement. However, for a large table, it is more efficient to use the TRUNCATE TABLE statement. The TRUNCATE TABLE statement removes all rows from a table without scanning it. This is the reason why it is faster than the DELETE statement. In addition, the TRUNCATE TABLE statement reclaims the storage right away so the user does not have to perform a subsequent VACUUM operation, which is useful in case of large tables.
Syntax: TRUNCATE TABLE table_name;
Example 1:In our database, we already have a table with data called animals. Let’s check if it has any data using the below statement:
SELECT * FROM animals;
It shows the following result:Now we will delete all the data from the table using the below statement:
TRUNCATE TABLE animals;
Now we verify whether the deletion is complete using the below statement:
SELECT * FROM animals;
Output:
Example 2:In our database, we already have a table with data called galaxy. Let’s check if it has any data using the below statement:
SELECT * FROM galaxy;
It shows the following result:Now we will delete all the data from the table using the below statement:
TRUNCATE TABLE galaxy;
Now we verify whether the deletion is complete using the below statement:
SELECT * FROM galaxy;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column
|
[
{
"code": null,
"e": 29245,
"s": 29217,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 29815,
"s": 29245,
"text": "PostgreSQL supports the TRUNCATE TABLE statement to remove all data from large tables quickly. To remove all data from a table, you use the DELETE statement. However, for a large table, it is more efficient to use the TRUNCATE TABLE statement. The TRUNCATE TABLE statement removes all rows from a table without scanning it. This is the reason why it is faster than the DELETE statement. In addition, the TRUNCATE TABLE statement reclaims the storage right away so the user does not have to perform a subsequent VACUUM operation, which is useful in case of large tables."
},
{
"code": null,
"e": 29850,
"s": 29815,
"text": "Syntax: TRUNCATE TABLE table_name;"
},
{
"code": null,
"e": 29985,
"s": 29850,
"text": "Example 1:In our database, we already have a table with data called animals. Let’s check if it has any data using the below statement:"
},
{
"code": null,
"e": 30008,
"s": 29985,
"text": "SELECT * FROM animals;"
},
{
"code": null,
"e": 30112,
"s": 30008,
"text": "It shows the following result:Now we will delete all the data from the table using the below statement:"
},
{
"code": null,
"e": 30136,
"s": 30112,
"text": "TRUNCATE TABLE animals;"
},
{
"code": null,
"e": 30210,
"s": 30136,
"text": "Now we verify whether the deletion is complete using the below statement:"
},
{
"code": null,
"e": 30233,
"s": 30210,
"text": "SELECT * FROM animals;"
},
{
"code": null,
"e": 30241,
"s": 30233,
"text": "Output:"
},
{
"code": null,
"e": 30375,
"s": 30241,
"text": "Example 2:In our database, we already have a table with data called galaxy. Let’s check if it has any data using the below statement:"
},
{
"code": null,
"e": 30397,
"s": 30375,
"text": "SELECT * FROM galaxy;"
},
{
"code": null,
"e": 30501,
"s": 30397,
"text": "It shows the following result:Now we will delete all the data from the table using the below statement:"
},
{
"code": null,
"e": 30524,
"s": 30501,
"text": "TRUNCATE TABLE galaxy;"
},
{
"code": null,
"e": 30598,
"s": 30524,
"text": "Now we verify whether the deletion is complete using the below statement:"
},
{
"code": null,
"e": 30620,
"s": 30598,
"text": "SELECT * FROM galaxy;"
},
{
"code": null,
"e": 30628,
"s": 30620,
"text": "Output:"
},
{
"code": null,
"e": 30654,
"s": 30628,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 30665,
"s": 30654,
"text": "PostgreSQL"
},
{
"code": null,
"e": 30763,
"s": 30665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30790,
"s": 30763,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 30822,
"s": 30790,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 30845,
"s": 30822,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 30885,
"s": 30845,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 30940,
"s": 30885,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 30970,
"s": 30940,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 31004,
"s": 30970,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 31028,
"s": 31004,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 31052,
"s": 31028,
"text": "PostgreSQL - Copy Table"
}
] |
How To Select Only One Column Using SQLAlchemy? - GeeksforGeeks
|
10 Feb, 2022
In this article, we are going to see how to select only one column using SQLAlchemy in Python.
SQLAlchemy is a large SQL toolkit with lots of different components. The two largest components are SQLAlchemy Core and SQLAlchemy ORM. The major difference between them is SQLAlchemy Core is a schema-centric model that means everything is treated as a part of the database i.e., rows, columns, tables, etc while SQLAlchemy Core uses an object-centric view which encapsulates the schema with business objects. SQLAlchemy is a more pythonic implementation. In this post, we shall look at the SQLAlchemy core and ORM and how to select only one column using it.
SQLAlchemy is available via the pip install package.
pip install sqlalchemy
However, if you are using a flask you can make use of its own implementation of SQLAlchemy. It can be installed using:
pip install flask-sqlalchemy
Before we proceed with the code, make sure you have a database to work with. In the below examples, we are going to make use of the mySQL database. Feel free to use any database but the connection string will vary accordingly.
The syntax, given below, holds true for both to the SQLAlchemy core and ORM.
Syntax: sqlalchemy.sql.expression.select(*args, **kw)
Creates a SQL SELECT statement
Python
import sqlalchemy as db # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine("mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE METADATA OBJECTmetadata_obj = db.MetaData() # DEFINE THE PROFILE TABLE WITH 3 COLUMNSprofile = db.Table( 'profile', metadata_obj, db.Column('email', db.String(50), primary_key=True), db.Column('name', db.String(100)), db.Column('contact', db.Integer),) # CREATE THE PROFILE TABLE IN THE DATABASEmetadata_obj.create_all(engine) # INSERT RECORDS IN THE PROFILE TABLEstmt = profile.insert().values(("amitpathak@zmail.com", "Amit Pathak", 879456123))engine.execute(stmt)stmt = profile.insert().values(("amitmishra@zmail.com", "Amit Mishra", 456789123))engine.execute(stmt)stmt = profile.insert().values(("ravipandey@zmail.com", "Ravi Pandey", 321456987))engine.execute(stmt) # SQLAlCHEMY CORE QUERY TO FETCH SINGLE COLUMN (EMAIL)query = db.select([profile.c.email]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print("\n", record)
Output:
In the above code, we have used SQLAlchemy core to select one column from a table. We first created a profile table with 3 columns, namely, email, name, and contact. We then entered 3 different records in this table. The records are then fetched using the select method of the sqlalchemy library.
In the first example, we have already created the profile table and provided 3 records in the table. In this example, we focus on how to extract a single column using SQLAlchemy ORM. As we can see, both ORM and core have the same syntax when it comes to querying a single row. The only difference is the way we define the metadata of the profile table. In the ORM code, it seems more pythonic since the usage of python class is observed. For this example, we have fetched the name column. We first define the profile table and then use this definition to fetch the name column from the profile table.
Python
import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine("mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # SQLAlCHEMY CORE QUERY TO FETCH SINGLE COLUMN (EMAIL)query = db.select([Profile.name]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print("\n", record)
Output:
sagar0719kumar
Picked
Python SQLAlchemy-Core
Python SQLAlchemy-ORM
Python-SQLAlchemy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 25632,
"s": 25537,
"text": "In this article, we are going to see how to select only one column using SQLAlchemy in Python."
},
{
"code": null,
"e": 26191,
"s": 25632,
"text": "SQLAlchemy is a large SQL toolkit with lots of different components. The two largest components are SQLAlchemy Core and SQLAlchemy ORM. The major difference between them is SQLAlchemy Core is a schema-centric model that means everything is treated as a part of the database i.e., rows, columns, tables, etc while SQLAlchemy Core uses an object-centric view which encapsulates the schema with business objects. SQLAlchemy is a more pythonic implementation. In this post, we shall look at the SQLAlchemy core and ORM and how to select only one column using it."
},
{
"code": null,
"e": 26244,
"s": 26191,
"text": "SQLAlchemy is available via the pip install package."
},
{
"code": null,
"e": 26267,
"s": 26244,
"text": "pip install sqlalchemy"
},
{
"code": null,
"e": 26386,
"s": 26267,
"text": "However, if you are using a flask you can make use of its own implementation of SQLAlchemy. It can be installed using:"
},
{
"code": null,
"e": 26415,
"s": 26386,
"text": "pip install flask-sqlalchemy"
},
{
"code": null,
"e": 26642,
"s": 26415,
"text": "Before we proceed with the code, make sure you have a database to work with. In the below examples, we are going to make use of the mySQL database. Feel free to use any database but the connection string will vary accordingly."
},
{
"code": null,
"e": 26719,
"s": 26642,
"text": "The syntax, given below, holds true for both to the SQLAlchemy core and ORM."
},
{
"code": null,
"e": 26773,
"s": 26719,
"text": "Syntax: sqlalchemy.sql.expression.select(*args, **kw)"
},
{
"code": null,
"e": 26804,
"s": 26773,
"text": "Creates a SQL SELECT statement"
},
{
"code": null,
"e": 26811,
"s": 26804,
"text": "Python"
},
{
"code": "import sqlalchemy as db # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine(\"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE METADATA OBJECTmetadata_obj = db.MetaData() # DEFINE THE PROFILE TABLE WITH 3 COLUMNSprofile = db.Table( 'profile', metadata_obj, db.Column('email', db.String(50), primary_key=True), db.Column('name', db.String(100)), db.Column('contact', db.Integer),) # CREATE THE PROFILE TABLE IN THE DATABASEmetadata_obj.create_all(engine) # INSERT RECORDS IN THE PROFILE TABLEstmt = profile.insert().values((\"amitpathak@zmail.com\", \"Amit Pathak\", 879456123))engine.execute(stmt)stmt = profile.insert().values((\"amitmishra@zmail.com\", \"Amit Mishra\", 456789123))engine.execute(stmt)stmt = profile.insert().values((\"ravipandey@zmail.com\", \"Ravi Pandey\", 321456987))engine.execute(stmt) # SQLAlCHEMY CORE QUERY TO FETCH SINGLE COLUMN (EMAIL)query = db.select([profile.c.email]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print(\"\\n\", record)",
"e": 28088,
"s": 26811,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28092,
"text": "Output:"
},
{
"code": null,
"e": 28399,
"s": 28102,
"text": "In the above code, we have used SQLAlchemy core to select one column from a table. We first created a profile table with 3 columns, namely, email, name, and contact. We then entered 3 different records in this table. The records are then fetched using the select method of the sqlalchemy library."
},
{
"code": null,
"e": 29004,
"s": 28403,
"text": "In the first example, we have already created the profile table and provided 3 records in the table. In this example, we focus on how to extract a single column using SQLAlchemy ORM. As we can see, both ORM and core have the same syntax when it comes to querying a single row. The only difference is the way we define the metadata of the profile table. In the ORM code, it seems more pythonic since the usage of python class is observed. For this example, we have fetched the name column. We first define the profile table and then use this definition to fetch the name column from the profile table."
},
{
"code": null,
"e": 29013,
"s": 29006,
"text": "Python"
},
{
"code": "import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine(\"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # SQLAlCHEMY CORE QUERY TO FETCH SINGLE COLUMN (EMAIL)query = db.select([Profile.name]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print(\"\\n\", record)",
"e": 29712,
"s": 29013,
"text": null
},
{
"code": null,
"e": 29724,
"s": 29716,
"text": "Output:"
},
{
"code": null,
"e": 29743,
"s": 29728,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 29750,
"s": 29743,
"text": "Picked"
},
{
"code": null,
"e": 29773,
"s": 29750,
"text": "Python SQLAlchemy-Core"
},
{
"code": null,
"e": 29795,
"s": 29773,
"text": "Python SQLAlchemy-ORM"
},
{
"code": null,
"e": 29813,
"s": 29795,
"text": "Python-SQLAlchemy"
},
{
"code": null,
"e": 29820,
"s": 29813,
"text": "Python"
},
{
"code": null,
"e": 29918,
"s": 29820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29950,
"s": 29918,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29992,
"s": 29950,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30034,
"s": 29992,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30090,
"s": 30034,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30117,
"s": 30090,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30148,
"s": 30117,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30187,
"s": 30148,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30216,
"s": 30187,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30238,
"s": 30216,
"text": "Defaultdict in Python"
}
] |
How to write a Pseudo Code? - GeeksforGeeks
|
30 Sep, 2021
Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology that allows the programmer to represent the implementation of an algorithm. Simply, we can say that it’s the cooked up representation of an algorithm. Often at times, algorithms are represented with the help of pseudo codes as they can be interpreted by programmers no matter what their programming background or knowledge is. Pseudo code, as the name suggests, is a false code or a representation of code which can be understood by even a layman with some school level programming knowledge.
Algorithm: It’s an organized logical sequence of the actions or the approach towards a particular problem. A programmer implements an algorithm to solve a problem. Algorithms are expressed using natural verbal but somewhat technical annotations.
Pseudo code: It’s simply an implementation of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the computer.
Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm.
Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves vital.
The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer.
Arrange the sequence of tasks and write the pseudocode accordingly.Start with the statement of a pseudo code which establishes the main goal or the aim.Example:This program will allow the user to check
the number whether it's even or odd.The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it helps to comprehend the decision control and execution mechanism. They also improve the readability to a great extent.Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
Use appropriate naming conventions. The human tendency follows the approach to follow what we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the naming must be simple and distinct.Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower case for variables.Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code abstract.Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming.Check whether all the sections of a pseudo code is complete, finite and clear to understand and comprehend.Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to understand even for a layman or client, hence don’t incorporate too many technical terms.
Arrange the sequence of tasks and write the pseudocode accordingly.
Start with the statement of a pseudo code which establishes the main goal or the aim.Example:This program will allow the user to check
the number whether it's even or odd.
Example:
This program will allow the user to check
the number whether it's even or odd.
The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it helps to comprehend the decision control and execution mechanism. They also improve the readability to a great extent.Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
Use appropriate naming conventions. The human tendency follows the approach to follow what we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the naming must be simple and distinct.
Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower case for variables.
Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code abstract.
Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming.
Check whether all the sections of a pseudo code is complete, finite and clear to understand and comprehend.
Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to understand even for a layman or client, hence don’t incorporate too many technical terms.
Let’s have a look at this code
Java
// This program calculates the Lowest Common multiple// for excessively long input values import java.util.*; public class LowestCommonMultiple { private static long lcmNaive(long numberOne, long numberTwo) { long lowestCommonMultiple; lowestCommonMultiple = (numberOne * numberTwo) / greatestCommonDivisor(numberOne, numberTwo); return lowestCommonMultiple; } private static long greatestCommonDivisor(long numberOne, long numberTwo) { if (numberTwo == 0) return numberOne; return greatestCommonDivisor(numberTwo, numberOne % numberTwo); } public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the inputs"); long numberOne = scanner.nextInt(); long numberTwo = scanner.nextInt(); System.out.println(lcmNaive(numberOne, numberTwo)); }}
And here’s the Pseudo Code for the same.
This program calculates the Lowest Common multiple for excessively long input values function lcmNaive(Argument one, Argument two){ Calculate the lowest common variable of Argument 1 and Argument 2 by dividing their product by their Greatest common divisor product return lowest common multipleend}function greatestCommonDivisor(Argument one, Argument two){ if Argument two is equal to zero then return Argument one return the greatest common divisor end} {In the main function print prompt "Input two numbers" Take the first number from the user Take the second number from the user Send the first number and second number to the lcmNaive function and print the result to the user }
itskawal2000
Algorithms-Misc
Picked
Algorithms
Articles
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
How to Start Learning DSA?
Playfair Cipher with Examples
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
SQL Interview Questions
|
[
{
"code": null,
"e": 26427,
"s": 26399,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 27025,
"s": 26427,
"text": "Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology that allows the programmer to represent the implementation of an algorithm. Simply, we can say that it’s the cooked up representation of an algorithm. Often at times, algorithms are represented with the help of pseudo codes as they can be interpreted by programmers no matter what their programming background or knowledge is. Pseudo code, as the name suggests, is a false code or a representation of code which can be understood by even a layman with some school level programming knowledge."
},
{
"code": null,
"e": 27271,
"s": 27025,
"text": "Algorithm: It’s an organized logical sequence of the actions or the approach towards a particular problem. A programmer implements an algorithm to solve a problem. Algorithms are expressed using natural verbal but somewhat technical annotations."
},
{
"code": null,
"e": 27517,
"s": 27271,
"text": "Pseudo code: It’s simply an implementation of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the computer."
},
{
"code": null,
"e": 27632,
"s": 27517,
"text": "Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm."
},
{
"code": null,
"e": 27934,
"s": 27632,
"text": "Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves vital."
},
{
"code": null,
"e": 28094,
"s": 27934,
"text": "The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer."
},
{
"code": null,
"e": 29512,
"s": 28094,
"text": "Arrange the sequence of tasks and write the pseudocode accordingly.Start with the statement of a pseudo code which establishes the main goal or the aim.Example:This program will allow the user to check\nthe number whether it's even or odd.The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it helps to comprehend the decision control and execution mechanism. They also improve the readability to a great extent.Example:\n\nif \"1\"\n print response\n \"I am case 1\"\n\nif \"2\"\n print response\n \"I am case 2\"\nUse appropriate naming conventions. The human tendency follows the approach to follow what we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the naming must be simple and distinct.Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower case for variables.Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code abstract.Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming.Check whether all the sections of a pseudo code is complete, finite and clear to understand and comprehend.Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to understand even for a layman or client, hence don’t incorporate too many technical terms.\n"
},
{
"code": null,
"e": 29580,
"s": 29512,
"text": "Arrange the sequence of tasks and write the pseudocode accordingly."
},
{
"code": null,
"e": 29752,
"s": 29580,
"text": "Start with the statement of a pseudo code which establishes the main goal or the aim.Example:This program will allow the user to check\nthe number whether it's even or odd."
},
{
"code": null,
"e": 29761,
"s": 29752,
"text": "Example:"
},
{
"code": null,
"e": 29840,
"s": 29761,
"text": "This program will allow the user to check\nthe number whether it's even or odd."
},
{
"code": null,
"e": 30169,
"s": 29840,
"text": "The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it helps to comprehend the decision control and execution mechanism. They also improve the readability to a great extent.Example:\n\nif \"1\"\n print response\n \"I am case 1\"\n\nif \"2\"\n print response\n \"I am case 2\"\n"
},
{
"code": null,
"e": 30277,
"s": 30169,
"text": "Example:\n\nif \"1\"\n print response\n \"I am case 1\"\n\nif \"2\"\n print response\n \"I am case 2\"\n"
},
{
"code": null,
"e": 30504,
"s": 30277,
"text": "Use appropriate naming conventions. The human tendency follows the approach to follow what we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the naming must be simple and distinct."
},
{
"code": null,
"e": 30624,
"s": 30504,
"text": "Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower case for variables."
},
{
"code": null,
"e": 30727,
"s": 30624,
"text": "Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code abstract."
},
{
"code": null,
"e": 30840,
"s": 30727,
"text": "Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming."
},
{
"code": null,
"e": 30948,
"s": 30840,
"text": "Check whether all the sections of a pseudo code is complete, finite and clear to understand and comprehend."
},
{
"code": null,
"e": 31134,
"s": 30948,
"text": "Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to understand even for a layman or client, hence don’t incorporate too many technical terms.\n"
},
{
"code": null,
"e": 31165,
"s": 31134,
"text": "Let’s have a look at this code"
},
{
"code": null,
"e": 31170,
"s": 31165,
"text": "Java"
},
{
"code": "// This program calculates the Lowest Common multiple// for excessively long input values import java.util.*; public class LowestCommonMultiple { private static long lcmNaive(long numberOne, long numberTwo) { long lowestCommonMultiple; lowestCommonMultiple = (numberOne * numberTwo) / greatestCommonDivisor(numberOne, numberTwo); return lowestCommonMultiple; } private static long greatestCommonDivisor(long numberOne, long numberTwo) { if (numberTwo == 0) return numberOne; return greatestCommonDivisor(numberTwo, numberOne % numberTwo); } public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println(\"Enter the inputs\"); long numberOne = scanner.nextInt(); long numberTwo = scanner.nextInt(); System.out.println(lcmNaive(numberOne, numberTwo)); }}",
"e": 32192,
"s": 31170,
"text": null
},
{
"code": null,
"e": 32233,
"s": 32192,
"text": "And here’s the Pseudo Code for the same."
},
{
"code": "This program calculates the Lowest Common multiple for excessively long input values function lcmNaive(Argument one, Argument two){ Calculate the lowest common variable of Argument 1 and Argument 2 by dividing their product by their Greatest common divisor product return lowest common multipleend}function greatestCommonDivisor(Argument one, Argument two){ if Argument two is equal to zero then return Argument one return the greatest common divisor end} {In the main function print prompt \"Input two numbers\" Take the first number from the user Take the second number from the user Send the first number and second number to the lcmNaive function and print the result to the user }",
"e": 32982,
"s": 32233,
"text": null
},
{
"code": null,
"e": 32995,
"s": 32982,
"text": "itskawal2000"
},
{
"code": null,
"e": 33011,
"s": 32995,
"text": "Algorithms-Misc"
},
{
"code": null,
"e": 33018,
"s": 33011,
"text": "Picked"
},
{
"code": null,
"e": 33029,
"s": 33018,
"text": "Algorithms"
},
{
"code": null,
"e": 33038,
"s": 33029,
"text": "Articles"
},
{
"code": null,
"e": 33049,
"s": 33038,
"text": "Algorithms"
},
{
"code": null,
"e": 33147,
"s": 33049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33196,
"s": 33147,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33221,
"s": 33196,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33272,
"s": 33221,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 33299,
"s": 33272,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 33329,
"s": 33299,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 33379,
"s": 33329,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 33426,
"s": 33379,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 33462,
"s": 33426,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 33515,
"s": 33462,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
}
] |
Deque element() method in Java - GeeksforGeeks
|
19 Dec, 2021
The element() method of Deque Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the Deque. The method throws an exception when the Deque is empty. Syntax:
E element()
Parameters: This method does not accepts any parameter.Returns: This method returns the element at the front the container or the head of the Deque.Exception: The function throws NoSuchElementException when the Deque is empty and the function is called. Below programs illustrate element() method of Deque:Program 1: With the help of LinkedList.
Java
// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println("Deque: " + DQ); // print head System.out.println("Deque's head: " + DQ.element()); }}
Deque: [7855642, 35658786, 5278367, 74381793]
Deque's head: 7855642
Program 2: With the help of ArrayDeque.
Java
// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ArrayDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println("Deque: " + DQ); // print head System.out.println("Deque's head: " + DQ.element()); }}
Deque: [7855642, 35658786, 5278367, 74381793]
Deque's head: 7855642
Program 3: With the help of ConcurrentLinkedDeque.
Java
// Java Program Demonstrate element()// method of Dequeimport java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println("Deque: " + DQ); // print head System.out.println("Deque's head: " + DQ.element()); }}
Deque: [7855642, 35658786, 5278367, 74381793]
Deque's head: 7855642
Program 4: With the help of LinkedBlockingDeque.
Java
// Java Program Demonstrate element()// method of Dequeimport java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println("Deque: " + DQ); // print head System.out.println("Deque's head: " + DQ.element()); }}
Deque: [7855642, 35658786, 5278367, 74381793]
Deque's head: 7855642
Program 2:
Java
// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println("Deque: " + DQ); // print head System.out.println("Deque's head: " + DQ.element()); DQ.clear(); // Deque is empty now hence exception System.out.println("Deque's head: " + DQ.element()); }}
Output:
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.getFirst(LinkedList.java:244)
at java.util.LinkedList.element(LinkedList.java:663)
at GFG.main(GFG.java:29)
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html#element–
anikaseth98
Java - util package
java-deque
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25497,
"s": 25469,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 25744,
"s": 25497,
"text": "The element() method of Deque Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the Deque. The method throws an exception when the Deque is empty. Syntax: "
},
{
"code": null,
"e": 25756,
"s": 25744,
"text": "E element()"
},
{
"code": null,
"e": 26104,
"s": 25756,
"text": "Parameters: This method does not accepts any parameter.Returns: This method returns the element at the front the container or the head of the Deque.Exception: The function throws NoSuchElementException when the Deque is empty and the function is called. Below programs illustrate element() method of Deque:Program 1: With the help of LinkedList. "
},
{
"code": null,
"e": 26109,
"s": 26104,
"text": "Java"
},
{
"code": "// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println(\"Deque: \" + DQ); // print head System.out.println(\"Deque's head: \" + DQ.element()); }}",
"e": 26676,
"s": 26109,
"text": null
},
{
"code": null,
"e": 26744,
"s": 26676,
"text": "Deque: [7855642, 35658786, 5278367, 74381793]\nDeque's head: 7855642"
},
{
"code": null,
"e": 26787,
"s": 26746,
"text": "Program 2: With the help of ArrayDeque. "
},
{
"code": null,
"e": 26792,
"s": 26787,
"text": "Java"
},
{
"code": "// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ArrayDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println(\"Deque: \" + DQ); // print head System.out.println(\"Deque's head: \" + DQ.element()); }}",
"e": 27359,
"s": 26792,
"text": null
},
{
"code": null,
"e": 27427,
"s": 27359,
"text": "Deque: [7855642, 35658786, 5278367, 74381793]\nDeque's head: 7855642"
},
{
"code": null,
"e": 27481,
"s": 27429,
"text": "Program 3: With the help of ConcurrentLinkedDeque. "
},
{
"code": null,
"e": 27486,
"s": 27481,
"text": "Java"
},
{
"code": "// Java Program Demonstrate element()// method of Dequeimport java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println(\"Deque: \" + DQ); // print head System.out.println(\"Deque's head: \" + DQ.element()); }}",
"e": 28114,
"s": 27486,
"text": null
},
{
"code": null,
"e": 28182,
"s": 28114,
"text": "Deque: [7855642, 35658786, 5278367, 74381793]\nDeque's head: 7855642"
},
{
"code": null,
"e": 28234,
"s": 28184,
"text": "Program 4: With the help of LinkedBlockingDeque. "
},
{
"code": null,
"e": 28239,
"s": 28234,
"text": "Java"
},
{
"code": "// Java Program Demonstrate element()// method of Dequeimport java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println(\"Deque: \" + DQ); // print head System.out.println(\"Deque's head: \" + DQ.element()); }}",
"e": 28863,
"s": 28239,
"text": null
},
{
"code": null,
"e": 28931,
"s": 28863,
"text": "Deque: [7855642, 35658786, 5278367, 74381793]\nDeque's head: 7855642"
},
{
"code": null,
"e": 28945,
"s": 28933,
"text": "Program 2: "
},
{
"code": null,
"e": 28950,
"s": 28945,
"text": "Java"
},
{
"code": "// Java Program Demonstrate element()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // print Deque System.out.println(\"Deque: \" + DQ); // print head System.out.println(\"Deque's head: \" + DQ.element()); DQ.clear(); // Deque is empty now hence exception System.out.println(\"Deque's head: \" + DQ.element()); }}",
"e": 29643,
"s": 28950,
"text": null
},
{
"code": null,
"e": 29652,
"s": 29643,
"text": "Output: "
},
{
"code": null,
"e": 29856,
"s": 29652,
"text": "Exception in thread \"main\" java.util.NoSuchElementException\n at java.util.LinkedList.getFirst(LinkedList.java:244)\n at java.util.LinkedList.element(LinkedList.java:663)\n at GFG.main(GFG.java:29)"
},
{
"code": null,
"e": 29939,
"s": 29856,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html#element–"
},
{
"code": null,
"e": 29951,
"s": 29939,
"text": "anikaseth98"
},
{
"code": null,
"e": 29971,
"s": 29951,
"text": "Java - util package"
},
{
"code": null,
"e": 29982,
"s": 29971,
"text": "java-deque"
},
{
"code": null,
"e": 29997,
"s": 29982,
"text": "Java-Functions"
},
{
"code": null,
"e": 30002,
"s": 29997,
"text": "Java"
},
{
"code": null,
"e": 30007,
"s": 30002,
"text": "Java"
},
{
"code": null,
"e": 30105,
"s": 30007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30156,
"s": 30105,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30186,
"s": 30156,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30205,
"s": 30186,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30220,
"s": 30205,
"text": "Stream In Java"
},
{
"code": null,
"e": 30251,
"s": 30220,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30269,
"s": 30251,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30301,
"s": 30269,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30333,
"s": 30301,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30357,
"s": 30333,
"text": "Singleton Class in Java"
}
] |
Attributes in C# - GeeksforGeeks
|
01 May, 2019
Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element. There are two types of Attributes implementations provided by the .NET Framework are:
Predefined AttributesCustom Attributes
Predefined Attributes
Custom Attributes
Properties of Attributes:
Attributes can have arguments just like methods, properties, etc. can have arguments.
Attributes can have zero or more parameters.
Different code elements such as methods, assemblies, properties, types, etc. can have one or multiple attributes.
Reflection can be used to obtain the metadata of the program by accessing the attributes at run-time.
Attributes are generally derived from the System.Attribute Class.
Predefined attributes are those attributes that are a part of the .NET Framework Class Library and are supported by the C# compiler for a specific purpose. Some of the predefined attributes that are derived from the System.Attribute base class are given as follows:
Let’s discuss some of the predefined attributes:
This attribute shows if a particular code element complies with the Common Language Specification. If a particular code element complies with the Common Language Specification. If it doesn’t, then a warning message is issued by the compiler.
Example 1: Here, it will not give any warning message and code compiles successfully.
// C# program to demonstrate CLSCompliantAttributeusing System; // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)] public class GFG { // Main Method public static void Main(string[] args) { Console.WriteLine("GeeksForGeeks"); }}
GeeksForGeeks
Example 2: This code will give a warning message by the compiler.
// C# program to demonstrate CLSCompliantAttribute// giving a warning messageusing System; // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)] public class GFG { public uint z;} class GFG2 { // Main Methodpublic static void Main(string[] args){ Console.WriteLine("GeeksForGeeks");} }
Warning:
prog.cs(9,14): warning CS3003: Type of `GFG.z’ is not CLS-compliant
The FlagsAttribute specifies that an enumeration can be used as a set of flags. This is most commonly used with bitwise operators.
Example:
// C# program to demonstrate FlagsAttributeusing System; class GFG { // Enum defined without FlagsAttribute. enum Colours { Red = 1, Blue = 2, Pink = 4, Green = 8 } // Enum defined with FlagsAttribute. [Flags] enum ColoursFlags { Red = 1, Blue = 2, Pink = 4, Green = 8 } // Main Method public static void Main(string[] args) { Console.WriteLine((Colours.Red | Colours.Blue).ToString()); Console.WriteLine((ColoursFlags.Red | ColoursFlags.Blue).ToString()); }}
3
Red, Blue
The ObsoleteAttribute marks the code elements that are obsolete i.e. not in use anymore. Calling these obsolete code elements results in a compiler error.
Example:
// C# program to demonstrate ObsoleteAttributeusing System; class GFG { // The method1() is marked as obsolete [Obsolete("method1 is obsolete", true)] static void method1() { Console.WriteLine("This is method1"); } static void method2() { Console.WriteLine("This is method2"); } public static void Main(string[] args) { method1(); // Compiler error as method1() is obsolete method2(); }}
Compile Errors:
prog.cs(18,3): error CS0619: `GFG.method1()’ is obsolete: `method1 is obsolete’
Custom attributes can be created in C# for attaching declarative information to methods, assemblies, properties, types, etc. in any way required. This increases the extensibility of the .NET framework.
Steps for creating Custom Attributes:
Define a custom attribute class that is derived from System.Attribute class.
The custom attribute class name should have the suffix Attribute.
Use the attribute AttributeUsage to specify the usage of the custom attribute class created.
Create the constructor and the accessible properties of the custom attribute class.Example:// C# program to demonstrate Custom Attributesusing System; // AttributeUsage specifies the usage// of InformationAttribute[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true)] // InformationAttribute is a custom attribute class // that is derived from Attribute class class InformationAttribute : Attribute { public string InformationString{ get; set; } } // InformationAttribute is used in student class[Information(InformationString = "Class")] public class student{ private int rollno; private string name; [Information(InformationString = "Constructor")] public student(int rollno, string name) { this.rollno = rollno; this.name = name; } [Information(InformationString = "Method")] public void display() { Console.WriteLine("Roll Number: {0}", rollno); Console.WriteLine("Name: {0}", name); }} // Driver Classpublic class GFG { // Main Method public static void Main(string[] args) { student s = new student(1001, "Lily Adams"); s.display(); }}Output:Roll Number: 1001
Name: Lily Adams
My Personal Notes
arrow_drop_upSave
Example:
// C# program to demonstrate Custom Attributesusing System; // AttributeUsage specifies the usage// of InformationAttribute[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true)] // InformationAttribute is a custom attribute class // that is derived from Attribute class class InformationAttribute : Attribute { public string InformationString{ get; set; } } // InformationAttribute is used in student class[Information(InformationString = "Class")] public class student{ private int rollno; private string name; [Information(InformationString = "Constructor")] public student(int rollno, string name) { this.rollno = rollno; this.name = name; } [Information(InformationString = "Method")] public void display() { Console.WriteLine("Roll Number: {0}", rollno); Console.WriteLine("Name: {0}", name); }} // Driver Classpublic class GFG { // Main Method public static void Main(string[] args) { student s = new student(1001, "Lily Adams"); s.display(); }}
Roll Number: 1001
Name: Lily Adams
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
C# | Arrays
|
[
{
"code": null,
"e": 25467,
"s": 25439,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 25846,
"s": 25467,
"text": "Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element. There are two types of Attributes implementations provided by the .NET Framework are:"
},
{
"code": null,
"e": 25885,
"s": 25846,
"text": "Predefined AttributesCustom Attributes"
},
{
"code": null,
"e": 25907,
"s": 25885,
"text": "Predefined Attributes"
},
{
"code": null,
"e": 25925,
"s": 25907,
"text": "Custom Attributes"
},
{
"code": null,
"e": 25951,
"s": 25925,
"text": "Properties of Attributes:"
},
{
"code": null,
"e": 26037,
"s": 25951,
"text": "Attributes can have arguments just like methods, properties, etc. can have arguments."
},
{
"code": null,
"e": 26082,
"s": 26037,
"text": "Attributes can have zero or more parameters."
},
{
"code": null,
"e": 26196,
"s": 26082,
"text": "Different code elements such as methods, assemblies, properties, types, etc. can have one or multiple attributes."
},
{
"code": null,
"e": 26298,
"s": 26196,
"text": "Reflection can be used to obtain the metadata of the program by accessing the attributes at run-time."
},
{
"code": null,
"e": 26364,
"s": 26298,
"text": "Attributes are generally derived from the System.Attribute Class."
},
{
"code": null,
"e": 26630,
"s": 26364,
"text": "Predefined attributes are those attributes that are a part of the .NET Framework Class Library and are supported by the C# compiler for a specific purpose. Some of the predefined attributes that are derived from the System.Attribute base class are given as follows:"
},
{
"code": null,
"e": 26679,
"s": 26630,
"text": "Let’s discuss some of the predefined attributes:"
},
{
"code": null,
"e": 26921,
"s": 26679,
"text": "This attribute shows if a particular code element complies with the Common Language Specification. If a particular code element complies with the Common Language Specification. If it doesn’t, then a warning message is issued by the compiler."
},
{
"code": null,
"e": 27007,
"s": 26921,
"text": "Example 1: Here, it will not give any warning message and code compiles successfully."
},
{
"code": "// C# program to demonstrate CLSCompliantAttributeusing System; // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)] public class GFG { // Main Method public static void Main(string[] args) { Console.WriteLine(\"GeeksForGeeks\"); }}",
"e": 27293,
"s": 27007,
"text": null
},
{
"code": null,
"e": 27308,
"s": 27293,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 27374,
"s": 27308,
"text": "Example 2: This code will give a warning message by the compiler."
},
{
"code": "// C# program to demonstrate CLSCompliantAttribute// giving a warning messageusing System; // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)] public class GFG { public uint z;} class GFG2 { // Main Methodpublic static void Main(string[] args){ Console.WriteLine(\"GeeksForGeeks\");} }",
"e": 27702,
"s": 27374,
"text": null
},
{
"code": null,
"e": 27711,
"s": 27702,
"text": "Warning:"
},
{
"code": null,
"e": 27779,
"s": 27711,
"text": "prog.cs(9,14): warning CS3003: Type of `GFG.z’ is not CLS-compliant"
},
{
"code": null,
"e": 27910,
"s": 27779,
"text": "The FlagsAttribute specifies that an enumeration can be used as a set of flags. This is most commonly used with bitwise operators."
},
{
"code": null,
"e": 27919,
"s": 27910,
"text": "Example:"
},
{
"code": "// C# program to demonstrate FlagsAttributeusing System; class GFG { // Enum defined without FlagsAttribute. enum Colours { Red = 1, Blue = 2, Pink = 4, Green = 8 } // Enum defined with FlagsAttribute. [Flags] enum ColoursFlags { Red = 1, Blue = 2, Pink = 4, Green = 8 } // Main Method public static void Main(string[] args) { Console.WriteLine((Colours.Red | Colours.Blue).ToString()); Console.WriteLine((ColoursFlags.Red | ColoursFlags.Blue).ToString()); }}",
"e": 28577,
"s": 27919,
"text": null
},
{
"code": null,
"e": 28590,
"s": 28577,
"text": "3\nRed, Blue\n"
},
{
"code": null,
"e": 28745,
"s": 28590,
"text": "The ObsoleteAttribute marks the code elements that are obsolete i.e. not in use anymore. Calling these obsolete code elements results in a compiler error."
},
{
"code": null,
"e": 28754,
"s": 28745,
"text": "Example:"
},
{
"code": "// C# program to demonstrate ObsoleteAttributeusing System; class GFG { // The method1() is marked as obsolete [Obsolete(\"method1 is obsolete\", true)] static void method1() { Console.WriteLine(\"This is method1\"); } static void method2() { Console.WriteLine(\"This is method2\"); } public static void Main(string[] args) { method1(); // Compiler error as method1() is obsolete method2(); }}",
"e": 29207,
"s": 28754,
"text": null
},
{
"code": null,
"e": 29223,
"s": 29207,
"text": "Compile Errors:"
},
{
"code": null,
"e": 29303,
"s": 29223,
"text": "prog.cs(18,3): error CS0619: `GFG.method1()’ is obsolete: `method1 is obsolete’"
},
{
"code": null,
"e": 29505,
"s": 29303,
"text": "Custom attributes can be created in C# for attaching declarative information to methods, assemblies, properties, types, etc. in any way required. This increases the extensibility of the .NET framework."
},
{
"code": null,
"e": 29543,
"s": 29505,
"text": "Steps for creating Custom Attributes:"
},
{
"code": null,
"e": 29620,
"s": 29543,
"text": "Define a custom attribute class that is derived from System.Attribute class."
},
{
"code": null,
"e": 29686,
"s": 29620,
"text": "The custom attribute class name should have the suffix Attribute."
},
{
"code": null,
"e": 29779,
"s": 29686,
"text": "Use the attribute AttributeUsage to specify the usage of the custom attribute class created."
},
{
"code": null,
"e": 31101,
"s": 29779,
"text": "Create the constructor and the accessible properties of the custom attribute class.Example:// C# program to demonstrate Custom Attributesusing System; // AttributeUsage specifies the usage// of InformationAttribute[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true)] // InformationAttribute is a custom attribute class // that is derived from Attribute class class InformationAttribute : Attribute { public string InformationString{ get; set; } } // InformationAttribute is used in student class[Information(InformationString = \"Class\")] public class student{ private int rollno; private string name; [Information(InformationString = \"Constructor\")] public student(int rollno, string name) { this.rollno = rollno; this.name = name; } [Information(InformationString = \"Method\")] public void display() { Console.WriteLine(\"Roll Number: {0}\", rollno); Console.WriteLine(\"Name: {0}\", name); }} // Driver Classpublic class GFG { // Main Method public static void Main(string[] args) { student s = new student(1001, \"Lily Adams\"); s.display(); }}Output:Roll Number: 1001\nName: Lily Adams\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31110,
"s": 31101,
"text": "Example:"
},
{
"code": "// C# program to demonstrate Custom Attributesusing System; // AttributeUsage specifies the usage// of InformationAttribute[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true)] // InformationAttribute is a custom attribute class // that is derived from Attribute class class InformationAttribute : Attribute { public string InformationString{ get; set; } } // InformationAttribute is used in student class[Information(InformationString = \"Class\")] public class student{ private int rollno; private string name; [Information(InformationString = \"Constructor\")] public student(int rollno, string name) { this.rollno = rollno; this.name = name; } [Information(InformationString = \"Method\")] public void display() { Console.WriteLine(\"Roll Number: {0}\", rollno); Console.WriteLine(\"Name: {0}\", name); }} // Driver Classpublic class GFG { // Main Method public static void Main(string[] args) { student s = new student(1001, \"Lily Adams\"); s.display(); }}",
"e": 32264,
"s": 31110,
"text": null
},
{
"code": null,
"e": 32300,
"s": 32264,
"text": "Roll Number: 1001\nName: Lily Adams\n"
},
{
"code": null,
"e": 32303,
"s": 32300,
"text": "C#"
},
{
"code": null,
"e": 32401,
"s": 32303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32429,
"s": 32401,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 32444,
"s": 32429,
"text": "C# | Delegates"
},
{
"code": null,
"e": 32466,
"s": 32444,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 32512,
"s": 32466,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 32535,
"s": 32512,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 32575,
"s": 32535,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 32597,
"s": 32575,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 32628,
"s": 32597,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 32644,
"s": 32628,
"text": "C# | Data Types"
}
] |
Sum of multiples of A and B less than N - GeeksforGeeks
|
07 Apr, 2021
Given a number N, the task is to find the sum of all the multiples of A and B below N.Examples:
Input:N = 11, A= 8, B= 2
Output: Sum = 30
Multiples of 8 less than 11 is 8 only.
Multiples of 2 less than 11 is 2, 4, 6, 8, 10 and their sum is 30.
As 8 is common in both so it is counted only once.
Input: N = 100, A= 5, B= 10
Output: Sum = 950
A naive approach is to iterate through 1 to and find the multiples of A and B and add them to sum. At the end of the loop display the sum.Efficient approach: As the multiples of A will form an AP series a, 2a, 3a.... and B forms an AP series b, 2b, 3b ... On adding the sum of these two series we will get the sum of multiples of both the numbers but there might be some common multiples so remove the duplicates from the sum of these two series by subtracting the multiples of lcm(A, B). So, subtract the series of lcm(A, B) . So the sum of multiples of A and B less than N is Sum(A)+Sum(B)-Sum(lcm(A, B)).Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the sum of all// multiples of A and B below N#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find sum of AP seriesll sumAP(ll n, ll d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nll sumMultiples(ll A, ll B, ll n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B ll common = (A * B) / __gcd(A, B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codeint main(){ ll n = 100, A = 5, B = 10; cout << "Sum = " << sumMultiples(A, B, n); return 0;}
// Java program to find the sum of all// multiples of A and B below N class GFG{ static int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find sum of AP seriesstatic int sumAP(int n, int d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nstatic int sumMultiples(int A, int B, int n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B int common = (A * B) / __gcd(A,B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codepublic static void main(String[] args){ int n = 100, A = 5, B = 10; System.out.println("Sum = "+sumMultiples(A, B, n));}}// this code is contributed by mits
# Python 3 program to find the sum of# all multiples of A and B below Nfrom math import gcd,sqrt # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d) return (n) * (1 + n) * d / 2 # Function to find the sum of all# multiples of A and B below Ndef sumMultiples(A, B, n): # Since, we need the sum of # multiples less than N n -= 1 # common factors of A and B common = int((A * B) / gcd(A, B)) return (sumAP(n, A) + sumAP(n, B) - sumAP(n, common)) # Driver codeif __name__ == '__main__': n = 100 A = 5 B = 10 print("Sum =", int(sumMultiples(A, B, n))) # This code is contributed by# Surendra_Gangwar
// C# program to find the sum of all// multiples of A and B below N class GFG{ static int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find sum of AP seriesstatic int sumAP(int n, int d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nstatic int sumMultiples(int A, int B, int n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B int common = (A * B) / __gcd(A,B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codepublic static void Main(){ int n = 100, A = 5, B = 10; System.Console.WriteLine("Sum = "+sumMultiples(A, B, n));}}// this code is contributed by mits
<?php// PHP program to find the sum of all// multiples of A and B below Nfunction __gcd($a,$b){ if ($b == 0) return $a; return __gcd($b, $a % $b);} // Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n / $d); return ($n) * (1 + $n) * $d / 2;} // Function to find the sum of all// multiples of A and B below Nfunction sumMultiples($A, $B, $n){ // Since, we need the sum of // multiples less than N $n--; // common factors of A and B $common = (int)(($A * $B) / __gcd($A, $B)); return sumAP($n, $A) + sumAP($n, $B) - sumAP($n, $common);} // Driver code$n = 100;$A = 5;$B = 10; echo "Sum = " . sumMultiples($A, $B, $n); // This code is contributed by mits?>
<script> // JavaScript program to find the sum of all// multiples of A and B below Nfunction __gcd(a,b){ if (b == 0) return a; return __gcd(b, a % b);} // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nfunction sumMultiples(A, B, n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B common = parseInt((A * B) / __gcd(A, B)); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codelet n = 100;let A = 5;let B = 10; document.write( "Sum = " + sumMultiples(A, B, n)); // This code is contributed by bobby </script>
Sum = 950
SURENDRA_GANGWAR
Mithun Kumar
gottumukkalabobby
arithmetic progression
GCD-LCM
series-sum
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
5 Best Languages for Competitive Programming
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26333,
"s": 26305,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26431,
"s": 26333,
"text": "Given a number N, the task is to find the sum of all the multiples of A and B below N.Examples: "
},
{
"code": null,
"e": 26677,
"s": 26431,
"text": "Input:N = 11, A= 8, B= 2\nOutput: Sum = 30\nMultiples of 8 less than 11 is 8 only.\nMultiples of 2 less than 11 is 2, 4, 6, 8, 10 and their sum is 30.\nAs 8 is common in both so it is counted only once.\n\nInput: N = 100, A= 5, B= 10\nOutput: Sum = 950"
},
{
"code": null,
"e": 27339,
"s": 26679,
"text": "A naive approach is to iterate through 1 to and find the multiples of A and B and add them to sum. At the end of the loop display the sum.Efficient approach: As the multiples of A will form an AP series a, 2a, 3a.... and B forms an AP series b, 2b, 3b ... On adding the sum of these two series we will get the sum of multiples of both the numbers but there might be some common multiples so remove the duplicates from the sum of these two series by subtracting the multiples of lcm(A, B). So, subtract the series of lcm(A, B) . So the sum of multiples of A and B less than N is Sum(A)+Sum(B)-Sum(lcm(A, B)).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27343,
"s": 27339,
"text": "C++"
},
{
"code": null,
"e": 27348,
"s": 27343,
"text": "Java"
},
{
"code": null,
"e": 27356,
"s": 27348,
"text": "Python3"
},
{
"code": null,
"e": 27359,
"s": 27356,
"text": "C#"
},
{
"code": null,
"e": 27363,
"s": 27359,
"text": "PHP"
},
{
"code": null,
"e": 27374,
"s": 27363,
"text": "Javascript"
},
{
"code": "// CPP program to find the sum of all// multiples of A and B below N#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find sum of AP seriesll sumAP(ll n, ll d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nll sumMultiples(ll A, ll B, ll n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B ll common = (A * B) / __gcd(A, B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codeint main(){ ll n = 100, A = 5, B = 10; cout << \"Sum = \" << sumMultiples(A, B, n); return 0;}",
"e": 28052,
"s": 27374,
"text": null
},
{
"code": "// Java program to find the sum of all// multiples of A and B below N class GFG{ static int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find sum of AP seriesstatic int sumAP(int n, int d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nstatic int sumMultiples(int A, int B, int n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B int common = (A * B) / __gcd(A,B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codepublic static void main(String[] args){ int n = 100, A = 5, B = 10; System.out.println(\"Sum = \"+sumMultiples(A, B, n));}}// this code is contributed by mits",
"e": 28864,
"s": 28052,
"text": null
},
{
"code": "# Python 3 program to find the sum of# all multiples of A and B below Nfrom math import gcd,sqrt # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d) return (n) * (1 + n) * d / 2 # Function to find the sum of all# multiples of A and B below Ndef sumMultiples(A, B, n): # Since, we need the sum of # multiples less than N n -= 1 # common factors of A and B common = int((A * B) / gcd(A, B)) return (sumAP(n, A) + sumAP(n, B) - sumAP(n, common)) # Driver codeif __name__ == '__main__': n = 100 A = 5 B = 10 print(\"Sum =\", int(sumMultiples(A, B, n))) # This code is contributed by# Surendra_Gangwar",
"e": 29556,
"s": 28864,
"text": null
},
{
"code": "// C# program to find the sum of all// multiples of A and B below N class GFG{ static int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find sum of AP seriesstatic int sumAP(int n, int d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nstatic int sumMultiples(int A, int B, int n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B int common = (A * B) / __gcd(A,B); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codepublic static void Main(){ int n = 100, A = 5, B = 10; System.Console.WriteLine(\"Sum = \"+sumMultiples(A, B, n));}}// this code is contributed by mits",
"e": 30354,
"s": 29556,
"text": null
},
{
"code": "<?php// PHP program to find the sum of all// multiples of A and B below Nfunction __gcd($a,$b){ if ($b == 0) return $a; return __gcd($b, $a % $b);} // Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n / $d); return ($n) * (1 + $n) * $d / 2;} // Function to find the sum of all// multiples of A and B below Nfunction sumMultiples($A, $B, $n){ // Since, we need the sum of // multiples less than N $n--; // common factors of A and B $common = (int)(($A * $B) / __gcd($A, $B)); return sumAP($n, $A) + sumAP($n, $B) - sumAP($n, $common);} // Driver code$n = 100;$A = 5;$B = 10; echo \"Sum = \" . sumMultiples($A, $B, $n); // This code is contributed by mits?>",
"e": 31125,
"s": 30354,
"text": null
},
{
"code": "<script> // JavaScript program to find the sum of all// multiples of A and B below Nfunction __gcd(a,b){ if (b == 0) return a; return __gcd(b, a % b);} // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of A and B below Nfunction sumMultiples(A, B, n){ // Since, we need the sum of // multiples less than N n--; // common factors of A and B common = parseInt((A * B) / __gcd(A, B)); return sumAP(n, A) + sumAP(n, B) - sumAP(n, common);} // Driver codelet n = 100;let A = 5;let B = 10; document.write( \"Sum = \" + sumMultiples(A, B, n)); // This code is contributed by bobby </script>",
"e": 31912,
"s": 31125,
"text": null
},
{
"code": null,
"e": 31922,
"s": 31912,
"text": "Sum = 950"
},
{
"code": null,
"e": 31941,
"s": 31924,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31954,
"s": 31941,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31972,
"s": 31954,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 31995,
"s": 31972,
"text": "arithmetic progression"
},
{
"code": null,
"e": 32003,
"s": 31995,
"text": "GCD-LCM"
},
{
"code": null,
"e": 32014,
"s": 32003,
"text": "series-sum"
},
{
"code": null,
"e": 32038,
"s": 32014,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32051,
"s": 32038,
"text": "Mathematical"
},
{
"code": null,
"e": 32064,
"s": 32051,
"text": "Mathematical"
},
{
"code": null,
"e": 32162,
"s": 32064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32195,
"s": 32162,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 32241,
"s": 32195,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 32299,
"s": 32241,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 32340,
"s": 32299,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 32385,
"s": 32340,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 32415,
"s": 32385,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32475,
"s": 32415,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32490,
"s": 32475,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32533,
"s": 32490,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to create NumPy arrays from scratch? | by Tanu N Prabhu | Towards Data Science
|
Regardless of the data, the first step in analyzing them is transforming them into an array of numbers. The fundamental process of doing data science is efficiently is storing and manipulating numerical arrays. Because of this Python has specialized tools for handling numerical arrays:
NumPy PackagePandas Package
NumPy Package
Pandas Package
This tutorial only focuses on the NumPy package. However, Pandas package documentation will be provided in the latter days. The entire code for the tutorial can be found on my GitHub Repository below:
github.com
NumPy stands for Numerical Python. NumPy provides an efficient way to store and operate on dense data buffers. With the help of the NumPy library, we can create and operate with arrays to store the data. In some ways, NumPy’s arrays are like Python’s list built-in function.
Let’s get started. You can execute the below programs in your favorite python editors like PyCharm, Sublime Text, or Notebooks like Jupyter and Google Colab. It's basically your preference to choose an IDE of your choice. I am using Google Colab to write my code because it gives me tons of options to provides good documentation. Also, visit the NumPy website to get more guidelines about the installation process.
Once you have installed the NumPy on your IDE you need to import it. It’s often a good practice to check the version of the library. So to install the NumPy library you need to use the below code.
import numpyprint(numpy.__version__)1.17.4
Just make sure that you the latest NumPy version to use all the features and options. Rather than using “numpy” we can use an alias as “np”. This is called “Aliasing”. Now the point of using an alias is we can use “np” rather “numpy” which is long to type every time when we use its methods. So creating an alias and checking the version can be done as shown below:
import numpy as npprint(np.__version__)1.17.4
From now on we can use “np” rather than “numpy” every time.
Python provides several different options for storing efficient, fixed-type data. Python has a built-in array module called “array” which is used to create arrays of uniform type. This was its main disadvantage.
import array# Creating an arrayprint(array.array('i', [1, 2, 3, 4, 5]))array('i', [1, 2, 3, 4, 5])
The “i” here indicates the integer data. We cannot try to store other types of data in the array module. It often leads to an error.
import array# Creating an arrayprint(array.array('i', [1, 2.0, 3, 4, 5]))--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-25-49d63cb1f570> in <module>()----> 1 array.array('i', [1, 2.0, 3, 4, 5])TypeError: integer argument expected, got float
However, Python’s array module provides efficient storage of array-based data. But NumPy arrays can perform efficient operations on that type of data. There are two ways that we can create NumPy arrays:
Creating a NumPy array from Python ListsCreating a NumPy array from scratch
Creating a NumPy array from Python Lists
Creating a NumPy array from scratch
We can use np.array method to create arrays from python lists.
import numpy as np# Creating a list named "a"a = [1, 2, 3, 4, 5]print(type(a))<class 'list'># Creating a numpy array from the listprint(np.array(a))[1 2 3 4 5]print(type(np.array(a)))<class 'numpy.ndarray'>
The NumPy library is limited to arrays with the same type, if there is a type mismatch then it would upcast if possible. Consider the below example:
import numpy as np# Creating a list named "a"a = [1, 2.0, 3, 4, 5]print(type(a))<class 'list'># Creating a numpy array from the listprint(np.array(a))[1. 2. 3. 4. 5.]print(type(np.array(a)))<class 'numpy.ndarray'>
So the original list was integers with one floating value but the numpy array upcasted it to all floating-point numbers. The integers are upcasted to floating-point numbers. Below is a small diagram that gives you enough knowledge to understand the upcast and downcast.
Also explicitly setting the data type is also possible. This can be done using the keyword “dtype”.
import numpy as np# Creating a list named "a"a = [1, 2, 3, 4, 5]# Creating a numpy array from the listnp.array(a, dtype='float64')print(np.array(a, dtype='float64'))[1. 2. 3. 4. 5.]
As seen from the above example, the integer type list data is converted into the float type data by using the “dtype” keyword.
Numpy arrays can also be multidimensional (Array within an array). Here’s one way of doing it.
import numpy as np# Creating a list named "a"a = [1, 2, 3, 4, 5]# Creating a numpy array from the listnp.array([range(i, i + 4) for i in a])[[1 2 3 4] [2 3 4 5] [3 4 5 6] [4 5 6 7] [5 6 7 8]]
Hint: Just increment the “i” value in terms of 1 (i+1, 2, 3, 4, ...) by doing so you can increase the dimension of the array too. The above array is treated as 2D — Array.
Numpy arrays are actually used for creating larger arrays. It is more efficient to create large arrays from scratch using the numpy package library. Below are some of the examples of creating numpy arrays from scratch.
Creating an array filled with zeros of length 5
Creating an array filled with zeros of length 5
We can do this using the numpy built-in method called zeros as shown below:
import numpy as np# Creating a numpy array of zeros of length 5print(np.zeros(5, dtype='int'))[0 0 0 0 0]
There are some standard numpy data types available. I cannot just discuss all of them in one stretch. Most of them are never used. So I will be providing the data types of numpy array in the form of a chart below just use that accordingly. If you don't know how to use the datatypes refer to Explicitly changing the array datatypes above its → dtypes = “name of the datatype”
2. Creating a 3 x 4 array filled with 1's
Thanks to NumPy because we don’t have to put the array inside a looping statement (I hate to do that ;)). All you have to do is just mention the rows and the columns that you want your array to have inside the numpy.one method.
import numpy as np# Creating a numpy array of 1’s which should have 3 rows and 4 columnsprint(np.ones((3, 4)))[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
So the number 3 → rows and 4 → obviously columns.
3. Filling the numpy arrays with a particular number
Till now we have seen filling the array with 0’s and 1’s but we should also know that numpy allows us to fill the arrays with any specific number of our choice. We can do this with the help of numpy.full method. For example, let us fill the array with the number 500.
import numpy as np# Creating a numpy array of 500’s which should have 3 rows and 4 columnsprint(np.full((3, 4), 500))[[500 500 500 500] [500 500 500 500] [500 500 500 500]]
With the help of the full method, we can add any number of our choice to our array.
4. Creating a numpy array of random numbers
Uniform distribution → It is a probability distribution in which all the outcomes are equally likely. For example, tossing a coin has the probability of uniform distribution because the outcomes are a most likely head or a tail. It’s never going to be both at the same time.
The NumPy package library provides us a uniform distribution method to generate random numbers called numpy.random.uniform.
import numpy as np# Create a 3x3 array of uniformly distributed # random values between 0 and 1print(np.random.random((3, 3)))[[0.89865866 0.71138067 0.85067426] [0.53568422 0.32887081 0.97449983] [0.48130729 0.15841703 0.57756513]]
Also, the numpy package library has a seed generator along with the random number generator, with the help of the seed method we can control the sequence of the random numbers being generated. Most of them don’t know the specialty of the seed method and its purpose. To know more about the seed method refer below.
If we use the seed every time then we get the same sequence of random numbers.
So, the same seed yields the same sequence of random numbers.
import numpy as np# Create a random number arrays of size 5np.random.seed(0)print(np.random.random(5))[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548]
No matter how many times you execute the above code you get the same random numbers every time. To know the difference just comment on the code (#) and then see the difference. Let us explore the seed method to a bit more extent.
For example, if you use seed(1) and then generate some random numbers they will be the same with the ones you generate later on but with the same seed (1) as shown below.
import numpy as np# Create a random number arrays of size 5np.random.seed(1)print(np.random.random(5))[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01 1.46755891e-01]print(np.random.random(5))# Different random numbers would be generated now[0.09233859 0.18626021 0.34556073 0.39676747 0.53881673]np.random.seed(1)print(np.random.random(5))# Same random numbers would be generated same as the first time - Due to seed[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01 1.46755891e-01]
Same seed same random numbers ensure “Reproducibility” — Quora.com
Also, the range of the seed is from 0 and 2**32–1. Don’t just use negative numbers as the seed value, if you do so you will get an error as shown below:
import numpy as npnp.random.seed(-1)-------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-9-bfd0c22f2d0a> in <module>()----> 1 np.random.seed(-1)mtrand.pyx in numpy.random.mtrand.RandomState.seed()mt19937.pyx in numpy.random.mt19937.MT19937._legacy_seeding()mt19937.pyx in numpy.random.mt19937.MT19937._legacy_seeding()ValueError: Seed must be between 0 and 2**32 - 1
Normal Distribution → Is Also known as the Gaussian Distribution, a continuous probability distribution for a real-valued random variable. It is also known as a symmetric distribution where most of the values cluster at the center of the peak. The standard deviation determines the spread.
The NumPy package library provides us a uniform distribution method to generate random numbers called numpy.random.normal. The syntax is almost the same as the uniform distribution but you need to add two more vital data here known as the mean and the standard deviation.
import numpy as np# Create a 3x3 array of normally distributed random values# with mean 0 and standard deviation 1print(np.random.normal(0, 1, (3, 3)))[[-0.56651023 0.7299756 0.37299379] [ 0.53381091 -0.0919733 1.91382039] [ 0.33079713 1.14194252 -1.12959516]]
5. Creating an identity matrix using numpy array
An identity matrix is a matrix where the principal diagonal elements are 1 and the other elements except the principal diagonal elements are 0. The numpy package library provides a method to generate an identity matrix called the eye. An identity matrix is a square matrix meaning it has equal rows and columns.
import numpy as np# Create a identity matrix of 4 rows and 4 columnsprint(np.eye(4))[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]
The number 4 represents the rows and columns since it is a square matrix we only need to specify the value once (4 in this case).
This is the end of this tutorial “How to create NumPy arrays from scratch?”, this is just the introductory tutorial for NumPy Package library. However, much more complex concepts of the NumPy package library will be discussed in the upcoming tutorials. Thank you guys for spending your time reading my tutorial. I hope you enjoyed it. If you have any doubts related to NumPy, then the comment section is all yours. Until then Goodbye, See you have a good day.
|
[
{
"code": null,
"e": 459,
"s": 172,
"text": "Regardless of the data, the first step in analyzing them is transforming them into an array of numbers. The fundamental process of doing data science is efficiently is storing and manipulating numerical arrays. Because of this Python has specialized tools for handling numerical arrays:"
},
{
"code": null,
"e": 487,
"s": 459,
"text": "NumPy PackagePandas Package"
},
{
"code": null,
"e": 501,
"s": 487,
"text": "NumPy Package"
},
{
"code": null,
"e": 516,
"s": 501,
"text": "Pandas Package"
},
{
"code": null,
"e": 717,
"s": 516,
"text": "This tutorial only focuses on the NumPy package. However, Pandas package documentation will be provided in the latter days. The entire code for the tutorial can be found on my GitHub Repository below:"
},
{
"code": null,
"e": 728,
"s": 717,
"text": "github.com"
},
{
"code": null,
"e": 1003,
"s": 728,
"text": "NumPy stands for Numerical Python. NumPy provides an efficient way to store and operate on dense data buffers. With the help of the NumPy library, we can create and operate with arrays to store the data. In some ways, NumPy’s arrays are like Python’s list built-in function."
},
{
"code": null,
"e": 1419,
"s": 1003,
"text": "Let’s get started. You can execute the below programs in your favorite python editors like PyCharm, Sublime Text, or Notebooks like Jupyter and Google Colab. It's basically your preference to choose an IDE of your choice. I am using Google Colab to write my code because it gives me tons of options to provides good documentation. Also, visit the NumPy website to get more guidelines about the installation process."
},
{
"code": null,
"e": 1616,
"s": 1419,
"text": "Once you have installed the NumPy on your IDE you need to import it. It’s often a good practice to check the version of the library. So to install the NumPy library you need to use the below code."
},
{
"code": null,
"e": 1659,
"s": 1616,
"text": "import numpyprint(numpy.__version__)1.17.4"
},
{
"code": null,
"e": 2025,
"s": 1659,
"text": "Just make sure that you the latest NumPy version to use all the features and options. Rather than using “numpy” we can use an alias as “np”. This is called “Aliasing”. Now the point of using an alias is we can use “np” rather “numpy” which is long to type every time when we use its methods. So creating an alias and checking the version can be done as shown below:"
},
{
"code": null,
"e": 2071,
"s": 2025,
"text": "import numpy as npprint(np.__version__)1.17.4"
},
{
"code": null,
"e": 2131,
"s": 2071,
"text": "From now on we can use “np” rather than “numpy” every time."
},
{
"code": null,
"e": 2343,
"s": 2131,
"text": "Python provides several different options for storing efficient, fixed-type data. Python has a built-in array module called “array” which is used to create arrays of uniform type. This was its main disadvantage."
},
{
"code": null,
"e": 2442,
"s": 2343,
"text": "import array# Creating an arrayprint(array.array('i', [1, 2, 3, 4, 5]))array('i', [1, 2, 3, 4, 5])"
},
{
"code": null,
"e": 2575,
"s": 2442,
"text": "The “i” here indicates the integer data. We cannot try to store other types of data in the array module. It often leads to an error."
},
{
"code": null,
"e": 2906,
"s": 2575,
"text": "import array# Creating an arrayprint(array.array('i', [1, 2.0, 3, 4, 5]))--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-25-49d63cb1f570> in <module>()----> 1 array.array('i', [1, 2.0, 3, 4, 5])TypeError: integer argument expected, got float"
},
{
"code": null,
"e": 3109,
"s": 2906,
"text": "However, Python’s array module provides efficient storage of array-based data. But NumPy arrays can perform efficient operations on that type of data. There are two ways that we can create NumPy arrays:"
},
{
"code": null,
"e": 3185,
"s": 3109,
"text": "Creating a NumPy array from Python ListsCreating a NumPy array from scratch"
},
{
"code": null,
"e": 3226,
"s": 3185,
"text": "Creating a NumPy array from Python Lists"
},
{
"code": null,
"e": 3262,
"s": 3226,
"text": "Creating a NumPy array from scratch"
},
{
"code": null,
"e": 3325,
"s": 3262,
"text": "We can use np.array method to create arrays from python lists."
},
{
"code": null,
"e": 3532,
"s": 3325,
"text": "import numpy as np# Creating a list named \"a\"a = [1, 2, 3, 4, 5]print(type(a))<class 'list'># Creating a numpy array from the listprint(np.array(a))[1 2 3 4 5]print(type(np.array(a)))<class 'numpy.ndarray'>"
},
{
"code": null,
"e": 3681,
"s": 3532,
"text": "The NumPy library is limited to arrays with the same type, if there is a type mismatch then it would upcast if possible. Consider the below example:"
},
{
"code": null,
"e": 3895,
"s": 3681,
"text": "import numpy as np# Creating a list named \"a\"a = [1, 2.0, 3, 4, 5]print(type(a))<class 'list'># Creating a numpy array from the listprint(np.array(a))[1. 2. 3. 4. 5.]print(type(np.array(a)))<class 'numpy.ndarray'>"
},
{
"code": null,
"e": 4165,
"s": 3895,
"text": "So the original list was integers with one floating value but the numpy array upcasted it to all floating-point numbers. The integers are upcasted to floating-point numbers. Below is a small diagram that gives you enough knowledge to understand the upcast and downcast."
},
{
"code": null,
"e": 4265,
"s": 4165,
"text": "Also explicitly setting the data type is also possible. This can be done using the keyword “dtype”."
},
{
"code": null,
"e": 4447,
"s": 4265,
"text": "import numpy as np# Creating a list named \"a\"a = [1, 2, 3, 4, 5]# Creating a numpy array from the listnp.array(a, dtype='float64')print(np.array(a, dtype='float64'))[1. 2. 3. 4. 5.]"
},
{
"code": null,
"e": 4574,
"s": 4447,
"text": "As seen from the above example, the integer type list data is converted into the float type data by using the “dtype” keyword."
},
{
"code": null,
"e": 4669,
"s": 4574,
"text": "Numpy arrays can also be multidimensional (Array within an array). Here’s one way of doing it."
},
{
"code": null,
"e": 4869,
"s": 4669,
"text": "import numpy as np# Creating a list named \"a\"a = [1, 2, 3, 4, 5]# Creating a numpy array from the listnp.array([range(i, i + 4) for i in a])[[1 2 3 4] [2 3 4 5] [3 4 5 6] [4 5 6 7] [5 6 7 8]]"
},
{
"code": null,
"e": 5041,
"s": 4869,
"text": "Hint: Just increment the “i” value in terms of 1 (i+1, 2, 3, 4, ...) by doing so you can increase the dimension of the array too. The above array is treated as 2D — Array."
},
{
"code": null,
"e": 5260,
"s": 5041,
"text": "Numpy arrays are actually used for creating larger arrays. It is more efficient to create large arrays from scratch using the numpy package library. Below are some of the examples of creating numpy arrays from scratch."
},
{
"code": null,
"e": 5308,
"s": 5260,
"text": "Creating an array filled with zeros of length 5"
},
{
"code": null,
"e": 5356,
"s": 5308,
"text": "Creating an array filled with zeros of length 5"
},
{
"code": null,
"e": 5432,
"s": 5356,
"text": "We can do this using the numpy built-in method called zeros as shown below:"
},
{
"code": null,
"e": 5538,
"s": 5432,
"text": "import numpy as np# Creating a numpy array of zeros of length 5print(np.zeros(5, dtype='int'))[0 0 0 0 0]"
},
{
"code": null,
"e": 5914,
"s": 5538,
"text": "There are some standard numpy data types available. I cannot just discuss all of them in one stretch. Most of them are never used. So I will be providing the data types of numpy array in the form of a chart below just use that accordingly. If you don't know how to use the datatypes refer to Explicitly changing the array datatypes above its → dtypes = “name of the datatype”"
},
{
"code": null,
"e": 5956,
"s": 5914,
"text": "2. Creating a 3 x 4 array filled with 1's"
},
{
"code": null,
"e": 6184,
"s": 5956,
"text": "Thanks to NumPy because we don’t have to put the array inside a looping statement (I hate to do that ;)). All you have to do is just mention the rows and the columns that you want your array to have inside the numpy.one method."
},
{
"code": null,
"e": 6342,
"s": 6184,
"text": "import numpy as np# Creating a numpy array of 1’s which should have 3 rows and 4 columnsprint(np.ones((3, 4)))[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]"
},
{
"code": null,
"e": 6392,
"s": 6342,
"text": "So the number 3 → rows and 4 → obviously columns."
},
{
"code": null,
"e": 6445,
"s": 6392,
"text": "3. Filling the numpy arrays with a particular number"
},
{
"code": null,
"e": 6713,
"s": 6445,
"text": "Till now we have seen filling the array with 0’s and 1’s but we should also know that numpy allows us to fill the arrays with any specific number of our choice. We can do this with the help of numpy.full method. For example, let us fill the array with the number 500."
},
{
"code": null,
"e": 6890,
"s": 6713,
"text": "import numpy as np# Creating a numpy array of 500’s which should have 3 rows and 4 columnsprint(np.full((3, 4), 500))[[500 500 500 500] [500 500 500 500] [500 500 500 500]]"
},
{
"code": null,
"e": 6974,
"s": 6890,
"text": "With the help of the full method, we can add any number of our choice to our array."
},
{
"code": null,
"e": 7018,
"s": 6974,
"text": "4. Creating a numpy array of random numbers"
},
{
"code": null,
"e": 7293,
"s": 7018,
"text": "Uniform distribution → It is a probability distribution in which all the outcomes are equally likely. For example, tossing a coin has the probability of uniform distribution because the outcomes are a most likely head or a tail. It’s never going to be both at the same time."
},
{
"code": null,
"e": 7417,
"s": 7293,
"text": "The NumPy package library provides us a uniform distribution method to generate random numbers called numpy.random.uniform."
},
{
"code": null,
"e": 7654,
"s": 7417,
"text": "import numpy as np# Create a 3x3 array of uniformly distributed # random values between 0 and 1print(np.random.random((3, 3)))[[0.89865866 0.71138067 0.85067426] [0.53568422 0.32887081 0.97449983] [0.48130729 0.15841703 0.57756513]]"
},
{
"code": null,
"e": 7969,
"s": 7654,
"text": "Also, the numpy package library has a seed generator along with the random number generator, with the help of the seed method we can control the sequence of the random numbers being generated. Most of them don’t know the specialty of the seed method and its purpose. To know more about the seed method refer below."
},
{
"code": null,
"e": 8048,
"s": 7969,
"text": "If we use the seed every time then we get the same sequence of random numbers."
},
{
"code": null,
"e": 8110,
"s": 8048,
"text": "So, the same seed yields the same sequence of random numbers."
},
{
"code": null,
"e": 8268,
"s": 8110,
"text": "import numpy as np# Create a random number arrays of size 5np.random.seed(0)print(np.random.random(5))[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548]"
},
{
"code": null,
"e": 8498,
"s": 8268,
"text": "No matter how many times you execute the above code you get the same random numbers every time. To know the difference just comment on the code (#) and then see the difference. Let us explore the seed method to a bit more extent."
},
{
"code": null,
"e": 8669,
"s": 8498,
"text": "For example, if you use seed(1) and then generate some random numbers they will be the same with the ones you generate later on but with the same seed (1) as shown below."
},
{
"code": null,
"e": 9177,
"s": 8669,
"text": "import numpy as np# Create a random number arrays of size 5np.random.seed(1)print(np.random.random(5))[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01 1.46755891e-01]print(np.random.random(5))# Different random numbers would be generated now[0.09233859 0.18626021 0.34556073 0.39676747 0.53881673]np.random.seed(1)print(np.random.random(5))# Same random numbers would be generated same as the first time - Due to seed[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01 1.46755891e-01]"
},
{
"code": null,
"e": 9244,
"s": 9177,
"text": "Same seed same random numbers ensure “Reproducibility” — Quora.com"
},
{
"code": null,
"e": 9397,
"s": 9244,
"text": "Also, the range of the seed is from 0 and 2**32–1. Don’t just use negative numbers as the seed value, if you do so you will get an error as shown below:"
},
{
"code": null,
"e": 9858,
"s": 9397,
"text": "import numpy as npnp.random.seed(-1)-------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-9-bfd0c22f2d0a> in <module>()----> 1 np.random.seed(-1)mtrand.pyx in numpy.random.mtrand.RandomState.seed()mt19937.pyx in numpy.random.mt19937.MT19937._legacy_seeding()mt19937.pyx in numpy.random.mt19937.MT19937._legacy_seeding()ValueError: Seed must be between 0 and 2**32 - 1"
},
{
"code": null,
"e": 10148,
"s": 9858,
"text": "Normal Distribution → Is Also known as the Gaussian Distribution, a continuous probability distribution for a real-valued random variable. It is also known as a symmetric distribution where most of the values cluster at the center of the peak. The standard deviation determines the spread."
},
{
"code": null,
"e": 10420,
"s": 10148,
"text": "The NumPy package library provides us a uniform distribution method to generate random numbers called numpy.random.normal. The syntax is almost the same as the uniform distribution but you need to add two more vital data here known as the mean and the standard deviation."
},
{
"code": null,
"e": 10691,
"s": 10420,
"text": "import numpy as np# Create a 3x3 array of normally distributed random values# with mean 0 and standard deviation 1print(np.random.normal(0, 1, (3, 3)))[[-0.56651023 0.7299756 0.37299379] [ 0.53381091 -0.0919733 1.91382039] [ 0.33079713 1.14194252 -1.12959516]]"
},
{
"code": null,
"e": 10740,
"s": 10691,
"text": "5. Creating an identity matrix using numpy array"
},
{
"code": null,
"e": 11052,
"s": 10740,
"text": "An identity matrix is a matrix where the principal diagonal elements are 1 and the other elements except the principal diagonal elements are 0. The numpy package library provides a method to generate an identity matrix called the eye. An identity matrix is a square matrix meaning it has equal rows and columns."
},
{
"code": null,
"e": 11200,
"s": 11052,
"text": "import numpy as np# Create a identity matrix of 4 rows and 4 columnsprint(np.eye(4))[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]"
},
{
"code": null,
"e": 11330,
"s": 11200,
"text": "The number 4 represents the rows and columns since it is a square matrix we only need to specify the value once (4 in this case)."
}
] |
How to get the Android Emulator's IP address using Kotlin?
|
This example demonstrates how to get the Android Emulator's IP address 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnGetIPAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:text="Get IP Address" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.net.wifi.WifiManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.text.format.Formatter
class MainActivity : AppCompatActivity() {
lateinit var button: Button
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
button = findViewById(R.id.btnGetIPAddress)
button.setOnClickListener {
val wifiManager: WifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
val ip: String = Formatter.formatIpAddress(wifiManager.connectionInfo.ipAddress)
textView.text = String.format("IP Address: %s", ip)
}
}
}
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">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<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.
Click here to download the project code.
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "This example demonstrates how to get the Android Emulator's IP address using Kotlin."
},
{
"code": null,
"e": 1276,
"s": 1147,
"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": 1341,
"s": 1276,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2604,
"s": 1341,
"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 <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/btnGetIPAddress\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/textView\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Get IP Address\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2659,
"s": 2604,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3542,
"s": 2659,
"text": "import android.net.wifi.WifiManager\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport android.text.format.Formatter\nclass MainActivity : AppCompatActivity() {\n lateinit var button: Button\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n button = findViewById(R.id.btnGetIPAddress)\n button.setOnClickListener {\n val wifiManager: WifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager\n val ip: String = Formatter.formatIpAddress(wifiManager.connectionInfo.ipAddress)\n textView.text = String.format(\"IP Address: %s\", ip)\n }\n }\n}"
},
{
"code": null,
"e": 3597,
"s": 3542,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4339,
"s": 3597,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>\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": 4689,
"s": 4339,
"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."
},
{
"code": null,
"e": 4730,
"s": 4689,
"text": "Click here to download the project code."
}
] |
Horizontally Flip a Binary Matrix - GeeksforGeeks
|
18 Apr, 2022
Given a binary matrix. The task is to flip the matrix horizontally(find the image of the matrix), then invert it.
Note:
To flip a matrix horizontally means that reversing each row of the matrix. For example, flipping [1, 1, 0, 0] horizontally results in [0, 0, 1, 1].
To invert a matrix means that replacing each 0 by 1 and vice-versa. For example, inverting [0, 0, 1] results in [1, 1, 0].
Examples:
Input: mat[][] = [[1, 1, 0],
[1, 0, 1],
[0, 0, 0]]
Output: [[1, 0, 0],
[0, 1, 0],
[1, 1, 1]]
Explanation:
First reverse each row: [[0, 1, 1], [1, 0, 1], [0, 0, 0]]
Then, invert the image: [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
Input: mat[][] = [[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 1, 1, 1],
[1, 0, 1, 0]]
Output: [[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 1],
[1, 0, 1, 0]]
Explanation:
First reverse each row:
[[0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 1, 0], [0, 1, 0, 1]].
Then invert the image:
[[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]]
Approach: We can do this in-place. On observing carefully, it can be deduced that in each row in the final matrix, the i-th value from the left is equal to the inverse of the i-th value from the right of the input binary matrix.
Thus, we use (Column + 1) / 2 (with floor division) to iterate over all indexes in the first half of the row, including the centre and updating the answer accordingly.
Below is the implementation of above approach:
Python3
# Python3 implementation of above approach# Function to return final Image def flipped_Invert_Image(mat): for row in mat: for i in range((len(row) + 1) // 2): row[i] = row[len(row) - 1 - i] ^ 1 row[len(row) - 1 - i] = row[i] ^ 1 # return Flipped and Inverted image return mat # Driver codemat = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]] print(flipped_Invert_Image(mat))
[[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 0]]
Time Complexity: O(N*M), where N is the number of rows and M is the number of columns in the given binary matrix.
C++14
Python3
//c++ program to flip the binary image horizontally#include<bits/stdc++.h>using namespace std;//function to flip the matrix using two pointer techniquevector<vector<int>> flip_matrix(vector<vector<int>>matrix){ for(int i=0;i<matrix.size();i++) { int left = 0; int right = matrix[i].size()-1; while( left <= right ) { //conditions executes if compared elements are not equal if(matrix[i][left] == matrix[i][right]) { // if element is 0 it becomes 1 if not it becomes 0 matrix[i][left] = 1-matrix[i][left]; matrix[i][right] = matrix[i][left]; } left++; right--; } } //return matrix return matrix;}//Drive codeint main(){ vector<vector<int>>matrix={{1,1,0},{1,0,1},{0,0,0}}; vector<vector<int>>v=flip_matrix(matrix); for(int i=0;i<matrix.size();i++) { for(int j=0;j<matrix[i].size();j++) { cout<<v[i][j]<<" "; } cout<<'\n'; }}
# Python program to flip the binary image horizontally # function to flip the matrix using two pointer techniquedef flip_matrix(matrix): for i in range(len(matrix)): left,right = 0,len(matrix[i])-1 while(left <= right): # conditions executes if compared elements are not equal if(matrix[i][left] == matrix[i][right]): # if element is 0 it becomes 1 if not it becomes 0 matrix[i][left] = 1-matrix[i][left] matrix[i][right] = matrix[i][left] left += 1 right -= 1 # return matrix return matrix # Drive codematrix = [[1, 1, 0], [1, 0, 1], [0, 0, 0]]v = flip_matrix(matrix) for i in range(len(matrix)): for j in range(len(matrix[i])): print(v[i][j],end = " ") print() # This code is contributed by shinjanpatra
surinderdawra388
bunny09262002
inversion
Backtracking
Bit Magic
Mathematical
Mathematical
Bit Magic
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
The Knight's tour problem | Backtracking-1
Backtracking | Introduction
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Print all paths from a given source to a destination
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 24617,
"s": 24589,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24732,
"s": 24617,
"text": "Given a binary matrix. The task is to flip the matrix horizontally(find the image of the matrix), then invert it. "
},
{
"code": null,
"e": 24739,
"s": 24732,
"text": "Note: "
},
{
"code": null,
"e": 24887,
"s": 24739,
"text": "To flip a matrix horizontally means that reversing each row of the matrix. For example, flipping [1, 1, 0, 0] horizontally results in [0, 0, 1, 1]."
},
{
"code": null,
"e": 25010,
"s": 24887,
"text": "To invert a matrix means that replacing each 0 by 1 and vice-versa. For example, inverting [0, 0, 1] results in [1, 1, 0]."
},
{
"code": null,
"e": 25021,
"s": 25010,
"text": "Examples: "
},
{
"code": null,
"e": 25706,
"s": 25021,
"text": "Input: mat[][] = [[1, 1, 0], \n [1, 0, 1], \n [0, 0, 0]]\nOutput: [[1, 0, 0], \n [0, 1, 0], \n [1, 1, 1]]\nExplanation: \nFirst reverse each row: [[0, 1, 1], [1, 0, 1], [0, 0, 0]]\nThen, invert the image: [[1, 0, 0], [0, 1, 0], [1, 1, 1]]\n\nInput: mat[][] = [[1, 1, 0, 0], \n [1, 0, 0, 1], \n [0, 1, 1, 1], \n [1, 0, 1, 0]]\nOutput: [[1, 1, 0, 0], \n [0, 1, 1, 0], \n [0, 0, 0, 1], \n [1, 0, 1, 0]]\nExplanation: \nFirst reverse each row: \n[[0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 1, 0], [0, 1, 0, 1]].\nThen invert the image:\n[[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]]"
},
{
"code": null,
"e": 25935,
"s": 25706,
"text": "Approach: We can do this in-place. On observing carefully, it can be deduced that in each row in the final matrix, the i-th value from the left is equal to the inverse of the i-th value from the right of the input binary matrix."
},
{
"code": null,
"e": 26103,
"s": 25935,
"text": "Thus, we use (Column + 1) / 2 (with floor division) to iterate over all indexes in the first half of the row, including the centre and updating the answer accordingly."
},
{
"code": null,
"e": 26151,
"s": 26103,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26159,
"s": 26151,
"text": "Python3"
},
{
"code": "# Python3 implementation of above approach# Function to return final Image def flipped_Invert_Image(mat): for row in mat: for i in range((len(row) + 1) // 2): row[i] = row[len(row) - 1 - i] ^ 1 row[len(row) - 1 - i] = row[i] ^ 1 # return Flipped and Inverted image return mat # Driver codemat = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]] print(flipped_Invert_Image(mat))",
"e": 26585,
"s": 26159,
"text": null
},
{
"code": null,
"e": 26642,
"s": 26585,
"text": "[[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 0]]"
},
{
"code": null,
"e": 26759,
"s": 26644,
"text": "Time Complexity: O(N*M), where N is the number of rows and M is the number of columns in the given binary matrix. "
},
{
"code": null,
"e": 26765,
"s": 26759,
"text": "C++14"
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Python3"
},
{
"code": "//c++ program to flip the binary image horizontally#include<bits/stdc++.h>using namespace std;//function to flip the matrix using two pointer techniquevector<vector<int>> flip_matrix(vector<vector<int>>matrix){ for(int i=0;i<matrix.size();i++) { int left = 0; int right = matrix[i].size()-1; while( left <= right ) { //conditions executes if compared elements are not equal if(matrix[i][left] == matrix[i][right]) { // if element is 0 it becomes 1 if not it becomes 0 matrix[i][left] = 1-matrix[i][left]; matrix[i][right] = matrix[i][left]; } left++; right--; } } //return matrix return matrix;}//Drive codeint main(){ vector<vector<int>>matrix={{1,1,0},{1,0,1},{0,0,0}}; vector<vector<int>>v=flip_matrix(matrix); for(int i=0;i<matrix.size();i++) { for(int j=0;j<matrix[i].size();j++) { cout<<v[i][j]<<\" \"; } cout<<'\\n'; }}",
"e": 27916,
"s": 26773,
"text": null
},
{
"code": "# Python program to flip the binary image horizontally # function to flip the matrix using two pointer techniquedef flip_matrix(matrix): for i in range(len(matrix)): left,right = 0,len(matrix[i])-1 while(left <= right): # conditions executes if compared elements are not equal if(matrix[i][left] == matrix[i][right]): # if element is 0 it becomes 1 if not it becomes 0 matrix[i][left] = 1-matrix[i][left] matrix[i][right] = matrix[i][left] left += 1 right -= 1 # return matrix return matrix # Drive codematrix = [[1, 1, 0], [1, 0, 1], [0, 0, 0]]v = flip_matrix(matrix) for i in range(len(matrix)): for j in range(len(matrix[i])): print(v[i][j],end = \" \") print() # This code is contributed by shinjanpatra",
"e": 28813,
"s": 27916,
"text": null
},
{
"code": null,
"e": 28830,
"s": 28813,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28844,
"s": 28830,
"text": "bunny09262002"
},
{
"code": null,
"e": 28854,
"s": 28844,
"text": "inversion"
},
{
"code": null,
"e": 28867,
"s": 28854,
"text": "Backtracking"
},
{
"code": null,
"e": 28877,
"s": 28867,
"text": "Bit Magic"
},
{
"code": null,
"e": 28890,
"s": 28877,
"text": "Mathematical"
},
{
"code": null,
"e": 28903,
"s": 28890,
"text": "Mathematical"
},
{
"code": null,
"e": 28913,
"s": 28903,
"text": "Bit Magic"
},
{
"code": null,
"e": 28926,
"s": 28913,
"text": "Backtracking"
},
{
"code": null,
"e": 29024,
"s": 28926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29033,
"s": 29024,
"text": "Comments"
},
{
"code": null,
"e": 29046,
"s": 29033,
"text": "Old Comments"
},
{
"code": null,
"e": 29089,
"s": 29046,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 29117,
"s": 29089,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 29153,
"s": 29117,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 29188,
"s": 29153,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 29241,
"s": 29188,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 29268,
"s": 29241,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29314,
"s": 29268,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29382,
"s": 29314,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 29411,
"s": 29382,
"text": "Count set bits in an integer"
}
] |
Jackson Annotations - @JsonDeserialize
|
@JsonDeserialize is used to specify custom deserializer to unmarshall the json object.
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class JacksonTester {
public static void main(String args[]) throws ParseException{
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mark\",\"dateOfBirth\":\"20-12-1984\"}";
try {
Student student = mapper
.readerFor(Student.class)
.readValue(jsonString);
System.out.println(student.dateOfBirth);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
public String name;
@JsonDeserialize(using = CustomDateDeserializer.class)
public Date dateOfBirth;
}
class CustomDateDeserializer extends StdDeserializer<Date> {
private static final long serialVersionUID = 1L;
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<Date> t) {
super(t);
}
@Override
public Date deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
String date = parser.getText();
try {
return formatter.parse(date);
}
catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
Thu Dec 20 00:00:00 IST 1984
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2562,
"s": 2475,
"text": "@JsonDeserialize is used to specify custom deserializer to unmarshall the json object."
},
{
"code": null,
"e": 4359,
"s": 2562,
"text": "import java.io.IOException; \nimport java.text.ParseException; \nimport java.text.SimpleDateFormat; \nimport java.util.Date; \n\nimport com.fasterxml.jackson.core.JsonParser; \nimport com.fasterxml.jackson.core.JsonProcessingException; \nimport com.fasterxml.jackson.databind.DeserializationContext; \nimport com.fasterxml.jackson.databind.ObjectMapper; \nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize; \nimport com.fasterxml.jackson.databind.deser.std.StdDeserializer; \n\npublic class JacksonTester {\n public static void main(String args[]) throws ParseException{ \n ObjectMapper mapper = new ObjectMapper(); \n String jsonString = \"{\\\"name\\\":\\\"Mark\\\",\\\"dateOfBirth\\\":\\\"20-12-1984\\\"}\"; \n try { \n Student student = mapper\n .readerFor(Student.class) \n .readValue(jsonString); \n System.out.println(student.dateOfBirth); \n } \n catch (IOException e) { \n e.printStackTrace(); \n } \n }\n}\nclass Student {\n public String name; \n @JsonDeserialize(using = CustomDateDeserializer.class) \n public Date dateOfBirth; \n}\nclass CustomDateDeserializer extends StdDeserializer<Date> {\n private static final long serialVersionUID = 1L;\n private static SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n public CustomDateDeserializer() { \n this(null); \n } \n public CustomDateDeserializer(Class<Date> t) { \n super(t); \n } \n @Override \n public Date deserialize(JsonParser parser, DeserializationContext context) \n throws IOException, JsonProcessingException { \n \n String date = parser.getText(); \n try { \n return formatter.parse(date); \n } \n catch (ParseException e) { \n e.printStackTrace(); \n } \n return null; \n } \n}"
},
{
"code": null,
"e": 4390,
"s": 4359,
"text": "Thu Dec 20 00:00:00 IST 1984 \n"
},
{
"code": null,
"e": 4397,
"s": 4390,
"text": " Print"
},
{
"code": null,
"e": 4408,
"s": 4397,
"text": " Add Notes"
}
] |
Print the string after the specified character has occurred given no. of times in C Program
|
Task is to print the given after the specified character occurrence for given number of times which is specified by the user
Input : string = {“I am harsh vaid “}
Char =’a’
Count =2
Output : rsh vaid
It means user specified character ‘a’ and its occurrence 2 so the output string should be displayed after two occurrences of a.
START
Step 1 -> input character in ch(e.g. ‘a’) and count(e.g. 2) as int
Step 2 -> declare and initialize n with size of a string by sizeof(string)/sizeof(string[0])
Step 3 - > Loop For i to 0 and i<n and i++
IF count > 0
IF string[i]==ch
Count=count-1
End IF
Continue
End IF
Else
Print string[i]
End Else
Step 4 -> End For
STOP
#include <stdio.h>
int main(int argc, char const *argv[]) {
char string[] = {"I am Harsh Vaid"};
char ch = 'a';
int i, count = 2;
int n = sizeof(string)/sizeof(string[0]);
for( i = 0; i < n; i++ ) {
if(count>0) {
if(string[i]==ch) {
count--;
}
continue;
}
else
printf("%c", string[i]);
}
return 0;
}
If we run above program then it will generate following output
rsh Vaid
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "Task is to print the given after the specified character occurrence for given number of times which is specified by the user"
},
{
"code": null,
"e": 1268,
"s": 1187,
"text": "Input : string = {“I am harsh vaid “}\n Char =’a’\n Count =2\nOutput : rsh vaid"
},
{
"code": null,
"e": 1396,
"s": 1268,
"text": "It means user specified character ‘a’ and its occurrence 2 so the output string should be displayed after two occurrences of a."
},
{
"code": null,
"e": 1770,
"s": 1396,
"text": "START\nStep 1 -> input character in ch(e.g. ‘a’) and count(e.g. 2) as int\nStep 2 -> declare and initialize n with size of a string by sizeof(string)/sizeof(string[0])\nStep 3 - > Loop For i to 0 and i<n and i++\n IF count > 0\n IF string[i]==ch\n Count=count-1\n End IF\n Continue\n End IF\n Else\n Print string[i]\n End Else\nStep 4 -> End For\nSTOP"
},
{
"code": null,
"e": 2154,
"s": 1770,
"text": "#include <stdio.h>\nint main(int argc, char const *argv[]) {\n char string[] = {\"I am Harsh Vaid\"};\n char ch = 'a';\n int i, count = 2;\n int n = sizeof(string)/sizeof(string[0]);\n for( i = 0; i < n; i++ ) {\n if(count>0) {\n if(string[i]==ch) {\n count--;\n }\n continue;\n }\n else\n printf(\"%c\", string[i]);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2217,
"s": 2154,
"text": "If we run above program then it will generate following output"
},
{
"code": null,
"e": 2226,
"s": 2217,
"text": "rsh Vaid"
}
] |
How to take MySQL database backup using MySQL Workbench?
|
To make MySQL database backup using MySQL, first we need to install MySQL Workbench. Follow the below link to install MySQL workbench.
https://dev.mysql.com/downloads/windows/installer/8.0.html
After installing successfully, we need to open MySQL Workbench. Choose the option “Data Export”. Here is the snapshot.
Select the database you want to export. You can also set the path here where you want to save the database.
After successful completion, you can see the following screenshot.
You have successfully created a backup of the above database. The following message is now visible.
Export of E:\BackupDatabase has finished
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "To make MySQL database backup using MySQL, first we need to install MySQL Workbench. Follow the below link to install MySQL workbench."
},
{
"code": null,
"e": 1256,
"s": 1197,
"text": "https://dev.mysql.com/downloads/windows/installer/8.0.html"
},
{
"code": null,
"e": 1375,
"s": 1256,
"text": "After installing successfully, we need to open MySQL Workbench. Choose the option “Data Export”. Here is the snapshot."
},
{
"code": null,
"e": 1483,
"s": 1375,
"text": "Select the database you want to export. You can also set the path here where you want to save the database."
},
{
"code": null,
"e": 1550,
"s": 1483,
"text": "After successful completion, you can see the following screenshot."
},
{
"code": null,
"e": 1650,
"s": 1550,
"text": "You have successfully created a backup of the above database. The following message is now visible."
},
{
"code": null,
"e": 1691,
"s": 1650,
"text": "Export of E:\\BackupDatabase has finished"
}
] |
How to set the Foreground Color of a ListBox in C#? - GeeksforGeeks
|
11 Jul, 2019
In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the foreground color of the ListBox using ForeColor Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the foreground color of the ListBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ListBox control to set the foreground color of the ListBox.Output:
Output:
2. RunTime: It is a little bit trickier than the above method. In this method, you can set the foreground color of the ListBox control programmatically with the help of given syntax:
public override System.Drawing.Color ForeColor { get; set; }
Here, Color indicates the foreground color of the ListBox. The following steps show how to set the foreground color of the ListBox dynamically:
Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor
ListBox mylist = new ListBox();
// Creating ListBox using ListBox class constructor
ListBox mylist = new ListBox();
Step 2: After creating ListBox, set the ForeColor property of the ListBox provided by the ListBox class.// Setting the foreground color
mylist.ForeColor = Color.Purple;
// Setting the foreground color
mylist.ForeColor = Color.Purple;
Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form
this.Controls.Add(mylist);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output:
// Add this ListBox to the form
this.Controls.Add(mylist);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 23793,
"s": 23765,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 24186,
"s": 23793,
"text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the foreground color of the ListBox using ForeColor Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways:"
},
{
"code": null,
"e": 24300,
"s": 24186,
"text": "1. Design-Time: It is the easiest way to set the foreground color of the ListBox as shown in the following steps:"
},
{
"code": null,
"e": 24416,
"s": 24300,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24595,
"s": 24416,
"text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 24727,
"s": 24595,
"text": "Step 3: After drag and drop you will go to the properties of the ListBox control to set the foreground color of the ListBox.Output:"
},
{
"code": null,
"e": 24735,
"s": 24727,
"text": "Output:"
},
{
"code": null,
"e": 24918,
"s": 24735,
"text": "2. RunTime: It is a little bit trickier than the above method. In this method, you can set the foreground color of the ListBox control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 24979,
"s": 24918,
"text": "public override System.Drawing.Color ForeColor { get; set; }"
},
{
"code": null,
"e": 25123,
"s": 24979,
"text": "Here, Color indicates the foreground color of the ListBox. The following steps show how to set the foreground color of the ListBox dynamically:"
},
{
"code": null,
"e": 25299,
"s": 25123,
"text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n"
},
{
"code": null,
"e": 25384,
"s": 25299,
"text": "// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n"
},
{
"code": null,
"e": 25554,
"s": 25384,
"text": "Step 2: After creating ListBox, set the ForeColor property of the ListBox provided by the ListBox class.// Setting the foreground color\nmylist.ForeColor = Color.Purple;\n"
},
{
"code": null,
"e": 25620,
"s": 25554,
"text": "// Setting the foreground color\nmylist.ForeColor = Color.Purple;\n"
},
{
"code": null,
"e": 26604,
"s": 25620,
"text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(mylist);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output:"
},
{
"code": null,
"e": 26664,
"s": 26604,
"text": "// Add this ListBox to the form\nthis.Controls.Add(mylist);\n"
},
{
"code": null,
"e": 26673,
"s": 26664,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}",
"e": 27510,
"s": 26673,
"text": null
},
{
"code": null,
"e": 27518,
"s": 27510,
"text": "Output:"
},
{
"code": null,
"e": 27521,
"s": 27518,
"text": "C#"
},
{
"code": null,
"e": 27619,
"s": 27521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27628,
"s": 27619,
"text": "Comments"
},
{
"code": null,
"e": 27641,
"s": 27628,
"text": "Old Comments"
},
{
"code": null,
"e": 27664,
"s": 27641,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27692,
"s": 27664,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27738,
"s": 27692,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27753,
"s": 27738,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27793,
"s": 27753,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27811,
"s": 27793,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27842,
"s": 27811,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27865,
"s": 27842,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27887,
"s": 27865,
"text": "C# | Class and Object"
}
] |
How to create an exponential curve in R?
|
To create an exponential curve, we can use exp function inside the plot function for the variable that we want to plot. For example, if we have a vector x then the exponential curve for the vector x can be created by using plot(x,exp(x)). We can use the exponential function for the variable that is appropriate based on the objective of the analysis, here we have shown only an example of how it works.
Live Demo
> x<-rpois(1000,5)
> plot(x,exp(x))
Live Demo
> y<-runif(50,2,8)
> plot(y,exp(y))
|
[
{
"code": null,
"e": 1466,
"s": 1062,
"text": "To create an exponential curve, we can use exp function inside the plot function for the variable that we want to plot. For example, if we have a vector x then the exponential curve for the vector x can be created by using plot(x,exp(x)). We can use the exponential function for the variable that is appropriate based on the objective of the analysis, here we have shown only an example of how it works."
},
{
"code": null,
"e": 1476,
"s": 1466,
"text": "Live Demo"
},
{
"code": null,
"e": 1512,
"s": 1476,
"text": "> x<-rpois(1000,5)\n> plot(x,exp(x))"
},
{
"code": null,
"e": 1522,
"s": 1512,
"text": "Live Demo"
},
{
"code": null,
"e": 1558,
"s": 1522,
"text": "> y<-runif(50,2,8)\n> plot(y,exp(y))"
}
] |
Clojure - Databases
|
In order to use the database functionality, please ensure to first download the jdbc files from the following url − https://codeload.github.com/clojure/java.jdbc/zip/master
You will find a zip file which has the necessary drivers for Clojure to have the ability to connect to databases. Once the zip file is extracted, ensure to add the unzipped location to your classpath.
The main file for database connectivity is a file called jdbc.clj in the location clojure/java.
The clojure jdbc connector supports a wide variety of databases, some of which are the following.
H2Database
Oracle
Microsoft SQL Server
MySQL
PostgreSQL
In our example, we are going to use MySQL DB as an example.
The following operations are possible in Clojure with regards to Databases.
Before connecting to a MySQL database, make sure of the following −
You have created a database TESTDB.
You have created a database TESTDB.
You have created a table EMPLOYEE in TESTDB.
You have created a table EMPLOYEE in TESTDB.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
User ID "testuser" and password "test123" are set to access TESTDB.
Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath.
Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath.
You have gone through MySQL tutorial to understand MySQL Basics.
You have gone through MySQL tutorial to understand MySQL Basics.
Following is the syntax to create a connection in Clojure.
(def connection_name {
:subprotocol “protocol_name”
:subname “Location of mysql DB”
:user “username” :password “password” })
Parameters − ‘connection_name’ is the name to be given to the connection. ‘subprotocol’ is the protocol to be used for the connection. By default we will be using the mysql protocol. ‘subname’ is the url to connect to the mysql db along with the database name. ‘user’ is the username used to connect to the database. ‘password’ is the password to be used to connect to the database.
Return Value − This will provide a connection string, which can be used in subsequent mysql operations.
The following example shows how to connect to the tables in the information schema and retrieve all the data in the table.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/information_schema"
:user "root"
:password "shakinstev"})
(println (sql/query mysql-db
["select table_name from tables"]
:row-fn :table_name)))
Querying data on any database means to fetch some useful information from the database. Once a database connection is established, you are ready to make a query into this database. Following is the syntax by which data can be queried using Clojure.
clojure.java.jdbc/query dbconn
["query"]
:row-fn :sequence
Parameters − ‘dbconn’ is the name of the connection used to connect to the database. ‘query’ is the query string used to fetch data from the database. ‘:sequence’ is by default all the rows of data fetched from the database and is returned as a sequence. The necessary operations on the sequence can then be done to see what data has been fetched.
Return Value − This will return a sequence, which will have the rows of data from the query operation.
The following example shows how to connect to the employee table and fetch the first_name column of the rows in the table.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/testdb"
:user "root"
:password "shakinstev"})
(println (sql/query mysql-db
["select first_name from employee"]
:row-fn :first_name)))
From the above code, we can see that
The query of “select first_name from employee” is passed as the query string.
The query of “select first_name from employee” is passed as the query string.
The :first_name is the sequence, which is returned as a result of the fetch operation.
The :first_name is the sequence, which is returned as a result of the fetch operation.
If we assume that there is just one row in our database which contains a first_name value of John, following will be the output of the above program.
(John)
It is required when you want to create your records into a database table. Following is the syntax by which data can be inserted using Clojure. This is done by using the ‘insert!’ function.
clojure.java.jdbc/insert!
:table_name {:column_namen columnvalue}
Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘{:column_namen columnvalue }’ is a map of all the column names and values, which need to be added as a row in the table.
Return Value − This will return nil if the insertion is made successfully.
The following example shows how to insert a record into the employee table in the testdb database.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/testdb"
:user "root"
:password "shakinstev"})
(sql/insert! mysql-db
:employee {:first_name "John" :last_name "Mark" :sex "M" :age 30 :income 30}))
If you now check your MySQL database and the employee table, you will see that the above row will be successfully inserted in the table.
Rows can be deleted from a table by using the ‘delete!’ function. Following is the syntax on how this operation can be performed.
clojure.java.jdbc/delete!
:table_name [condition]
Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘condition’ is the condition used to determine which row needs to be deleted from the table.
Return Value − This will return the number of rows deleted.
The following example shows how to delete a record from the employee table in the testdb database. The example deletes a row from the table based on the condition that the age is equal to 30.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/testdb"
:user "root"
:password "shakinstev"})
(println (sql/delete! mysql-db
:employee ["age = ? " 30])))
If you had a record which had a row with age equal to the value of 30, that row will be deleted.
Rows can be updated from a table by using the ‘update!’ function. Following is the syntax on how this operation can be performed.
clojure.java.jdbc/update!
:table_name
{setcondition}
[condition]
Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘setcondition’ is the column which needs to be updated as mentioned in terms of a map. ‘condition’ is the condition which is used to determine which row needs to be deleted from the table.
Return Value − This will return the number of rows updated.
The following example shows how to delete a record from the employee table in the testdb database. The example updates a row from the table based on the condition that the age is equal to 30 and updates the value of income to 40.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/testdb"
:user "root"
:password "shakinstev"})
(println (sql/update! mysql-db
:employee
{:income 40}
["age = ? " 30])))
If you had a record which had a row with age equal to the value of 30, that row will be updated wherein the value of income will be set to 40.
Transactions are mechanisms that ensure data consistency. Transactions have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
The following example shows how to implement transactions in Clojure. Any operations which needs to be performed in a transaction needs to be embedded in the ‘with-dbtransaction’ clause.
(ns test.core
(:require [clojure.java.jdbc :as sql]))
(defn -main []
(def mysql-db {
:subprotocol "mysql"
:subname "//127.0.0.1:3306/testdb"
:user "root"
:password "shakinstev"})
(sql/with-db-transaction [t-con mysql-db]
(sql/update! t-con
:employee
{:income 40}
["age = ? " 30])))
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2547,
"s": 2374,
"text": "In order to use the database functionality, please ensure to first download the jdbc files from the following url − https://codeload.github.com/clojure/java.jdbc/zip/master"
},
{
"code": null,
"e": 2748,
"s": 2547,
"text": "You will find a zip file which has the necessary drivers for Clojure to have the ability to connect to databases. Once the zip file is extracted, ensure to add the unzipped location to your classpath."
},
{
"code": null,
"e": 2844,
"s": 2748,
"text": "The main file for database connectivity is a file called jdbc.clj in the location clojure/java."
},
{
"code": null,
"e": 2942,
"s": 2844,
"text": "The clojure jdbc connector supports a wide variety of databases, some of which are the following."
},
{
"code": null,
"e": 2953,
"s": 2942,
"text": "H2Database"
},
{
"code": null,
"e": 2960,
"s": 2953,
"text": "Oracle"
},
{
"code": null,
"e": 2981,
"s": 2960,
"text": "Microsoft SQL Server"
},
{
"code": null,
"e": 2987,
"s": 2981,
"text": "MySQL"
},
{
"code": null,
"e": 2998,
"s": 2987,
"text": "PostgreSQL"
},
{
"code": null,
"e": 3058,
"s": 2998,
"text": "In our example, we are going to use MySQL DB as an example."
},
{
"code": null,
"e": 3134,
"s": 3058,
"text": "The following operations are possible in Clojure with regards to Databases."
},
{
"code": null,
"e": 3202,
"s": 3134,
"text": "Before connecting to a MySQL database, make sure of the following −"
},
{
"code": null,
"e": 3238,
"s": 3202,
"text": "You have created a database TESTDB."
},
{
"code": null,
"e": 3274,
"s": 3238,
"text": "You have created a database TESTDB."
},
{
"code": null,
"e": 3319,
"s": 3274,
"text": "You have created a table EMPLOYEE in TESTDB."
},
{
"code": null,
"e": 3364,
"s": 3319,
"text": "You have created a table EMPLOYEE in TESTDB."
},
{
"code": null,
"e": 3430,
"s": 3364,
"text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 3496,
"s": 3430,
"text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 3564,
"s": 3496,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 3632,
"s": 3564,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 3718,
"s": 3632,
"text": "Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath."
},
{
"code": null,
"e": 3804,
"s": 3718,
"text": "Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath."
},
{
"code": null,
"e": 3869,
"s": 3804,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 3934,
"s": 3869,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 3993,
"s": 3934,
"text": "Following is the syntax to create a connection in Clojure."
},
{
"code": null,
"e": 4128,
"s": 3993,
"text": "(def connection_name {\n :subprotocol “protocol_name”\n :subname “Location of mysql DB”\n :user “username” :password “password” })\n"
},
{
"code": null,
"e": 4511,
"s": 4128,
"text": "Parameters − ‘connection_name’ is the name to be given to the connection. ‘subprotocol’ is the protocol to be used for the connection. By default we will be using the mysql protocol. ‘subname’ is the url to connect to the mysql db along with the database name. ‘user’ is the username used to connect to the database. ‘password’ is the password to be used to connect to the database."
},
{
"code": null,
"e": 4615,
"s": 4511,
"text": "Return Value − This will provide a connection string, which can be used in subsequent mysql operations."
},
{
"code": null,
"e": 4738,
"s": 4615,
"text": "The following example shows how to connect to the tables in the information schema and retrieve all the data in the table."
},
{
"code": null,
"e": 5060,
"s": 4738,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/information_schema\"\n :user \"root\"\n :password \"shakinstev\"})\n (println (sql/query mysql-db\n [\"select table_name from tables\"]\n :row-fn :table_name)))"
},
{
"code": null,
"e": 5309,
"s": 5060,
"text": "Querying data on any database means to fetch some useful information from the database. Once a database connection is established, you are ready to make a query into this database. Following is the syntax by which data can be queried using Clojure."
},
{
"code": null,
"e": 5372,
"s": 5309,
"text": "clojure.java.jdbc/query dbconn\n[\"query\"]\n :row-fn :sequence\n"
},
{
"code": null,
"e": 5720,
"s": 5372,
"text": "Parameters − ‘dbconn’ is the name of the connection used to connect to the database. ‘query’ is the query string used to fetch data from the database. ‘:sequence’ is by default all the rows of data fetched from the database and is returned as a sequence. The necessary operations on the sequence can then be done to see what data has been fetched."
},
{
"code": null,
"e": 5823,
"s": 5720,
"text": "Return Value − This will return a sequence, which will have the rows of data from the query operation."
},
{
"code": null,
"e": 5946,
"s": 5823,
"text": "The following example shows how to connect to the employee table and fetch the first_name column of the rows in the table."
},
{
"code": null,
"e": 6258,
"s": 5946,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/testdb\"\n :user \"root\"\n :password \"shakinstev\"})\n (println (sql/query mysql-db\n [\"select first_name from employee\"]\n :row-fn :first_name)))"
},
{
"code": null,
"e": 6295,
"s": 6258,
"text": "From the above code, we can see that"
},
{
"code": null,
"e": 6373,
"s": 6295,
"text": "The query of “select first_name from employee” is passed as the query string."
},
{
"code": null,
"e": 6451,
"s": 6373,
"text": "The query of “select first_name from employee” is passed as the query string."
},
{
"code": null,
"e": 6538,
"s": 6451,
"text": "The :first_name is the sequence, which is returned as a result of the fetch operation."
},
{
"code": null,
"e": 6625,
"s": 6538,
"text": "The :first_name is the sequence, which is returned as a result of the fetch operation."
},
{
"code": null,
"e": 6775,
"s": 6625,
"text": "If we assume that there is just one row in our database which contains a first_name value of John, following will be the output of the above program."
},
{
"code": null,
"e": 6783,
"s": 6775,
"text": "(John)\n"
},
{
"code": null,
"e": 6973,
"s": 6783,
"text": "It is required when you want to create your records into a database table. Following is the syntax by which data can be inserted using Clojure. This is done by using the ‘insert!’ function."
},
{
"code": null,
"e": 7043,
"s": 6973,
"text": "clojure.java.jdbc/insert!\n :table_name {:column_namen columnvalue}\n"
},
{
"code": null,
"e": 7258,
"s": 7043,
"text": "Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘{:column_namen columnvalue }’ is a map of all the column names and values, which need to be added as a row in the table."
},
{
"code": null,
"e": 7333,
"s": 7258,
"text": "Return Value − This will return nil if the insertion is made successfully."
},
{
"code": null,
"e": 7432,
"s": 7333,
"text": "The following example shows how to insert a record into the employee table in the testdb database."
},
{
"code": null,
"e": 7751,
"s": 7432,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/testdb\"\n :user \"root\"\n :password \"shakinstev\"})\n (sql/insert! mysql-db\n :employee {:first_name \"John\" :last_name \"Mark\" :sex \"M\" :age 30 :income 30}))"
},
{
"code": null,
"e": 7888,
"s": 7751,
"text": "If you now check your MySQL database and the employee table, you will see that the above row will be successfully inserted in the table."
},
{
"code": null,
"e": 8018,
"s": 7888,
"text": "Rows can be deleted from a table by using the ‘delete!’ function. Following is the syntax on how this operation can be performed."
},
{
"code": null,
"e": 8072,
"s": 8018,
"text": "clojure.java.jdbc/delete!\n :table_name [condition]\n"
},
{
"code": null,
"e": 8258,
"s": 8072,
"text": "Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘condition’ is the condition used to determine which row needs to be deleted from the table."
},
{
"code": null,
"e": 8318,
"s": 8258,
"text": "Return Value − This will return the number of rows deleted."
},
{
"code": null,
"e": 8510,
"s": 8318,
"text": "The following example shows how to delete a record from the employee table in the testdb database. The example deletes a row from the table based on the condition that the age is equal to 30."
},
{
"code": null,
"e": 8788,
"s": 8510,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/testdb\"\n :user \"root\"\n :password \"shakinstev\"})\n (println (sql/delete! mysql-db\n :employee [\"age = ? \" 30])))"
},
{
"code": null,
"e": 8885,
"s": 8788,
"text": "If you had a record which had a row with age equal to the value of 30, that row will be deleted."
},
{
"code": null,
"e": 9015,
"s": 8885,
"text": "Rows can be updated from a table by using the ‘update!’ function. Following is the syntax on how this operation can be performed."
},
{
"code": null,
"e": 9084,
"s": 9015,
"text": "clojure.java.jdbc/update!\n :table_name\n{setcondition}\n[condition]\n"
},
{
"code": null,
"e": 9366,
"s": 9084,
"text": "Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘setcondition’ is the column which needs to be updated as mentioned in terms of a map. ‘condition’ is the condition which is used to determine which row needs to be deleted from the table."
},
{
"code": null,
"e": 9426,
"s": 9366,
"text": "Return Value − This will return the number of rows updated."
},
{
"code": null,
"e": 9656,
"s": 9426,
"text": "The following example shows how to delete a record from the employee table in the testdb database. The example updates a row from the table based on the condition that the age is equal to 30 and updates the value of income to 40."
},
{
"code": null,
"e": 9959,
"s": 9656,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/testdb\"\n :user \"root\"\n :password \"shakinstev\"})\n (println (sql/update! mysql-db\n :employee\n {:income 40}\n [\"age = ? \" 30])))"
},
{
"code": null,
"e": 10102,
"s": 9959,
"text": "If you had a record which had a row with age equal to the value of 30, that row will be updated wherein the value of income will be set to 40."
},
{
"code": null,
"e": 10210,
"s": 10102,
"text": "Transactions are mechanisms that ensure data consistency. Transactions have the following four properties −"
},
{
"code": null,
"e": 10280,
"s": 10210,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 10350,
"s": 10280,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 10455,
"s": 10350,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 10560,
"s": 10455,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 10659,
"s": 10560,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 10758,
"s": 10659,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 10862,
"s": 10758,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 10966,
"s": 10862,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 11153,
"s": 10966,
"text": "The following example shows how to implement transactions in Clojure. Any operations which needs to be performed in a transaction needs to be embedded in the ‘with-dbtransaction’ clause."
},
{
"code": null,
"e": 11501,
"s": 11153,
"text": "(ns test.core\n (:require [clojure.java.jdbc :as sql]))\n(defn -main []\n (def mysql-db {\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/testdb\"\n :user \"root\"\n :password \"shakinstev\"})\n (sql/with-db-transaction [t-con mysql-db]\n (sql/update! t-con\n :employee\n {:income 40}\n [\"age = ? \" 30])))"
},
{
"code": null,
"e": 11508,
"s": 11501,
"text": " Print"
},
{
"code": null,
"e": 11519,
"s": 11508,
"text": " Add Notes"
}
] |
VBA - Exit Do
|
An Exit Do Statement is used when we want to exit the Do Loops based on certain criteria. It can be used within both Do...While and Do...Until Loops.
When Exit Do is executed, the control jumps to the next statement immediately after the Do Loop.
Following is the syntax for Exit Do Statement in VBA.
Exit Do
The following example uses Exit Do. If the value of the Counter reaches 10, the Do Loop is exited and the control jumps to the next statement immediately after the For Loop.
Private Sub Constant_demo_Click()
i = 0
Do While i <= 100
If i > 10 Then
Exit Do ' Loop Exits if i>10
End If
MsgBox ("The Value of i is : " & i)
i = i + 2
Loop
End Sub
When the above code is executed, it prints the following output in a message box.
The Value of i is : 0
The Value of i is : 2
The Value of i is : 4
The Value of i is : 6
The Value of i is : 8
The Value of i is : 10
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2085,
"s": 1935,
"text": "An Exit Do Statement is used when we want to exit the Do Loops based on certain criteria. It can be used within both Do...While and Do...Until Loops."
},
{
"code": null,
"e": 2182,
"s": 2085,
"text": "When Exit Do is executed, the control jumps to the next statement immediately after the Do Loop."
},
{
"code": null,
"e": 2236,
"s": 2182,
"text": "Following is the syntax for Exit Do Statement in VBA."
},
{
"code": null,
"e": 2246,
"s": 2236,
"text": " Exit Do\n"
},
{
"code": null,
"e": 2420,
"s": 2246,
"text": "The following example uses Exit Do. If the value of the Counter reaches 10, the Do Loop is exited and the control jumps to the next statement immediately after the For Loop."
},
{
"code": null,
"e": 2632,
"s": 2420,
"text": "Private Sub Constant_demo_Click()\n i = 0\n Do While i <= 100\n If i > 10 Then\n Exit Do ' Loop Exits if i>10\n End If\n MsgBox (\"The Value of i is : \" & i)\n i = i + 2\n Loop\nEnd Sub"
},
{
"code": null,
"e": 2714,
"s": 2632,
"text": "When the above code is executed, it prints the following output in a message box."
},
{
"code": null,
"e": 2853,
"s": 2714,
"text": "The Value of i is : 0\n\nThe Value of i is : 2\n\nThe Value of i is : 4\n\nThe Value of i is : 6\n\nThe Value of i is : 8\n\nThe Value of i is : 10\n"
},
{
"code": null,
"e": 2887,
"s": 2853,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2902,
"s": 2887,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2935,
"s": 2902,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2950,
"s": 2935,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2985,
"s": 2950,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3003,
"s": 2985,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3036,
"s": 3003,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3054,
"s": 3036,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3087,
"s": 3054,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3102,
"s": 3087,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3138,
"s": 3102,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3166,
"s": 3138,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3173,
"s": 3166,
"text": " Print"
},
{
"code": null,
"e": 3184,
"s": 3173,
"text": " Add Notes"
}
] |
How to change an element color based on value of the color picker value using onclick? - GeeksforGeeks
|
20 Sep, 2019
We can define color picker by input type=”color”. It provides a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format. Only the colors without alpha channel are allowed. Though CSS colors have more formats, e.g. color names, functional notations and a hexadecimal format with an alpha channel.
Approach:
To change the color of our element based on the value of color picker we have to use onclick() event of the element and change its CSS color property as per the selected value in color picker element.
This value appears as color picker’s value attribute. using javascript, we will change the color of our element as the chosen value in color picker.
Syntax:
HTML: < div id="elementId" onclick="fn_name()"></div>
< input name="ColorPickerId" type="color" id="ColorPickerName" />
< div id="elementId" onclick="fn_name()"></div>
< input name="ColorPickerId" type="color" id="ColorPickerName" />
JavaScript:document.getElementById("elementID").style.Color =
document.getElementById("ColorPickerId").value;
document.getElementById("elementID").style.Color =
document.getElementById("ColorPickerId").value;
Example 1:
<html> <head> <style> #Myelement { background-color: black; width: 500px; height: 100px; } </style></head> <body> <div id="Myelement" onclick="changeColor()"> </div> <input name="MyColorPicker" type="color" id="MyColorPicker" /> <script> function changeColor() { document.getElementById( "Myelement").style.backgroundColor = document.getElementById( "MyColorPicker").value; } </script></body> </html>
Output:Before:After picking the color:After clicking the div:
Example 2:
<html> <head></head> <body> <h1 id="Myelement" onclick="changeColor()"> GeeksforGeeks </h1> <input name="MyColorPicker" type="color" id="ColorPicker1" /> <script> function changeColor() { document.getElementById("Myelement").style.color = document.getElementById("ColorPicker1").value; } </script></body> </html>
Output:Before:After picking the color:After clicking the div:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
How to Use the JavaScript Fetch API to Get Data?
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": 24727,
"s": 24699,
"text": "\n20 Sep, 2019"
},
{
"code": null,
"e": 25145,
"s": 24727,
"text": "We can define color picker by input type=”color”. It provides a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format. Only the colors without alpha channel are allowed. Though CSS colors have more formats, e.g. color names, functional notations and a hexadecimal format with an alpha channel."
},
{
"code": null,
"e": 25155,
"s": 25145,
"text": "Approach:"
},
{
"code": null,
"e": 25356,
"s": 25155,
"text": "To change the color of our element based on the value of color picker we have to use onclick() event of the element and change its CSS color property as per the selected value in color picker element."
},
{
"code": null,
"e": 25505,
"s": 25356,
"text": "This value appears as color picker’s value attribute. using javascript, we will change the color of our element as the chosen value in color picker."
},
{
"code": null,
"e": 25513,
"s": 25505,
"text": "Syntax:"
},
{
"code": null,
"e": 25639,
"s": 25513,
"text": "HTML: < div id=\"elementId\" onclick=\"fn_name()\"></div>\n < input name=\"ColorPickerId\" type=\"color\" id=\"ColorPickerName\" />"
},
{
"code": null,
"e": 25760,
"s": 25639,
"text": " < div id=\"elementId\" onclick=\"fn_name()\"></div>\n < input name=\"ColorPickerId\" type=\"color\" id=\"ColorPickerName\" />"
},
{
"code": null,
"e": 25877,
"s": 25760,
"text": "JavaScript:document.getElementById(\"elementID\").style.Color = \n document.getElementById(\"ColorPickerId\").value;"
},
{
"code": null,
"e": 25983,
"s": 25877,
"text": "document.getElementById(\"elementID\").style.Color = \n document.getElementById(\"ColorPickerId\").value;"
},
{
"code": null,
"e": 25994,
"s": 25983,
"text": "Example 1:"
},
{
"code": "<html> <head> <style> #Myelement { background-color: black; width: 500px; height: 100px; } </style></head> <body> <div id=\"Myelement\" onclick=\"changeColor()\"> </div> <input name=\"MyColorPicker\" type=\"color\" id=\"MyColorPicker\" /> <script> function changeColor() { document.getElementById( \"Myelement\").style.backgroundColor = document.getElementById( \"MyColorPicker\").value; } </script></body> </html>",
"e": 26559,
"s": 25994,
"text": null
},
{
"code": null,
"e": 26621,
"s": 26559,
"text": "Output:Before:After picking the color:After clicking the div:"
},
{
"code": null,
"e": 26632,
"s": 26621,
"text": "Example 2:"
},
{
"code": "<html> <head></head> <body> <h1 id=\"Myelement\" onclick=\"changeColor()\"> GeeksforGeeks </h1> <input name=\"MyColorPicker\" type=\"color\" id=\"ColorPicker1\" /> <script> function changeColor() { document.getElementById(\"Myelement\").style.color = document.getElementById(\"ColorPicker1\").value; } </script></body> </html>",
"e": 27038,
"s": 26632,
"text": null
},
{
"code": null,
"e": 27100,
"s": 27038,
"text": "Output:Before:After picking the color:After clicking the div:"
},
{
"code": null,
"e": 27116,
"s": 27100,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27127,
"s": 27116,
"text": "JavaScript"
},
{
"code": null,
"e": 27144,
"s": 27127,
"text": "Web Technologies"
},
{
"code": null,
"e": 27171,
"s": 27144,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27269,
"s": 27171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27278,
"s": 27269,
"text": "Comments"
},
{
"code": null,
"e": 27291,
"s": 27278,
"text": "Old Comments"
},
{
"code": null,
"e": 27352,
"s": 27291,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27397,
"s": 27352,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27469,
"s": 27397,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27510,
"s": 27469,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27559,
"s": 27510,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 27615,
"s": 27559,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27648,
"s": 27615,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27710,
"s": 27648,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27753,
"s": 27710,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Optimize Memory Tips in Python. Tracking, managing, and optimizing... | by Nhu Hoang | Towards Data Science
|
Memory management in Python is not a simple issue to solve, it requires a decent understanding of Python objects and data structures. Unlike in C/C++, users have no control over memory management. It is taken over by Python itself. However, with some insights about how Python works and memory support modules, we can somehow seed some light on how to control this issue.
There are several ways to get the size of an object in Python. You can use sys.getsizeof() to get the exact size of the object, objgraph.show_refs() to visualize the structure of an object or psutil.Process().memory_info().rss to get all memory is allocated at the moment.
tracemalloc is also another choice. It is included in the Python standard library and provides block-level traces of memory allocation, statistics for the overall memory behavior of a program.
The most used file is the arr object which takes up 2 memory blocks with a total size of 2637 MiB. Other objects are minimal.
Another important technique is to estimate how much memory is needed for the process to run. This can be guessed through monitoring the peak memory usage of the process. To measure peak memory, you can use the below code at the end of the process.
### For Linux (in KiB) and MacOS (in bytes)from resource import getrusage, RUSAGE_SELFprint(getrusage(RUSAGE_SELF).ru_maxrss)### For Windowsimport psutilprint(psutil.Process().memory_info().peak_wset)
Having the peak number and the amount of data put in the process, you can, by some means, judge the amount of memory to be consumed for your next process.
Training a large dataset is a bottleneck for your memory and you will never be able to train a complete model given the whole dataset never fits in your memory at the same time, especially for unstructured data such as image, text, voice,... However, with Pytorch DataLoader, you manage to set up various mini-batches for the whole dataset and each is loaded uninterruptedly into your model (the number of samples depends on your memory capability). You can see here the tutorial on using Pytorch DataLoader.
However, if you want to train a Machine Learning model on tabular data without using Deep learning (hence, not using Pytorch) or you don’t have access to a Database and have to work solely on the memory, what will be the choice for memory optimization?
By understanding how data is stored and manipulated and using the optimal data type for the tasks, it will save you huge space in memory and computation time. In Numpy, there are multiple types, including boolean (bool), integer (int), Unsigned integer (uint), float, complex, datetime64, timedelta64, object_, etc...
### Check numpy integer>>> import numpy as np>>> ii16 = np.iinfo(np.int16)>>> ii16iinfo(min=-32768, max=32767, dtype=int16)### Access min value>>> ii16.min-32768
I narrow them down to uint, int, and float given these are the most common when training models, handling data in Python. Depending on different needs and objectives, using sufficient data types becomes vital know-how. To check type minimum and maximum values, you can use function numpy.iinfo(), and numpy.finfo() for float.
Below is the summary information for each type.
The CSV file size doubles if the data type is converted to numpy.float64, which is the default type of numpy.array, compared to numpy.float32. Therefore, float32 is one of the optimal ones to use (Pytorch datatype is also float32).
As the default data type numpy.float() is float64 and numpy.int() is int64, remember to define the dtype when creating numpy array will save a huge amount of memory space.
When working with DataFrame, there will be another usual type which is “object”. Converting from object to category for feature having various repetitions will help computation time faster.
Below is an example function to optimize the pd.DataFrame data type for scalars and strings.
Another way to easily and efficiently reduce pd.DataFrame memory footprint is to import data with specific columns using usercols parameters in pd.read_csv()
Python is faster at retrieving a local variable than a global one. Moreover, declaring too many variables as global leads to Out of Memory issue as these remain in the memory till program execution is completed while local variables are deleted as soon as the function is over and release the memory space which it occupies. Read more at The real-life skill set that data scientists must master
towardsdatascience.com
Python yield returns a generator object, which converts the expression given into a generator function. To get the values of the object, it has to be iterated to read the values given to the yield. To read the generator’s values, you can use list(), for loop, or next().
>>> def say_hello():>>> yield "HELLO!">>> SENTENCE = say_hello()>>> print(next(SENTENCE))HELLO!
However, generators are for one-time use objects. If you access it the second time, it returns empty.
>>> def say_hello():>>> yield "HELLO!">>> SENTENCE = say_hello()>>> print(next(SENTENCE))HELLO!>>> print("calling the generator again: ", list(SENTENCE))calling the generator again: []
As there is no value returned unless the generator object is iterated, no memory is used when the Yield function is defined, while calling Return in a function leads to the allocation in memory.
Hence, Yield is suitable for large datasets, or when you don’t need to store all the output values but just one value for each iteration of the main function.
>>> import sys>>> my_generator_list = (i*2 for i in range(100000))>>> print(f"My generator is {sys.getsizeof(my_generator_list)} bytes")My generator is 128 bytes>>> timeit(my_generator_list)10000000 loops, best of 5: 32 ns per loop >>> my_list = [i*2 for i in range(1000000)]>>> print(f"My list is {sys.getsizeof(my_list)} bytes")My list is 824472 bytes>>> timeit(my_list)10000000 loops, best of 5: 34.5 ns per loop
Looking at the above code, the list comprehension is 6441 times heavier than the generator and runs slower than the other generator.
Use Python Built-in Functions to improve code performance, list of functions.
Python class objects’ attributes are stored in the form of a dictionary. Thus, defining thousands of objects is the same as allocating thousands of dictionaries to the memory space. And adding __slots__ (which reduces the wastage of space and speeds up the program by allocating space for a fixed amount of attributes.)
Regarding memory usage, given there is no longer __dict__ in a class object, the memory space reduces noticeably from (64+16+120)=200 to 56 bytes.
As strings are immutable, every time you add an element to a string by the “+” operator, a new string will be allocated in memory space. The longer the string, the more memory consumed, the less efficient the code becomes. Using join() can improve speed >30% vs ‘+’ operator.
There are other methods to improve speed and save memory, check details here.
Or flatten a list with itertools.chain()
### Concatenate string using '+' operationdef add_string_with_plus(iters): s = "" for i in range(iters): s += "abc" assert len(s) == 3*iters ### Concatenate strings using join() functiondef add_string_with_join(iters): l = [] for i in range(iters): l.append("abc") s = "".join(l) assert len(s) == 3*iters ### Compare speed>>> timeit(add_string_with_plus(10000))100 loops, best of 5: 3.74 ms per loop>>> timeit(add_string_with_join(10000))100 loops, best of 5: 2.3 ms per loop
Check out itertools documentation for more methods. I recommend exploring:
itertools.accumulate(iterable , func): accumulate through iterable. func can be an operator.func or default Python functions such as max, min...
itertools.compress(iterable, selectors): filters the iterable with another (the other object can be treated as a condition)
itertools.filterfalse(predicate, iterable): filter and drop values that satisfy the predicate. This is useful and fast for filtering a list object.
itertools.repeat(object[, times]): repeat a object value N times. However, I prefer using list multiplication ['hi']*1000 to repeat ‘hi’ 1000 times than using itertools.repeat('hi', 1000) (12.2 μs per loop vs 162 μs per loop respectively)
itertools.zip_longest(*iterables, fillvalue=None): zip multiple iterables into tuples and fill None value with the value specified in fillvalue.
import statement can be executed from anywhere. However, executing outside of a function will run much faster than the inside one, even though the package is declared as a global variable (doit2), but in return, takes up more memory space than the other one.
I’m confident to say that most of the time you don’t use all of your data all at once and loading them in 1 big batch may crash the memory. Therefore, chunking data or load in small chunks, process the chunk of data, and save the result is one of the most useful techniques to prevent memory error.
pandas lets you do that with the help of chunksize or iterator parameters in pandas.read_csv() and pandas.read_sql(). sklearn also supports training in small chunks with partial_fit()method for most models.
Handling Memory Error in Python is a tricky task and the root cause might be never been detected if you go another way around.
First, investigate which process/variable is the core reason leading to the memory overflown problem.
Second, apply the applicable memory optimization methods for that object, estimate the new memory footprint and examine if the new one solves the issue.
If not, try to optimize related processes (such as reducing whole process memory consumption to save more space for the core object).
Try the above tips and if the trouble remains, consider building the process with chunk/batch operation with the support of an outside database service.
|
[
{
"code": null,
"e": 544,
"s": 172,
"text": "Memory management in Python is not a simple issue to solve, it requires a decent understanding of Python objects and data structures. Unlike in C/C++, users have no control over memory management. It is taken over by Python itself. However, with some insights about how Python works and memory support modules, we can somehow seed some light on how to control this issue."
},
{
"code": null,
"e": 817,
"s": 544,
"text": "There are several ways to get the size of an object in Python. You can use sys.getsizeof() to get the exact size of the object, objgraph.show_refs() to visualize the structure of an object or psutil.Process().memory_info().rss to get all memory is allocated at the moment."
},
{
"code": null,
"e": 1010,
"s": 817,
"text": "tracemalloc is also another choice. It is included in the Python standard library and provides block-level traces of memory allocation, statistics for the overall memory behavior of a program."
},
{
"code": null,
"e": 1136,
"s": 1010,
"text": "The most used file is the arr object which takes up 2 memory blocks with a total size of 2637 MiB. Other objects are minimal."
},
{
"code": null,
"e": 1384,
"s": 1136,
"text": "Another important technique is to estimate how much memory is needed for the process to run. This can be guessed through monitoring the peak memory usage of the process. To measure peak memory, you can use the below code at the end of the process."
},
{
"code": null,
"e": 1585,
"s": 1384,
"text": "### For Linux (in KiB) and MacOS (in bytes)from resource import getrusage, RUSAGE_SELFprint(getrusage(RUSAGE_SELF).ru_maxrss)### For Windowsimport psutilprint(psutil.Process().memory_info().peak_wset)"
},
{
"code": null,
"e": 1740,
"s": 1585,
"text": "Having the peak number and the amount of data put in the process, you can, by some means, judge the amount of memory to be consumed for your next process."
},
{
"code": null,
"e": 2249,
"s": 1740,
"text": "Training a large dataset is a bottleneck for your memory and you will never be able to train a complete model given the whole dataset never fits in your memory at the same time, especially for unstructured data such as image, text, voice,... However, with Pytorch DataLoader, you manage to set up various mini-batches for the whole dataset and each is loaded uninterruptedly into your model (the number of samples depends on your memory capability). You can see here the tutorial on using Pytorch DataLoader."
},
{
"code": null,
"e": 2502,
"s": 2249,
"text": "However, if you want to train a Machine Learning model on tabular data without using Deep learning (hence, not using Pytorch) or you don’t have access to a Database and have to work solely on the memory, what will be the choice for memory optimization?"
},
{
"code": null,
"e": 2820,
"s": 2502,
"text": "By understanding how data is stored and manipulated and using the optimal data type for the tasks, it will save you huge space in memory and computation time. In Numpy, there are multiple types, including boolean (bool), integer (int), Unsigned integer (uint), float, complex, datetime64, timedelta64, object_, etc..."
},
{
"code": null,
"e": 2982,
"s": 2820,
"text": "### Check numpy integer>>> import numpy as np>>> ii16 = np.iinfo(np.int16)>>> ii16iinfo(min=-32768, max=32767, dtype=int16)### Access min value>>> ii16.min-32768"
},
{
"code": null,
"e": 3308,
"s": 2982,
"text": "I narrow them down to uint, int, and float given these are the most common when training models, handling data in Python. Depending on different needs and objectives, using sufficient data types becomes vital know-how. To check type minimum and maximum values, you can use function numpy.iinfo(), and numpy.finfo() for float."
},
{
"code": null,
"e": 3356,
"s": 3308,
"text": "Below is the summary information for each type."
},
{
"code": null,
"e": 3588,
"s": 3356,
"text": "The CSV file size doubles if the data type is converted to numpy.float64, which is the default type of numpy.array, compared to numpy.float32. Therefore, float32 is one of the optimal ones to use (Pytorch datatype is also float32)."
},
{
"code": null,
"e": 3760,
"s": 3588,
"text": "As the default data type numpy.float() is float64 and numpy.int() is int64, remember to define the dtype when creating numpy array will save a huge amount of memory space."
},
{
"code": null,
"e": 3950,
"s": 3760,
"text": "When working with DataFrame, there will be another usual type which is “object”. Converting from object to category for feature having various repetitions will help computation time faster."
},
{
"code": null,
"e": 4043,
"s": 3950,
"text": "Below is an example function to optimize the pd.DataFrame data type for scalars and strings."
},
{
"code": null,
"e": 4201,
"s": 4043,
"text": "Another way to easily and efficiently reduce pd.DataFrame memory footprint is to import data with specific columns using usercols parameters in pd.read_csv()"
},
{
"code": null,
"e": 4596,
"s": 4201,
"text": "Python is faster at retrieving a local variable than a global one. Moreover, declaring too many variables as global leads to Out of Memory issue as these remain in the memory till program execution is completed while local variables are deleted as soon as the function is over and release the memory space which it occupies. Read more at The real-life skill set that data scientists must master"
},
{
"code": null,
"e": 4619,
"s": 4596,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4890,
"s": 4619,
"text": "Python yield returns a generator object, which converts the expression given into a generator function. To get the values of the object, it has to be iterated to read the values given to the yield. To read the generator’s values, you can use list(), for loop, or next()."
},
{
"code": null,
"e": 4989,
"s": 4890,
"text": ">>> def say_hello():>>> yield \"HELLO!\">>> SENTENCE = say_hello()>>> print(next(SENTENCE))HELLO!"
},
{
"code": null,
"e": 5091,
"s": 4989,
"text": "However, generators are for one-time use objects. If you access it the second time, it returns empty."
},
{
"code": null,
"e": 5279,
"s": 5091,
"text": ">>> def say_hello():>>> yield \"HELLO!\">>> SENTENCE = say_hello()>>> print(next(SENTENCE))HELLO!>>> print(\"calling the generator again: \", list(SENTENCE))calling the generator again: []"
},
{
"code": null,
"e": 5474,
"s": 5279,
"text": "As there is no value returned unless the generator object is iterated, no memory is used when the Yield function is defined, while calling Return in a function leads to the allocation in memory."
},
{
"code": null,
"e": 5633,
"s": 5474,
"text": "Hence, Yield is suitable for large datasets, or when you don’t need to store all the output values but just one value for each iteration of the main function."
},
{
"code": null,
"e": 6050,
"s": 5633,
"text": ">>> import sys>>> my_generator_list = (i*2 for i in range(100000))>>> print(f\"My generator is {sys.getsizeof(my_generator_list)} bytes\")My generator is 128 bytes>>> timeit(my_generator_list)10000000 loops, best of 5: 32 ns per loop >>> my_list = [i*2 for i in range(1000000)]>>> print(f\"My list is {sys.getsizeof(my_list)} bytes\")My list is 824472 bytes>>> timeit(my_list)10000000 loops, best of 5: 34.5 ns per loop"
},
{
"code": null,
"e": 6183,
"s": 6050,
"text": "Looking at the above code, the list comprehension is 6441 times heavier than the generator and runs slower than the other generator."
},
{
"code": null,
"e": 6261,
"s": 6183,
"text": "Use Python Built-in Functions to improve code performance, list of functions."
},
{
"code": null,
"e": 6581,
"s": 6261,
"text": "Python class objects’ attributes are stored in the form of a dictionary. Thus, defining thousands of objects is the same as allocating thousands of dictionaries to the memory space. And adding __slots__ (which reduces the wastage of space and speeds up the program by allocating space for a fixed amount of attributes.)"
},
{
"code": null,
"e": 6728,
"s": 6581,
"text": "Regarding memory usage, given there is no longer __dict__ in a class object, the memory space reduces noticeably from (64+16+120)=200 to 56 bytes."
},
{
"code": null,
"e": 7004,
"s": 6728,
"text": "As strings are immutable, every time you add an element to a string by the “+” operator, a new string will be allocated in memory space. The longer the string, the more memory consumed, the less efficient the code becomes. Using join() can improve speed >30% vs ‘+’ operator."
},
{
"code": null,
"e": 7082,
"s": 7004,
"text": "There are other methods to improve speed and save memory, check details here."
},
{
"code": null,
"e": 7123,
"s": 7082,
"text": "Or flatten a list with itertools.chain()"
},
{
"code": null,
"e": 7640,
"s": 7123,
"text": "### Concatenate string using '+' operationdef add_string_with_plus(iters): s = \"\" for i in range(iters): s += \"abc\" assert len(s) == 3*iters ### Concatenate strings using join() functiondef add_string_with_join(iters): l = [] for i in range(iters): l.append(\"abc\") s = \"\".join(l) assert len(s) == 3*iters ### Compare speed>>> timeit(add_string_with_plus(10000))100 loops, best of 5: 3.74 ms per loop>>> timeit(add_string_with_join(10000))100 loops, best of 5: 2.3 ms per loop"
},
{
"code": null,
"e": 7715,
"s": 7640,
"text": "Check out itertools documentation for more methods. I recommend exploring:"
},
{
"code": null,
"e": 7860,
"s": 7715,
"text": "itertools.accumulate(iterable , func): accumulate through iterable. func can be an operator.func or default Python functions such as max, min..."
},
{
"code": null,
"e": 7984,
"s": 7860,
"text": "itertools.compress(iterable, selectors): filters the iterable with another (the other object can be treated as a condition)"
},
{
"code": null,
"e": 8132,
"s": 7984,
"text": "itertools.filterfalse(predicate, iterable): filter and drop values that satisfy the predicate. This is useful and fast for filtering a list object."
},
{
"code": null,
"e": 8371,
"s": 8132,
"text": "itertools.repeat(object[, times]): repeat a object value N times. However, I prefer using list multiplication ['hi']*1000 to repeat ‘hi’ 1000 times than using itertools.repeat('hi', 1000) (12.2 μs per loop vs 162 μs per loop respectively)"
},
{
"code": null,
"e": 8516,
"s": 8371,
"text": "itertools.zip_longest(*iterables, fillvalue=None): zip multiple iterables into tuples and fill None value with the value specified in fillvalue."
},
{
"code": null,
"e": 8775,
"s": 8516,
"text": "import statement can be executed from anywhere. However, executing outside of a function will run much faster than the inside one, even though the package is declared as a global variable (doit2), but in return, takes up more memory space than the other one."
},
{
"code": null,
"e": 9074,
"s": 8775,
"text": "I’m confident to say that most of the time you don’t use all of your data all at once and loading them in 1 big batch may crash the memory. Therefore, chunking data or load in small chunks, process the chunk of data, and save the result is one of the most useful techniques to prevent memory error."
},
{
"code": null,
"e": 9281,
"s": 9074,
"text": "pandas lets you do that with the help of chunksize or iterator parameters in pandas.read_csv() and pandas.read_sql(). sklearn also supports training in small chunks with partial_fit()method for most models."
},
{
"code": null,
"e": 9408,
"s": 9281,
"text": "Handling Memory Error in Python is a tricky task and the root cause might be never been detected if you go another way around."
},
{
"code": null,
"e": 9510,
"s": 9408,
"text": "First, investigate which process/variable is the core reason leading to the memory overflown problem."
},
{
"code": null,
"e": 9663,
"s": 9510,
"text": "Second, apply the applicable memory optimization methods for that object, estimate the new memory footprint and examine if the new one solves the issue."
},
{
"code": null,
"e": 9797,
"s": 9663,
"text": "If not, try to optimize related processes (such as reducing whole process memory consumption to save more space for the core object)."
}
] |
Access Modifiers in Scala - GeeksforGeeks
|
26 Feb, 2019
Access Modifiers in scala are used to define the access field of members of packages, classes or objects in scala.For using an access modifier, you must include its keyword in the definition of members of package, class or object.These modifiers will restrict accesses to the members to specific regions of code.There are Three types of access modifiers available in Scala:
PrivateProtectedPublic
Private
Protected
Public
Table:
What is companion in above table? It is a singleton object named same as the class.
1. Private: When a member is declared as private, we can only use it inside defining class or through one of its objects.
Example:
// Scala program of private access modifierclass abc{ private var a:Int = 123 def display() { a = 8 println(a) }} object access extends App{ // class abc is accessible // because this is in the same enclosing scope var e = new abc() e.display()}
Output:
8
Here we declared a variable ‘a’ private and now it can be accessed only inside it’s defining class or through classes object.
2. Protected: They can be only accessible from sub classes of the base class in which the member has been defined.
Example:
// Scala program of protected access modifier class gfg{ // declaration of protected member protected var a:Int = 123 def display() { a = 8 println(a) }} // class new1 extends by class gfgclass new1 extends gfg{ def display1() { a = 9 println(a) }} object access extends App{ // class abc is accessible because this // is in the same enclosing scope var e = new gfg() e.display() var e1 = new new1() e1.display1() }
Output:
8
9
When we extended abc in class new1, protected variable a is now available to be modified cause new1 is a subclass of class abc.
3. Public: There is no public keyword in Scala. The default access level (when no modifier is specified) corresponds to Java’s public access level.We can access these anywhere.
// Scala program of protected access modifier class gfg{ var a:Int = 123}object access extends App{ var e = new gfg() e.a = 444 println(e.a)}
Output:
444
Scala
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Map
Throw Keyword in Scala
Lambda Expression in Scala
Scala | Option
How to get the first element of List in Scala
Scala List mkString() method with a separator with example
Scala | Case Class and Case Object
How to install Scala on Windows?
|
[
{
"code": null,
"e": 23790,
"s": 23762,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 24164,
"s": 23790,
"text": "Access Modifiers in scala are used to define the access field of members of packages, classes or objects in scala.For using an access modifier, you must include its keyword in the definition of members of package, class or object.These modifiers will restrict accesses to the members to specific regions of code.There are Three types of access modifiers available in Scala:"
},
{
"code": null,
"e": 24187,
"s": 24164,
"text": "PrivateProtectedPublic"
},
{
"code": null,
"e": 24195,
"s": 24187,
"text": "Private"
},
{
"code": null,
"e": 24205,
"s": 24195,
"text": "Protected"
},
{
"code": null,
"e": 24212,
"s": 24205,
"text": "Public"
},
{
"code": null,
"e": 24219,
"s": 24212,
"text": "Table:"
},
{
"code": null,
"e": 24303,
"s": 24219,
"text": "What is companion in above table? It is a singleton object named same as the class."
},
{
"code": null,
"e": 24425,
"s": 24303,
"text": "1. Private: When a member is declared as private, we can only use it inside defining class or through one of its objects."
},
{
"code": null,
"e": 24434,
"s": 24425,
"text": "Example:"
},
{
"code": "// Scala program of private access modifierclass abc{ private var a:Int = 123 def display() { a = 8 println(a) }} object access extends App{ // class abc is accessible // because this is in the same enclosing scope var e = new abc() e.display()}",
"e": 24721,
"s": 24434,
"text": null
},
{
"code": null,
"e": 24729,
"s": 24721,
"text": "Output:"
},
{
"code": null,
"e": 24731,
"s": 24729,
"text": "8"
},
{
"code": null,
"e": 24857,
"s": 24731,
"text": "Here we declared a variable ‘a’ private and now it can be accessed only inside it’s defining class or through classes object."
},
{
"code": null,
"e": 24972,
"s": 24857,
"text": "2. Protected: They can be only accessible from sub classes of the base class in which the member has been defined."
},
{
"code": null,
"e": 24981,
"s": 24972,
"text": "Example:"
},
{
"code": "// Scala program of protected access modifier class gfg{ // declaration of protected member protected var a:Int = 123 def display() { a = 8 println(a) }} // class new1 extends by class gfgclass new1 extends gfg{ def display1() { a = 9 println(a) }} object access extends App{ // class abc is accessible because this // is in the same enclosing scope var e = new gfg() e.display() var e1 = new new1() e1.display1() }",
"e": 25481,
"s": 24981,
"text": null
},
{
"code": null,
"e": 25489,
"s": 25481,
"text": "Output:"
},
{
"code": null,
"e": 25493,
"s": 25489,
"text": "8\n9"
},
{
"code": null,
"e": 25621,
"s": 25493,
"text": "When we extended abc in class new1, protected variable a is now available to be modified cause new1 is a subclass of class abc."
},
{
"code": null,
"e": 25798,
"s": 25621,
"text": "3. Public: There is no public keyword in Scala. The default access level (when no modifier is specified) corresponds to Java’s public access level.We can access these anywhere."
},
{
"code": "// Scala program of protected access modifier class gfg{ var a:Int = 123}object access extends App{ var e = new gfg() e.a = 444 println(e.a)}",
"e": 25957,
"s": 25798,
"text": null
},
{
"code": null,
"e": 25965,
"s": 25957,
"text": "Output:"
},
{
"code": null,
"e": 25969,
"s": 25965,
"text": "444"
},
{
"code": null,
"e": 25975,
"s": 25969,
"text": "Scala"
},
{
"code": null,
"e": 25986,
"s": 25975,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 25992,
"s": 25986,
"text": "Scala"
},
{
"code": null,
"e": 26090,
"s": 25992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26099,
"s": 26090,
"text": "Comments"
},
{
"code": null,
"e": 26112,
"s": 26099,
"text": "Old Comments"
},
{
"code": null,
"e": 26124,
"s": 26112,
"text": "Scala Lists"
},
{
"code": null,
"e": 26177,
"s": 26124,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26187,
"s": 26177,
"text": "Scala Map"
},
{
"code": null,
"e": 26210,
"s": 26187,
"text": "Throw Keyword in Scala"
},
{
"code": null,
"e": 26237,
"s": 26210,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 26252,
"s": 26237,
"text": "Scala | Option"
},
{
"code": null,
"e": 26298,
"s": 26252,
"text": "How to get the first element of List in Scala"
},
{
"code": null,
"e": 26357,
"s": 26298,
"text": "Scala List mkString() method with a separator with example"
},
{
"code": null,
"e": 26392,
"s": 26357,
"text": "Scala | Case Class and Case Object"
}
] |
Read Text from Image with One Line of Python Code | by Dario Radečić | Towards Data Science
|
Dealing with images is not a trivial task. To you, as a human, it’s easy to look at something and immediately know what is it you’re looking at. But computers don’t work that way.
Tasks that are too hard for you, like complex arithmetics, and math in general, is something that a computer chews without breaking a sweat. But here the exact opposite applies — tasks that are trivial to you, like recognizing is it cat or dog in an image are really hard for a computer. In a way, we are a perfect match. For now at least.
While image classification and tasks that involve some level of computer vision might require a good bit of code and a solid understanding, reading text from a somewhat well-formatted image turns out to be a one-liner in Python —and can be applied to so many real-life problems.
And in today’s post, I want to prove that claim. There will be some installation to go though, but it shouldn’t take much time. These are the libraries you’ll need:
OpenCV
PyTesseract
I don’t want to prolonge this intro part anymore, so why don’t we jump into the good stuff now.
Now, this library will only be used to load the images(s), you don’t actually need to have a solid understanding of it beforehand (although it might be helpful, you’ll see why).
According to the official documentation:
OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.[1]
In a nutshell, you can use OpenCV to do any kind of image transformations, it’s fairly straightforward library.
If you don’t already have it installed, it’ll be just a single line in terminal:
pip install opencv-python
And that’s pretty much it. It was easy up until this point, but that’s about to change.
What the heck is this library? Well, according to Wikipedia:
Tesseract is an optical character recognition engine for various operating systems. It is free software, released under the Apache License, Version 2.0, and development has been sponsored by Google since 2006.[2]
I’m sure there are more sophisticated libraries available now, but I’ve found this one working out pretty well. Based on my own experience, this library should be able to read text from any image, provided that the font isn’t some bulls*** that even you aren’t able to read.
If it can’t read from your image, spend more time playing around with OpenCV, applying various filters to make the text stand out.
Now the installation is a bit of a pain in the bottom. If you are on Linux it all boils down to a couple of sudo-apt get commands:
sudo apt-get updatesudo apt-get install tesseract-ocrsudo apt-get install libtesseract-dev
I’m on Windows, so the process is a bit more tedious.
First, open up THIS URL, and download 32bit or 64bit installer:
The installation by itself is straightforward, boils down to clicking Next a couple of times. And yeah, you also need to do a pip installation:
pip install pytesseract
Is that all? Well, no. You still need to tell Python where Tesseract is installed. On Linux machines, I didn’t have to do so, but it’s required on Windows. By default, it’s installed in Program Files.
If you did everything correctly, executing this cell should not yield any error:
Is everything good? You may proceed.
Let’s start with a simple one. I’ve found a couple of royalty-free images that contain some sort of text, and the first one is this:
It should be the easy one, and there exists a possibility that Tesseract will read those blue ‘objects’ as brackets. Let’ see what will happen:
My claim was true. It’s not a problem though, you could easily address those with some Python magic.
The next one could be more tricky:
I hope it won’t detect that ‘B’ on the coin:
Looks like it works perfectly.
Now it’s up to you to apply this to your own problem. OpenCV skills could be of vital importance here if the text blends with the background.
Reading text from an image is a pretty difficult task for a computer to perform. Think about it, the computer doesn’t know what a letter is, it only works only with numbers. What happens behind the hood might seem like a black box at first, but I encourage you to investigate further if this is your area of interest.
I’m not saying that PyTesseract will work perfectly every time, but I’ve found it good enough even on some trickier images. But not straight out of the box. Some image manipulation is required to make the text stand out.
It’s a complex topic, I know. Take it one day at a time. One day it will be second nature to you.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
|
[
{
"code": null,
"e": 352,
"s": 172,
"text": "Dealing with images is not a trivial task. To you, as a human, it’s easy to look at something and immediately know what is it you’re looking at. But computers don’t work that way."
},
{
"code": null,
"e": 692,
"s": 352,
"text": "Tasks that are too hard for you, like complex arithmetics, and math in general, is something that a computer chews without breaking a sweat. But here the exact opposite applies — tasks that are trivial to you, like recognizing is it cat or dog in an image are really hard for a computer. In a way, we are a perfect match. For now at least."
},
{
"code": null,
"e": 971,
"s": 692,
"text": "While image classification and tasks that involve some level of computer vision might require a good bit of code and a solid understanding, reading text from a somewhat well-formatted image turns out to be a one-liner in Python —and can be applied to so many real-life problems."
},
{
"code": null,
"e": 1136,
"s": 971,
"text": "And in today’s post, I want to prove that claim. There will be some installation to go though, but it shouldn’t take much time. These are the libraries you’ll need:"
},
{
"code": null,
"e": 1143,
"s": 1136,
"text": "OpenCV"
},
{
"code": null,
"e": 1155,
"s": 1143,
"text": "PyTesseract"
},
{
"code": null,
"e": 1251,
"s": 1155,
"text": "I don’t want to prolonge this intro part anymore, so why don’t we jump into the good stuff now."
},
{
"code": null,
"e": 1429,
"s": 1251,
"text": "Now, this library will only be used to load the images(s), you don’t actually need to have a solid understanding of it beforehand (although it might be helpful, you’ll see why)."
},
{
"code": null,
"e": 1470,
"s": 1429,
"text": "According to the official documentation:"
},
{
"code": null,
"e": 1850,
"s": 1470,
"text": "OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.[1]"
},
{
"code": null,
"e": 1962,
"s": 1850,
"text": "In a nutshell, you can use OpenCV to do any kind of image transformations, it’s fairly straightforward library."
},
{
"code": null,
"e": 2043,
"s": 1962,
"text": "If you don’t already have it installed, it’ll be just a single line in terminal:"
},
{
"code": null,
"e": 2069,
"s": 2043,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 2157,
"s": 2069,
"text": "And that’s pretty much it. It was easy up until this point, but that’s about to change."
},
{
"code": null,
"e": 2218,
"s": 2157,
"text": "What the heck is this library? Well, according to Wikipedia:"
},
{
"code": null,
"e": 2431,
"s": 2218,
"text": "Tesseract is an optical character recognition engine for various operating systems. It is free software, released under the Apache License, Version 2.0, and development has been sponsored by Google since 2006.[2]"
},
{
"code": null,
"e": 2706,
"s": 2431,
"text": "I’m sure there are more sophisticated libraries available now, but I’ve found this one working out pretty well. Based on my own experience, this library should be able to read text from any image, provided that the font isn’t some bulls*** that even you aren’t able to read."
},
{
"code": null,
"e": 2837,
"s": 2706,
"text": "If it can’t read from your image, spend more time playing around with OpenCV, applying various filters to make the text stand out."
},
{
"code": null,
"e": 2968,
"s": 2837,
"text": "Now the installation is a bit of a pain in the bottom. If you are on Linux it all boils down to a couple of sudo-apt get commands:"
},
{
"code": null,
"e": 3059,
"s": 2968,
"text": "sudo apt-get updatesudo apt-get install tesseract-ocrsudo apt-get install libtesseract-dev"
},
{
"code": null,
"e": 3113,
"s": 3059,
"text": "I’m on Windows, so the process is a bit more tedious."
},
{
"code": null,
"e": 3177,
"s": 3113,
"text": "First, open up THIS URL, and download 32bit or 64bit installer:"
},
{
"code": null,
"e": 3321,
"s": 3177,
"text": "The installation by itself is straightforward, boils down to clicking Next a couple of times. And yeah, you also need to do a pip installation:"
},
{
"code": null,
"e": 3345,
"s": 3321,
"text": "pip install pytesseract"
},
{
"code": null,
"e": 3546,
"s": 3345,
"text": "Is that all? Well, no. You still need to tell Python where Tesseract is installed. On Linux machines, I didn’t have to do so, but it’s required on Windows. By default, it’s installed in Program Files."
},
{
"code": null,
"e": 3627,
"s": 3546,
"text": "If you did everything correctly, executing this cell should not yield any error:"
},
{
"code": null,
"e": 3664,
"s": 3627,
"text": "Is everything good? You may proceed."
},
{
"code": null,
"e": 3797,
"s": 3664,
"text": "Let’s start with a simple one. I’ve found a couple of royalty-free images that contain some sort of text, and the first one is this:"
},
{
"code": null,
"e": 3941,
"s": 3797,
"text": "It should be the easy one, and there exists a possibility that Tesseract will read those blue ‘objects’ as brackets. Let’ see what will happen:"
},
{
"code": null,
"e": 4042,
"s": 3941,
"text": "My claim was true. It’s not a problem though, you could easily address those with some Python magic."
},
{
"code": null,
"e": 4077,
"s": 4042,
"text": "The next one could be more tricky:"
},
{
"code": null,
"e": 4122,
"s": 4077,
"text": "I hope it won’t detect that ‘B’ on the coin:"
},
{
"code": null,
"e": 4153,
"s": 4122,
"text": "Looks like it works perfectly."
},
{
"code": null,
"e": 4295,
"s": 4153,
"text": "Now it’s up to you to apply this to your own problem. OpenCV skills could be of vital importance here if the text blends with the background."
},
{
"code": null,
"e": 4613,
"s": 4295,
"text": "Reading text from an image is a pretty difficult task for a computer to perform. Think about it, the computer doesn’t know what a letter is, it only works only with numbers. What happens behind the hood might seem like a black box at first, but I encourage you to investigate further if this is your area of interest."
},
{
"code": null,
"e": 4834,
"s": 4613,
"text": "I’m not saying that PyTesseract will work perfectly every time, but I’ve found it good enough even on some trickier images. But not straight out of the box. Some image manipulation is required to make the text stand out."
},
{
"code": null,
"e": 4932,
"s": 4834,
"text": "It’s a complex topic, I know. Take it one day at a time. One day it will be second nature to you."
}
] |
Difference between decodeURIComponent() and decodeURI() functions in JavaScript - GeeksforGeeks
|
13 Jan, 2022
Both decodeURI() and decodeURIComponent() are Javascript global functions that are used for decoding encoded URI (Uniform Resource Identifier). decodeURI() function: It decodes a string previously encoded by encodeURI() function. It returns a decoded URI by replacing each UTF-8 escape sequence with the characters it represents.
Syntax:
decodeURI(encodeURI(x));
Parameter It contains single parameter that includes a string previously encoded by encodeURI() function and hence result will be x again.
Example: This example using decodeURI() function.
HTML
<!DOCTYPE html><html> <head> <title>decodeURI() Example</title></head> <body> <script type="text/javascript"> var decodeText1 = decodeURI('http://www.testing.com/'); document.write(decodeText1); document.write("<br>"); var decodeText2 = decodeURI('http%3A%2F%2Fwww.testing.com%2F'); document.write(decodeText2); </script></body> </html>
Output:
http://www.testing.com/
http%3A%2F%2Fwww.testing.com%2F
decodeURIComponent() function: It decodes a string previously encoded by encodeURIComponent() function. It returns a decoded URI Component by replacing each UTF-8 escape sequence with the characters it represents. It can decode any value between %00 and %7F.
Syntax:
decodeURIComponent(encodeURIComponent(x));
Parameter Single parameter that includes a string previously encoded by encodeURIComponent() and hence result will be x again.
Example: This example is on decodeURIComponent()
HTML
<!DOCTYPE html><html> <head> <title>decodeURIComponent() Example</title></head> <body> <script type="text/javascript"> var decodeText1 = decodeURIComponent( 'http://www.testing.com/'); document.write(decodeText1); document.write("<br>"); var decodeText2 = decodeURIComponent( 'http%3A%2F%2Fwww.testing.com%2F'); document.write(decodeText2); </script></body> </html>
Output:
http://www.testing.com/
http://www.testing.com/
Note:Both functions throw URIError indicating that one or more of the escape sequences in string is malformed and cannot be correctly decoded.Difference between decodeURIComponent() and decodeURI() Function:
decodeURI(): It takes encodeURI(url) string so it cannot decoded characters (, / ? : @ & = + $ #)
decodeURIComponent(): It takes encodeURIComponent(url) string so it can decode these characters.
decodeURI(): It takes encodeURI(url) string as parameter and returns the decoded string.
decodeURIComponent(): It takes encodeURIComponent(url) string as parameter and returns the decoded string.
decodeURI(“%41”): It returns “A”
decodeURIComponent(“%41”) It returns “A”
decodeURI(“%26”): It returns “%26”
decodeURIComponent(“%26”): It returns “&”
simranarora5sos
javascript-functions
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
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": 24798,
"s": 24770,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 25129,
"s": 24798,
"text": "Both decodeURI() and decodeURIComponent() are Javascript global functions that are used for decoding encoded URI (Uniform Resource Identifier). decodeURI() function: It decodes a string previously encoded by encodeURI() function. It returns a decoded URI by replacing each UTF-8 escape sequence with the characters it represents. "
},
{
"code": null,
"e": 25139,
"s": 25129,
"text": "Syntax: "
},
{
"code": null,
"e": 25164,
"s": 25139,
"text": "decodeURI(encodeURI(x));"
},
{
"code": null,
"e": 25303,
"s": 25164,
"text": "Parameter It contains single parameter that includes a string previously encoded by encodeURI() function and hence result will be x again."
},
{
"code": null,
"e": 25355,
"s": 25303,
"text": "Example: This example using decodeURI() function. "
},
{
"code": null,
"e": 25360,
"s": 25355,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>decodeURI() Example</title></head> <body> <script type=\"text/javascript\"> var decodeText1 = decodeURI('http://www.testing.com/'); document.write(decodeText1); document.write(\"<br>\"); var decodeText2 = decodeURI('http%3A%2F%2Fwww.testing.com%2F'); document.write(decodeText2); </script></body> </html>",
"e": 25741,
"s": 25360,
"text": null
},
{
"code": null,
"e": 25751,
"s": 25741,
"text": "Output: "
},
{
"code": null,
"e": 25807,
"s": 25751,
"text": "http://www.testing.com/\nhttp%3A%2F%2Fwww.testing.com%2F"
},
{
"code": null,
"e": 26068,
"s": 25807,
"text": "decodeURIComponent() function: It decodes a string previously encoded by encodeURIComponent() function. It returns a decoded URI Component by replacing each UTF-8 escape sequence with the characters it represents. It can decode any value between %00 and %7F. "
},
{
"code": null,
"e": 26078,
"s": 26068,
"text": "Syntax: "
},
{
"code": null,
"e": 26121,
"s": 26078,
"text": "decodeURIComponent(encodeURIComponent(x));"
},
{
"code": null,
"e": 26248,
"s": 26121,
"text": "Parameter Single parameter that includes a string previously encoded by encodeURIComponent() and hence result will be x again."
},
{
"code": null,
"e": 26299,
"s": 26248,
"text": "Example: This example is on decodeURIComponent() "
},
{
"code": null,
"e": 26304,
"s": 26299,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>decodeURIComponent() Example</title></head> <body> <script type=\"text/javascript\"> var decodeText1 = decodeURIComponent( 'http://www.testing.com/'); document.write(decodeText1); document.write(\"<br>\"); var decodeText2 = decodeURIComponent( 'http%3A%2F%2Fwww.testing.com%2F'); document.write(decodeText2); </script></body> </html>",
"e": 26756,
"s": 26304,
"text": null
},
{
"code": null,
"e": 26766,
"s": 26756,
"text": "Output: "
},
{
"code": null,
"e": 26814,
"s": 26766,
"text": "http://www.testing.com/\nhttp://www.testing.com/"
},
{
"code": null,
"e": 27024,
"s": 26814,
"text": "Note:Both functions throw URIError indicating that one or more of the escape sequences in string is malformed and cannot be correctly decoded.Difference between decodeURIComponent() and decodeURI() Function: "
},
{
"code": null,
"e": 27122,
"s": 27024,
"text": "decodeURI(): It takes encodeURI(url) string so it cannot decoded characters (, / ? : @ & = + $ #)"
},
{
"code": null,
"e": 27219,
"s": 27122,
"text": "decodeURIComponent(): It takes encodeURIComponent(url) string so it can decode these characters."
},
{
"code": null,
"e": 27310,
"s": 27221,
"text": "decodeURI(): It takes encodeURI(url) string as parameter and returns the decoded string."
},
{
"code": null,
"e": 27417,
"s": 27310,
"text": "decodeURIComponent(): It takes encodeURIComponent(url) string as parameter and returns the decoded string."
},
{
"code": null,
"e": 27452,
"s": 27419,
"text": "decodeURI(“%41”): It returns “A”"
},
{
"code": null,
"e": 27493,
"s": 27452,
"text": "decodeURIComponent(“%41”) It returns “A”"
},
{
"code": null,
"e": 27530,
"s": 27495,
"text": "decodeURI(“%26”): It returns “%26”"
},
{
"code": null,
"e": 27572,
"s": 27530,
"text": "decodeURIComponent(“%26”): It returns “&”"
},
{
"code": null,
"e": 27590,
"s": 27574,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27611,
"s": 27590,
"text": "javascript-functions"
},
{
"code": null,
"e": 27627,
"s": 27611,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27634,
"s": 27627,
"text": "Picked"
},
{
"code": null,
"e": 27645,
"s": 27634,
"text": "JavaScript"
},
{
"code": null,
"e": 27662,
"s": 27645,
"text": "Web Technologies"
},
{
"code": null,
"e": 27689,
"s": 27662,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27787,
"s": 27689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27796,
"s": 27787,
"text": "Comments"
},
{
"code": null,
"e": 27809,
"s": 27796,
"text": "Old Comments"
},
{
"code": null,
"e": 27854,
"s": 27809,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27915,
"s": 27854,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27987,
"s": 27915,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28039,
"s": 27987,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28085,
"s": 28039,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28127,
"s": 28085,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28160,
"s": 28127,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28222,
"s": 28160,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28265,
"s": 28222,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
CodeIgniter - Error Handling
|
Many times, while using application, we come across errors. It is very annoying for the users if the errors are not handled properly. CodeIgniter provides an easy error handling mechanism.
You would like the messages to be displayed, when the application is in developing mode rather than in production mode as the error messages can be solved easily at the developing stage.
The environment of your application can be changed, by changing the line given below from index.php file. This can be set to anything but normally there are three values (development, test, production) used for this purpose.
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
Different environment will require different levels of error reporting. By default, development mode will display errors and testing and live mode will hide them. CodeIgniter provides three functions as shown below to handle errors.
show_error() function displays errors in HTML format at the top of the screen.
show_error() function displays errors in HTML format at the top of the screen.
Syntax
Parameters
$message (mixed) − Error message
$message (mixed) − Error message
$status_code (int) − HTTP Response status code
$status_code (int) − HTTP Response status code
$heading (string) − Error page heading
$heading (string) − Error page heading
Return Type
show_404() function displays error if you are trying to access a page which does not exist.
show_404() function displays error if you are trying to access a page which does not exist.
Syntax
Parameters
$page (string) – URI string
$page (string) – URI string
$log_error (bool) – Whether to log the error
$log_error (bool) – Whether to log the error
Return Type
log_message() function is used to write log messages. This is useful when you want to write custom messages.
log_message() function is used to write log messages. This is useful when you want to write custom messages.
Syntax
Parameters
$level (string) − Log level: ‘error’, ‘debug’ or ‘info’
$level (string) − Log level: ‘error’, ‘debug’ or ‘info’
$message (string) − Message to log
$message (string) − Message to log
$php_error (bool) − Whether we’re logging a native PHP error message
$php_error (bool) − Whether we’re logging a native PHP error message
Return Type
Logging can be enabled in application/config/config.php file. Given below is the screenshot of config.php file, where you can set threshold value.
/*
|--------------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disable logging, Error logging TURNED OFF
| 1 = Error Message (including PHP errors)
| 2 = Debug Message
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
You can find the log messages in application/log/. Make sure that this directory is writable before you enable log files.
Various templates for error messages can be found in application/views/errors/cli or application/views/errors/html.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2508,
"s": 2319,
"text": "Many times, while using application, we come across errors. It is very annoying for the users if the errors are not handled properly. CodeIgniter provides an easy error handling mechanism."
},
{
"code": null,
"e": 2695,
"s": 2508,
"text": "You would like the messages to be displayed, when the application is in developing mode rather than in production mode as the error messages can be solved easily at the developing stage."
},
{
"code": null,
"e": 2920,
"s": 2695,
"text": "The environment of your application can be changed, by changing the line given below from index.php file. This can be set to anything but normally there are three values (development, test, production) used for this purpose."
},
{
"code": null,
"e": 3008,
"s": 2920,
"text": "define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');\n"
},
{
"code": null,
"e": 3241,
"s": 3008,
"text": "Different environment will require different levels of error reporting. By default, development mode will display errors and testing and live mode will hide them. CodeIgniter provides three functions as shown below to handle errors."
},
{
"code": null,
"e": 3320,
"s": 3241,
"text": "show_error() function displays errors in HTML format at the top of the screen."
},
{
"code": null,
"e": 3399,
"s": 3320,
"text": "show_error() function displays errors in HTML format at the top of the screen."
},
{
"code": null,
"e": 3406,
"s": 3399,
"text": "Syntax"
},
{
"code": null,
"e": 3417,
"s": 3406,
"text": "Parameters"
},
{
"code": null,
"e": 3450,
"s": 3417,
"text": "$message (mixed) − Error message"
},
{
"code": null,
"e": 3483,
"s": 3450,
"text": "$message (mixed) − Error message"
},
{
"code": null,
"e": 3530,
"s": 3483,
"text": "$status_code (int) − HTTP Response status code"
},
{
"code": null,
"e": 3577,
"s": 3530,
"text": "$status_code (int) − HTTP Response status code"
},
{
"code": null,
"e": 3616,
"s": 3577,
"text": "$heading (string) − Error page heading"
},
{
"code": null,
"e": 3655,
"s": 3616,
"text": "$heading (string) − Error page heading"
},
{
"code": null,
"e": 3667,
"s": 3655,
"text": "Return Type"
},
{
"code": null,
"e": 3759,
"s": 3667,
"text": "show_404() function displays error if you are trying to access a page which does not exist."
},
{
"code": null,
"e": 3851,
"s": 3759,
"text": "show_404() function displays error if you are trying to access a page which does not exist."
},
{
"code": null,
"e": 3858,
"s": 3851,
"text": "Syntax"
},
{
"code": null,
"e": 3869,
"s": 3858,
"text": "Parameters"
},
{
"code": null,
"e": 3897,
"s": 3869,
"text": "$page (string) – URI string"
},
{
"code": null,
"e": 3925,
"s": 3897,
"text": "$page (string) – URI string"
},
{
"code": null,
"e": 3970,
"s": 3925,
"text": "$log_error (bool) – Whether to log the error"
},
{
"code": null,
"e": 4015,
"s": 3970,
"text": "$log_error (bool) – Whether to log the error"
},
{
"code": null,
"e": 4027,
"s": 4015,
"text": "Return Type"
},
{
"code": null,
"e": 4136,
"s": 4027,
"text": "log_message() function is used to write log messages. This is useful when you want to write custom messages."
},
{
"code": null,
"e": 4245,
"s": 4136,
"text": "log_message() function is used to write log messages. This is useful when you want to write custom messages."
},
{
"code": null,
"e": 4252,
"s": 4245,
"text": "Syntax"
},
{
"code": null,
"e": 4263,
"s": 4252,
"text": "Parameters"
},
{
"code": null,
"e": 4319,
"s": 4263,
"text": "$level (string) − Log level: ‘error’, ‘debug’ or ‘info’"
},
{
"code": null,
"e": 4375,
"s": 4319,
"text": "$level (string) − Log level: ‘error’, ‘debug’ or ‘info’"
},
{
"code": null,
"e": 4410,
"s": 4375,
"text": "$message (string) − Message to log"
},
{
"code": null,
"e": 4445,
"s": 4410,
"text": "$message (string) − Message to log"
},
{
"code": null,
"e": 4514,
"s": 4445,
"text": "$php_error (bool) − Whether we’re logging a native PHP error message"
},
{
"code": null,
"e": 4583,
"s": 4514,
"text": "$php_error (bool) − Whether we’re logging a native PHP error message"
},
{
"code": null,
"e": 4595,
"s": 4583,
"text": "Return Type"
},
{
"code": null,
"e": 4742,
"s": 4595,
"text": "Logging can be enabled in application/config/config.php file. Given below is the screenshot of config.php file, where you can set threshold value."
},
{
"code": null,
"e": 5537,
"s": 4742,
"text": "/*\n|--------------------------------------------------------------------------------\n| Error Logging Threshold\n|--------------------------------------------------------------------------------\n| You can enable error logging by setting a threshold over zero. The \n| threshold determines what gets logged. Threshold options are:\n|\n| 0 = Disable logging, Error logging TURNED OFF\n| 1 = Error Message (including PHP errors)\n| 2 = Debug Message\n| 3 = Informational Messages\n| 4 = All Messages\n|\n| You can also pass an array with threshold levels to show individual error types\n|\n| array(2) = Debug Message, without Error Messages\n| For a live site you'll usually only enable Errors (1) to be logged otherwise \n| your log files will fill up very fast.\n|\n*/\n$config['log_threshold'] = 0;"
},
{
"code": null,
"e": 5659,
"s": 5537,
"text": "You can find the log messages in application/log/. Make sure that this directory is writable before you enable log files."
},
{
"code": null,
"e": 5775,
"s": 5659,
"text": "Various templates for error messages can be found in application/views/errors/cli or application/views/errors/html."
},
{
"code": null,
"e": 5782,
"s": 5775,
"text": " Print"
},
{
"code": null,
"e": 5793,
"s": 5782,
"text": " Add Notes"
}
] |
How compare() method works in Java - GeeksforGeeks
|
19 Jul, 2021
Prerequisite: Comparator Interface in Java, TreeSet in JavaThe compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value:
0: if (x==y)
-1: if (x < y)
1: if (x > y)
Syntax:
public int compare(Object obj1, Object obj2)
where obj1 and obj2 are the two objects to be compared using compare() method.
To show working of compare() method using Integer Class.
Java
// Java program to demonstrate working// of compare() method using Integer Class import java.lang.Integer; class Gfg { // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, // Output will be a value less than zero System.out.println(Integer.compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, // Output will be zero System.out.println(Integer.compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, // Output will be a value greater than zero System.out.println(Integer.compare(w, z)); }}
-1
0
1
The internal working of the compare() method can be visualized with the help of below pseudocode:
Java
// Converting the two objects to integer// for comparisonint intObj1 = (int)obj1;int intObj2 = (int)obj2; // Get the differenceint difference = intObj1 - intObj2; if (difference == 0) { // Both are equal return 0;}else if (difference < 0) { // obj1 < obj2 return -1;}else { // obj1 > obj2 return 1;}
Java
// Java program to demonstrate working// of compare() method import java.lang.Integer; class Gfg { // Function to compare both objects public static int compare(Object obj1, Object obj2) { // Converting the two objects to integer // for comparison int intObj1 = (int)obj1; int intObj2 = (int)obj2; // Get the difference int difference = intObj1 - intObj2; if (difference == 0) { // Both are equal return 0; } else if (difference < 0) { // obj1 < obj2 return -1; } else { // obj1 > obj2 return 1; } } // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, // Output will be a value less than zero System.out.println(compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, // Output will be zero System.out.println(compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, // Output will be a value greater than zero System.out.println(compare(w, z)); }}
-1
0
1
public int compare(Object obj1, Object obj2)
{
Integer I1 = (Integer)obj1; // typecasting object type into integer type
Integer I2 = (Integer)obj2; // same as above ..
// 1.
return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]
// 2.
return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]
// 3.
return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]
// 4.
return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]
// 5.
return +1; // insertion order [10, 0, 15, 5, 20, 20]
// 6.
return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]
// 7.
return 0; // only first element [10]
}
nidhi_biet
arorakashish0911
java-basics
Articles
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
SQL Interview Questions
Mutex vs Semaphore
Understanding "extern" keyword in C
How to write a Pseudo Code?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 26116,
"s": 26088,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 26291,
"s": 26116,
"text": "Prerequisite: Comparator Interface in Java, TreeSet in JavaThe compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: "
},
{
"code": null,
"e": 26304,
"s": 26291,
"text": "0: if (x==y)"
},
{
"code": null,
"e": 26319,
"s": 26304,
"text": "-1: if (x < y)"
},
{
"code": null,
"e": 26333,
"s": 26319,
"text": "1: if (x > y)"
},
{
"code": null,
"e": 26343,
"s": 26333,
"text": "Syntax: "
},
{
"code": null,
"e": 26388,
"s": 26343,
"text": "public int compare(Object obj1, Object obj2)"
},
{
"code": null,
"e": 26468,
"s": 26388,
"text": "where obj1 and obj2 are the two objects to be compared using compare() method. "
},
{
"code": null,
"e": 26525,
"s": 26468,
"text": "To show working of compare() method using Integer Class."
},
{
"code": null,
"e": 26530,
"s": 26525,
"text": "Java"
},
{
"code": "// Java program to demonstrate working// of compare() method using Integer Class import java.lang.Integer; class Gfg { // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, // Output will be a value less than zero System.out.println(Integer.compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, // Output will be zero System.out.println(Integer.compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, // Output will be a value greater than zero System.out.println(Integer.compare(w, z)); }}",
"e": 27210,
"s": 26530,
"text": null
},
{
"code": null,
"e": 27217,
"s": 27210,
"text": "-1\n0\n1"
},
{
"code": null,
"e": 27317,
"s": 27219,
"text": "The internal working of the compare() method can be visualized with the help of below pseudocode:"
},
{
"code": null,
"e": 27322,
"s": 27317,
"text": "Java"
},
{
"code": "// Converting the two objects to integer// for comparisonint intObj1 = (int)obj1;int intObj2 = (int)obj2; // Get the differenceint difference = intObj1 - intObj2; if (difference == 0) { // Both are equal return 0;}else if (difference < 0) { // obj1 < obj2 return -1;}else { // obj1 > obj2 return 1;}",
"e": 27643,
"s": 27322,
"text": null
},
{
"code": null,
"e": 27648,
"s": 27643,
"text": "Java"
},
{
"code": "// Java program to demonstrate working// of compare() method import java.lang.Integer; class Gfg { // Function to compare both objects public static int compare(Object obj1, Object obj2) { // Converting the two objects to integer // for comparison int intObj1 = (int)obj1; int intObj2 = (int)obj2; // Get the difference int difference = intObj1 - intObj2; if (difference == 0) { // Both are equal return 0; } else if (difference < 0) { // obj1 < obj2 return -1; } else { // obj1 > obj2 return 1; } } // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, // Output will be a value less than zero System.out.println(compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, // Output will be zero System.out.println(compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, // Output will be a value greater than zero System.out.println(compare(w, z)); }}",
"e": 28854,
"s": 27648,
"text": null
},
{
"code": null,
"e": 28861,
"s": 28854,
"text": "-1\n0\n1"
},
{
"code": null,
"e": 29549,
"s": 28863,
"text": "public int compare(Object obj1, Object obj2)\n{\n Integer I1 = (Integer)obj1; // typecasting object type into integer type\n Integer I2 = (Integer)obj2; // same as above ..\n // 1.\n return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]\n // 2.\n return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]\n // 3.\n return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]\n // 4.\n return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]\n // 5.\n return +1; // insertion order [10, 0, 15, 5, 20, 20]\n // 6.\n return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]\n // 7.\n return 0; // only first element [10]\n}"
},
{
"code": null,
"e": 29560,
"s": 29549,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29577,
"s": 29560,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29589,
"s": 29577,
"text": "java-basics"
},
{
"code": null,
"e": 29598,
"s": 29589,
"text": "Articles"
},
{
"code": null,
"e": 29603,
"s": 29598,
"text": "Java"
},
{
"code": null,
"e": 29622,
"s": 29603,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29627,
"s": 29622,
"text": "Java"
},
{
"code": null,
"e": 29725,
"s": 29627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29778,
"s": 29725,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 29802,
"s": 29778,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 29821,
"s": 29802,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 29857,
"s": 29821,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 29885,
"s": 29857,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 29900,
"s": 29885,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29944,
"s": 29900,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29966,
"s": 29944,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29981,
"s": 29966,
"text": "Stream In Java"
}
] |
compress command in Linux with examples - GeeksforGeeks
|
15 May, 2019
compress command is used to reduce the file size. After compression, the file will be available with an added .Z extension. File permissions will still remain the same as before using compress command. This command uses the adaptive Lempel-Ziv coding and it ignores the symbolic links. And also this command is part of ncompress package, which contains utilities for fast compression and decompression.
Note: If no files are specified then the standard input is compressed to the standard output.
Syntax:
compress [OPTION]... [FILE]...
Options:
-v Option: It is used to print the percentage reduction of each file. This option is ignored if the -c option is also used. Compress example.xls and rename that file to example.xls.Z with a percentage reduction of 70.41%.compress -v example.xls
compress -v example.xls
-c Option: Compressed or uncompressed output is written to the standard output. No files are modified. The -v option is ignored. Compression is attempted even if the results will be larger than the original.Example:compress -c example.xls > new.Z
Example:
compress -c example.xls > new.Z
-r Option: This will compress all the files in the given directory and sub-directories recursively. It is helpful to combine the -r option with -v to see exactly what the command is doing.Example:compress -rv abc
This will compress all the files within abc.
Example:
compress -rv abc
This will compress all the files within abc.
-f Option: This will compress files without any guarantee of size reduction, meaning it will compress files even if the file size is not reduced.compress -f asc.txt
This will convert asc.txt into asc.txt.Z but size reduction is not assured.
compress -f asc.txt
This will convert asc.txt into asc.txt.Z but size reduction is not assured.
linux-command
Linux-file-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
|
[
{
"code": null,
"e": 25761,
"s": 25733,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 26164,
"s": 25761,
"text": "compress command is used to reduce the file size. After compression, the file will be available with an added .Z extension. File permissions will still remain the same as before using compress command. This command uses the adaptive Lempel-Ziv coding and it ignores the symbolic links. And also this command is part of ncompress package, which contains utilities for fast compression and decompression."
},
{
"code": null,
"e": 26258,
"s": 26164,
"text": "Note: If no files are specified then the standard input is compressed to the standard output."
},
{
"code": null,
"e": 26266,
"s": 26258,
"text": "Syntax:"
},
{
"code": null,
"e": 26298,
"s": 26266,
"text": "compress [OPTION]... [FILE]...\n"
},
{
"code": null,
"e": 26307,
"s": 26298,
"text": "Options:"
},
{
"code": null,
"e": 26553,
"s": 26307,
"text": "-v Option: It is used to print the percentage reduction of each file. This option is ignored if the -c option is also used. Compress example.xls and rename that file to example.xls.Z with a percentage reduction of 70.41%.compress -v example.xls\n"
},
{
"code": null,
"e": 26578,
"s": 26553,
"text": "compress -v example.xls\n"
},
{
"code": null,
"e": 26826,
"s": 26578,
"text": "-c Option: Compressed or uncompressed output is written to the standard output. No files are modified. The -v option is ignored. Compression is attempted even if the results will be larger than the original.Example:compress -c example.xls > new.Z\n"
},
{
"code": null,
"e": 26835,
"s": 26826,
"text": "Example:"
},
{
"code": null,
"e": 26868,
"s": 26835,
"text": "compress -c example.xls > new.Z\n"
},
{
"code": null,
"e": 27126,
"s": 26868,
"text": "-r Option: This will compress all the files in the given directory and sub-directories recursively. It is helpful to combine the -r option with -v to see exactly what the command is doing.Example:compress -rv abc\nThis will compress all the files within abc."
},
{
"code": null,
"e": 27135,
"s": 27126,
"text": "Example:"
},
{
"code": null,
"e": 27153,
"s": 27135,
"text": "compress -rv abc\n"
},
{
"code": null,
"e": 27198,
"s": 27153,
"text": "This will compress all the files within abc."
},
{
"code": null,
"e": 27439,
"s": 27198,
"text": "-f Option: This will compress files without any guarantee of size reduction, meaning it will compress files even if the file size is not reduced.compress -f asc.txt\nThis will convert asc.txt into asc.txt.Z but size reduction is not assured."
},
{
"code": null,
"e": 27460,
"s": 27439,
"text": "compress -f asc.txt\n"
},
{
"code": null,
"e": 27536,
"s": 27460,
"text": "This will convert asc.txt into asc.txt.Z but size reduction is not assured."
},
{
"code": null,
"e": 27550,
"s": 27536,
"text": "linux-command"
},
{
"code": null,
"e": 27570,
"s": 27550,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 27577,
"s": 27570,
"text": "Picked"
},
{
"code": null,
"e": 27601,
"s": 27577,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27612,
"s": 27601,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27631,
"s": 27612,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27729,
"s": 27631,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27764,
"s": 27729,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27798,
"s": 27764,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27835,
"s": 27798,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27861,
"s": 27835,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27898,
"s": 27861,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27927,
"s": 27898,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27969,
"s": 27927,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28005,
"s": 27969,
"text": "uniq Command in LINUX with examples"
},
{
"code": null,
"e": 28031,
"s": 28005,
"text": "Thread functions in C/C++"
}
] |
Check if two nodes are on same path in a tree | Set 2 - GeeksforGeeks
|
21 Jun, 2021
Given two nodes of a binary tree v1 and v2, the task is to check if two nodes are on the same path in a tree. Example:
Input: v1 = 1, v2 = 5
1
/ | \
2 3 4
/ | \
5 6 7
Output: Yes
Explanation:
Both nodes 1 and 5
lie in the path 1 -> 2 -> 5.
Input: v1 = 2, v2 = 6
1
/ | \
2 3 4
/ | \
5 6 7
Output: NO
DFS Approach: Refer to Check if two nodes are on same path in a tree for the DFS approach.LCA Approach: The idea is to use Lowest Common Ancestor. Find the LCA of the given vertices v1 and v2. If the LCA is equal to any of the given two vertices, print Yes. Otherwise, print No.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if two nodes// are on same path in a tree without// using any extra space#include <bits/stdc++.h>using namespace std; // Function to filter// the return Valuesint filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notint samePathUtil(int mtrx[][7], int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for (int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil(mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notbool isVertexAtSamePath(int mtrx[][7], int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver Programint main(){ int vrtx = 7, edge = 6; int mtrx[7][7] = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if two nodes// are on same path in a tree without// using any extra spaceclass GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int mtrx[][], int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notstatic boolean isVertexAtSamePath(int mtrx[][], int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver codepublic static void main(String[] args){ int vrtx = 7; int mtrx[][] = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Rajput-Ji
# Python3 program to check if two nodes# are on same path in a tree without# using any extra space # Function to filter# the return Valuesdef filter(x, y, z): if (x != -1 and y != -1): return z return y if x == -1 else x # Utility function to check if nodes# are on same path or notdef samePathUtil(mtrx, vrtx, v1, v2, i): ans = -1 # Condition to check # if any vertex # is equal to given two # vertex or not if (i == v1 or i == v2): return i for j in range(0, vrtx): # Check if the current # position has 1 if (mtrx[i][j] == 1): # Recursive call ans = filter(ans, samePathUtil(mtrx, vrtx, v1, v2, j), i) # Return LCA return ans # Function to check if nodes# lies on same path or notdef isVertexAtSamePath(mtrx, vrtx, v1, v2, i): lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i) if (lca == v1 - 1 or lca == v2 - 1): return True return False # Driver codevrtx = 7edge = 6 mtrx = [ [ 0, 1, 1, 1, 0, 0, 0 ] , [ 0, 0, 0, 0, 1, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ] ] v1 = 1v2 = 5 if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)): print("Yes")else: print("No") # This code is contributed by sanjoy_62
// C# program to check if two nodes// are on same path in a tree without// using any extra spaceusing System;class GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int [,]mtrx, int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i,j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notstatic bool isVertexAtSamePath(int [,]mtrx, int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver codepublic static void Main(String[] args){ int vrtx = 7; int [,]mtrx = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by sapnasingh4991
<script> // Javascript program to check if two nodes // are on same path in a tree without // using any extra space // Function to filter // the return Values function filter(x, y, z) { if (x != -1 && y != -1) { return z; } return x == -1 ? y : x; } // Utility function to check if nodes // are on same path or not function samePathUtil(mtrx, vrtx, v1, v2, i) { let ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(let j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans; } // Function to check if nodes // lies on same path or not function isVertexAtSamePath(mtrx, vrtx, v1, v2, i) { let lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false; } let vrtx = 7; let mtrx = [ [ 0, 1, 1, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ] ]; let v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) document.write("Yes"); else document.write("No"); // This code is contributed by mukesh07. </script>
Yes
Time Complexity: O(N) Auxiliary Space: O(1)
Rajput-Ji
sapnasingh4991
sanjoy_62
mukesh07
interview-preparation
LCA
Samsung
Competitive Programming
Data Structures
Placements
Tree
Samsung
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
7 Best Coding Challenge Websites in 2020
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
How to Start Learning DSA?
|
[
{
"code": null,
"e": 26337,
"s": 26309,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 26458,
"s": 26337,
"text": "Given two nodes of a binary tree v1 and v2, the task is to check if two nodes are on the same path in a tree. Example: "
},
{
"code": null,
"e": 26717,
"s": 26458,
"text": "Input: v1 = 1, v2 = 5\n 1\n / | \\\n 2 3 4\n / | \\\n 5 6 7\n \nOutput: Yes\nExplanation:\nBoth nodes 1 and 5\nlie in the path 1 -> 2 -> 5.\n\nInput: v1 = 2, v2 = 6\n 1\n / | \\\n 2 3 4\n / | \\\n 5 6 7\n\nOutput: NO"
},
{
"code": null,
"e": 27042,
"s": 26717,
"text": "DFS Approach: Refer to Check if two nodes are on same path in a tree for the DFS approach.LCA Approach: The idea is to use Lowest Common Ancestor. Find the LCA of the given vertices v1 and v2. If the LCA is equal to any of the given two vertices, print Yes. Otherwise, print No.Below is the implementation of above approach:"
},
{
"code": null,
"e": 27046,
"s": 27042,
"text": "C++"
},
{
"code": null,
"e": 27051,
"s": 27046,
"text": "Java"
},
{
"code": null,
"e": 27059,
"s": 27051,
"text": "Python3"
},
{
"code": null,
"e": 27062,
"s": 27059,
"text": "C#"
},
{
"code": null,
"e": 27073,
"s": 27062,
"text": "Javascript"
},
{
"code": "// C++ program to check if two nodes// are on same path in a tree without// using any extra space#include <bits/stdc++.h>using namespace std; // Function to filter// the return Valuesint filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notint samePathUtil(int mtrx[][7], int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for (int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil(mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notbool isVertexAtSamePath(int mtrx[][7], int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver Programint main(){ int vrtx = 7, edge = 6; int mtrx[7][7] = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 29016,
"s": 27073,
"text": null
},
{
"code": "// Java program to check if two nodes// are on same path in a tree without// using any extra spaceclass GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int mtrx[][], int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notstatic boolean isVertexAtSamePath(int mtrx[][], int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver codepublic static void main(String[] args){ int vrtx = 7; int mtrx[][] = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Rajput-Ji",
"e": 30972,
"s": 29016,
"text": null
},
{
"code": "# Python3 program to check if two nodes# are on same path in a tree without# using any extra space # Function to filter# the return Valuesdef filter(x, y, z): if (x != -1 and y != -1): return z return y if x == -1 else x # Utility function to check if nodes# are on same path or notdef samePathUtil(mtrx, vrtx, v1, v2, i): ans = -1 # Condition to check # if any vertex # is equal to given two # vertex or not if (i == v1 or i == v2): return i for j in range(0, vrtx): # Check if the current # position has 1 if (mtrx[i][j] == 1): # Recursive call ans = filter(ans, samePathUtil(mtrx, vrtx, v1, v2, j), i) # Return LCA return ans # Function to check if nodes# lies on same path or notdef isVertexAtSamePath(mtrx, vrtx, v1, v2, i): lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i) if (lca == v1 - 1 or lca == v2 - 1): return True return False # Driver codevrtx = 7edge = 6 mtrx = [ [ 0, 1, 1, 1, 0, 0, 0 ] , [ 0, 0, 0, 0, 1, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ] ] v1 = 1v2 = 5 if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)): print(\"Yes\")else: print(\"No\") # This code is contributed by sanjoy_62",
"e": 32472,
"s": 30972,
"text": null
},
{
"code": "// C# program to check if two nodes// are on same path in a tree without// using any extra spaceusing System;class GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){ if (x != -1 && y != -1) { return z; } return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int [,]mtrx, int vrtx, int v1, int v2, int i){ int ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(int j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i,j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans;} // Function to check if nodes// lies on same path or notstatic bool isVertexAtSamePath(int [,]mtrx, int vrtx, int v1, int v2, int i){ int lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false;} // Driver codepublic static void Main(String[] args){ int vrtx = 7; int [,]mtrx = { { 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; int v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by sapnasingh4991",
"e": 34419,
"s": 32472,
"text": null
},
{
"code": "<script> // Javascript program to check if two nodes // are on same path in a tree without // using any extra space // Function to filter // the return Values function filter(x, y, z) { if (x != -1 && y != -1) { return z; } return x == -1 ? y : x; } // Utility function to check if nodes // are on same path or not function samePathUtil(mtrx, vrtx, v1, v2, i) { let ans = -1; // Condition to check // if any vertex // is equal to given two // vertex or not if (i == v1 || i == v2) return i; for(let j = 0; j < vrtx; j++) { // Check if the current // position has 1 if (mtrx[i][j] == 1) { // Recursive call ans = filter(ans, samePathUtil( mtrx, vrtx, v1, v2, j), i); } } // Return LCA return ans; } // Function to check if nodes // lies on same path or not function isVertexAtSamePath(mtrx, vrtx, v1, v2, i) { let lca = samePathUtil(mtrx, vrtx, v1 - 1, v2 - 1, i); if (lca == v1 - 1 || lca == v2 - 1) return true; return false; } let vrtx = 7; let mtrx = [ [ 0, 1, 1, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0 ], [ 0, 0, 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 1 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ] ]; let v1 = 1, v2 = 5; if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by mukesh07. </script>",
"e": 36262,
"s": 34419,
"text": null
},
{
"code": null,
"e": 36266,
"s": 36262,
"text": "Yes"
},
{
"code": null,
"e": 36313,
"s": 36268,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 36323,
"s": 36313,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36338,
"s": 36323,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 36348,
"s": 36338,
"text": "sanjoy_62"
},
{
"code": null,
"e": 36357,
"s": 36348,
"text": "mukesh07"
},
{
"code": null,
"e": 36379,
"s": 36357,
"text": "interview-preparation"
},
{
"code": null,
"e": 36383,
"s": 36379,
"text": "LCA"
},
{
"code": null,
"e": 36391,
"s": 36383,
"text": "Samsung"
},
{
"code": null,
"e": 36415,
"s": 36391,
"text": "Competitive Programming"
},
{
"code": null,
"e": 36431,
"s": 36415,
"text": "Data Structures"
},
{
"code": null,
"e": 36442,
"s": 36431,
"text": "Placements"
},
{
"code": null,
"e": 36447,
"s": 36442,
"text": "Tree"
},
{
"code": null,
"e": 36455,
"s": 36447,
"text": "Samsung"
},
{
"code": null,
"e": 36471,
"s": 36455,
"text": "Data Structures"
},
{
"code": null,
"e": 36476,
"s": 36471,
"text": "Tree"
},
{
"code": null,
"e": 36574,
"s": 36476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36652,
"s": 36574,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 36681,
"s": 36652,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 36719,
"s": 36681,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 36778,
"s": 36719,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 36819,
"s": 36778,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 36868,
"s": 36819,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 36912,
"s": 36868,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36937,
"s": 36912,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36993,
"s": 36937,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
PostgreSQL - CREATE FUNCTION Statement - GeeksforGeeks
|
28 Aug, 2020
In PostgreSQL CREATE FUNCTION statement to develop user-defined functions.
Syntax:
create [or replace] function function_name(param_list)
returns return_type
language plpgsql
as
$$
declare
-- variable declaration
begin
-- logic
end;
$$
Let’s analyze the above syntax:
First, specify the name of the function after the create function keywords. If you want to replace the existing function, you can use the replace keywords.
Then, specify the function parameter list surrounded by parentheses after the function name. A function can have zero or many parameters.
Next, specify the datatype of the returned value after the returns keyword.
After that, use the language plpgsql to specify the procedural language of the function. Note that PostgreSQL supports many procedural languages, not just plpgsql.
Finally, place a block in the dollar-quoted string constant.
For the purpose of example, we will use the sample database ie, dvdrental.
Example:
The following statement creates a function that counts the films whose length between the len_from and len_to parameters:
create function get_film_count(len_from int, len_to int)
returns int
language plpgsql
as
$$
declare
film_count integer;
begin
select count(*)
into film_count
from film
where length between len_from and len_to;
return film_count;
end;
$$;
The function get_film_count has two main sections: header and body.
In the Header section:
First, the name of the function is get_film_count that follows the create function keywords.
Second, the get_film_count() function accepts two parameters len_from and len_to with the integer datatype.
Third, the get_film_count function returns an integer specified by the returns int clause
Finally, the language of the function is plpgsql indicated by the language plpgsql.
In the Body section:
Use the dollar-quoted string constant syntax that starts with $$ and ends with $$. Between these $$, you can place a block that contains the declaration and logic of the function.
In the declaration section, declare a variable called film_count that stores the number of films selected from the film table.
In the body of the block, use the select into statement to select the number of films whose length is between len_from and len_to and assign the result to the film_count variable. At the end of the block, use the return statement to return the film_count.
Now that we got familiar with the structure of the CREATE FUNCTION statement, let’s create a function using the same.
First, launch the psql interactive tool and connect to the dvdrental database and enter the above code in the psql to create the function like this:
create function get_film_count(len_from int, len_to int)
returns int
language plpgsql
as
$$
declare
film_count integer;
begin
select count(*)
into film_count
from film
where length between len_from and len_to;
return film_count;
end;
$$;
You will see the following message if the function is created successfully as shown below:
Finally, use the below command to list all user-defined in the current database:
\df
This will show you all the user-defined functions in the database as shown below:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - Function Returning A Table
PostgreSQL - For Loops
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Cursor
PostgreSQL - Record type variable
PostgreSQL - Copy Table
|
[
{
"code": null,
"e": 27920,
"s": 27892,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 27995,
"s": 27920,
"text": "In PostgreSQL CREATE FUNCTION statement to develop user-defined functions."
},
{
"code": null,
"e": 28167,
"s": 27995,
"text": "Syntax:\ncreate [or replace] function function_name(param_list)\n returns return_type \n language plpgsql\n as\n$$\ndeclare \n-- variable declaration\nbegin\n -- logic\nend;\n$$"
},
{
"code": null,
"e": 28199,
"s": 28167,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 28355,
"s": 28199,
"text": "First, specify the name of the function after the create function keywords. If you want to replace the existing function, you can use the replace keywords."
},
{
"code": null,
"e": 28493,
"s": 28355,
"text": "Then, specify the function parameter list surrounded by parentheses after the function name. A function can have zero or many parameters."
},
{
"code": null,
"e": 28569,
"s": 28493,
"text": "Next, specify the datatype of the returned value after the returns keyword."
},
{
"code": null,
"e": 28733,
"s": 28569,
"text": "After that, use the language plpgsql to specify the procedural language of the function. Note that PostgreSQL supports many procedural languages, not just plpgsql."
},
{
"code": null,
"e": 28794,
"s": 28733,
"text": "Finally, place a block in the dollar-quoted string constant."
},
{
"code": null,
"e": 28869,
"s": 28794,
"text": "For the purpose of example, we will use the sample database ie, dvdrental."
},
{
"code": null,
"e": 28878,
"s": 28869,
"text": "Example:"
},
{
"code": null,
"e": 29000,
"s": 28878,
"text": "The following statement creates a function that counts the films whose length between the len_from and len_to parameters:"
},
{
"code": null,
"e": 29261,
"s": 29000,
"text": "create function get_film_count(len_from int, len_to int)\nreturns int\nlanguage plpgsql\nas\n$$\ndeclare\n film_count integer;\nbegin\n select count(*) \n into film_count\n from film\n where length between len_from and len_to;\n \n return film_count;\nend;\n$$;"
},
{
"code": null,
"e": 29330,
"s": 29261,
"text": "The function get_film_count has two main sections: header and body. "
},
{
"code": null,
"e": 29353,
"s": 29330,
"text": "In the Header section:"
},
{
"code": null,
"e": 29446,
"s": 29353,
"text": "First, the name of the function is get_film_count that follows the create function keywords."
},
{
"code": null,
"e": 29554,
"s": 29446,
"text": "Second, the get_film_count() function accepts two parameters len_from and len_to with the integer datatype."
},
{
"code": null,
"e": 29644,
"s": 29554,
"text": "Third, the get_film_count function returns an integer specified by the returns int clause"
},
{
"code": null,
"e": 29728,
"s": 29644,
"text": "Finally, the language of the function is plpgsql indicated by the language plpgsql."
},
{
"code": null,
"e": 29749,
"s": 29728,
"text": "In the Body section:"
},
{
"code": null,
"e": 29929,
"s": 29749,
"text": "Use the dollar-quoted string constant syntax that starts with $$ and ends with $$. Between these $$, you can place a block that contains the declaration and logic of the function."
},
{
"code": null,
"e": 30056,
"s": 29929,
"text": "In the declaration section, declare a variable called film_count that stores the number of films selected from the film table."
},
{
"code": null,
"e": 30312,
"s": 30056,
"text": "In the body of the block, use the select into statement to select the number of films whose length is between len_from and len_to and assign the result to the film_count variable. At the end of the block, use the return statement to return the film_count."
},
{
"code": null,
"e": 30430,
"s": 30312,
"text": "Now that we got familiar with the structure of the CREATE FUNCTION statement, let’s create a function using the same."
},
{
"code": null,
"e": 30579,
"s": 30430,
"text": "First, launch the psql interactive tool and connect to the dvdrental database and enter the above code in the psql to create the function like this:"
},
{
"code": null,
"e": 30845,
"s": 30579,
"text": "create function get_film_count(len_from int, len_to int)\n returns int\n language plpgsql\n as\n $$\n declare\n film_count integer;\n begin\n select count(*)\n into film_count\n from film\n where length between len_from and len_to;\n\n return film_count;\n end;\n$$;"
},
{
"code": null,
"e": 30936,
"s": 30845,
"text": "You will see the following message if the function is created successfully as shown below:"
},
{
"code": null,
"e": 31017,
"s": 30936,
"text": "Finally, use the below command to list all user-defined in the current database:"
},
{
"code": null,
"e": 31021,
"s": 31017,
"text": "\\df"
},
{
"code": null,
"e": 31103,
"s": 31021,
"text": "This will show you all the user-defined functions in the database as shown below:"
},
{
"code": null,
"e": 31123,
"s": 31103,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 31134,
"s": 31123,
"text": "PostgreSQL"
},
{
"code": null,
"e": 31232,
"s": 31134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31241,
"s": 31232,
"text": "Comments"
},
{
"code": null,
"e": 31254,
"s": 31241,
"text": "Old Comments"
},
{
"code": null,
"e": 31286,
"s": 31254,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 31313,
"s": 31286,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 31353,
"s": 31313,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 31376,
"s": 31353,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 31431,
"s": 31376,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 31465,
"s": 31431,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 31489,
"s": 31465,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 31509,
"s": 31489,
"text": "PostgreSQL - Cursor"
},
{
"code": null,
"e": 31543,
"s": 31509,
"text": "PostgreSQL - Record type variable"
}
] |
A Kubernetes architecture for machine learning web-application deployments | by Geoffroy Gobert | Towards Data Science
|
Kubernetes became the reference for container orchestration. Container orchestration means starting containers, shutting them down, scaling them vertically (quantity of memory and CPU attributed), and scaling them horizontally (number of containers running in parallel).
Does Kubernetes add value to machine learning? Machine Learning needs a lot of resources for training a model, but a little resource for serving prediction. Kubernetes adapts the resources automatically! Machine learning usually implies a long training duration, that can be shortened by distributing the task over several computers. Kubernetes shines in adapting the number of computers necessary. In general, Kubernetes reduces infrastructure costs by requiring only the necessary resources over time.
This article describes a Kubernetes architecture for machine-learning web-application. The term “Kubernetes architecture” answers the question “how is the application deployed into Kubernetes?”. This article answers this question in 4 parts that:
Define a machine learning web-application.Analyze the requirements for deploying the machine learning web-application to production.Suggest a Kubernetes architecture for deploying machine learning web-application.Adapt the architecture for distributed training.
Define a machine learning web-application.
Analyze the requirements for deploying the machine learning web-application to production.
Suggest a Kubernetes architecture for deploying machine learning web-application.
Adapt the architecture for distributed training.
If you are interested in this article, you might also be interested in:
towardsdatascience.com
On a high level, a machine learning application is responsible for two things:
training a model: based on a training dataset, it trains an estimatorserving predictions: based on the trained estimator and new data, it predicts new values
training a model: based on a training dataset, it trains an estimator
serving predictions: based on the trained estimator and new data, it predicts new values
One example: demand-forecaster
Imagine an application that forecasts the demand of scooters in an area of a city. Its inputs and outputs are in red. In the next step, each input and output will be mapped to its Kubernetes component.
Input: It reads the historical demand from a database.
Output: It serves the predictions with a REST API. Uvicorn is the webserver.
Serialization: It writes and reads the trained estimator on the hard drive. This is the output of the training phase, and it is the input of the prediction phase.
Requirements for deploying machine learning web-applications:
Ensure consistency between the code and the estimator. Changing the estimator library (e.g. version of sklearn, xgboost, tensorflow) might require re-training the model. Adding a feature, updating a feature, or deleting a feature also requires re-training the model. And because a web-application is constantly serving prediction, discrepancies between the deployed code and the estimator must be avoided.Avoid model drift. A model trained yesterday will be less accurate tomorrow. This is called model drift. It matters more in some areas than in others. In forecasting, the latest observation matters, so the model is drifting fast. On the opposite, in computer vision, if the task is about to classify different types of cars, the model drifts when new models of cars are available. In order to be more accurate, model drift must be avoided.Scaling vertically. Training a model requires a lot of memory. To avoid out-of-memory errors, a sufficient quantity of memory must be provided.Scaling horizontally. Training machine learning models can be very long. Distributing the training over several computers helps. A sufficient number of computers must be provided.Share trained estimator. The model’s estimator is trained on a computer and predictions are served on another. The predictions can also be served by several computers. The serialized estimator must be shared between all the computers.
Ensure consistency between the code and the estimator. Changing the estimator library (e.g. version of sklearn, xgboost, tensorflow) might require re-training the model. Adding a feature, updating a feature, or deleting a feature also requires re-training the model. And because a web-application is constantly serving prediction, discrepancies between the deployed code and the estimator must be avoided.
Avoid model drift. A model trained yesterday will be less accurate tomorrow. This is called model drift. It matters more in some areas than in others. In forecasting, the latest observation matters, so the model is drifting fast. On the opposite, in computer vision, if the task is about to classify different types of cars, the model drifts when new models of cars are available. In order to be more accurate, model drift must be avoided.
Scaling vertically. Training a model requires a lot of memory. To avoid out-of-memory errors, a sufficient quantity of memory must be provided.
Scaling horizontally. Training machine learning models can be very long. Distributing the training over several computers helps. A sufficient number of computers must be provided.
Share trained estimator. The model’s estimator is trained on a computer and predictions are served on another. The predictions can also be served by several computers. The serialized estimator must be shared between all the computers.
Deploying a machine learning web-application on production adds new requirements. This section presents how they can be solved with Kubernetes.
Kubernetes terminology
Previously, this article spoke about “computers”, in Kubernetes it translates to “pods”.
Pods are the smallest, most basic deployable objects in Kubernetes. A Pod represents a single instance of a running process in your cluster. Pods contain one or more containers, such as Docker containers.
Kubernetes Engine Documentation
But to make things simpler: in this article, each pod will always have one container. This article speaks also about Kubernetes services:
A Kubernetes service is a logical abstraction for a deployed group of pods in a cluster (which all perform the same function). Since pods are ephemeral, a service enables a group of pods, which provide specific functions (web services, image processing, etc.) to be assigned a name and unique IP address (clusterIP).
In this example, Kubernetes will have one service. This service is responsible for forecasting the demand. It will do 2 things: training a machine learning model and serving predictions.
A Kubernetes architecture for machine learning web-applications
Kubernetes job (aka pod-init)
A Kubernetes job is a pod that is executed before the actual deployment, before that the pod of the web server starts. Kubernetes jobs can be used to train the model. So, the consistency between the code and the estimator can be ensured.
Kubernetes cronJob
A Kubernetes cronJob is a pod scheduled for being executed on a regular basis. It can be used to retrain the model on a regular basis (e.g. every day) with the latest data. So, the drift of the model can be avoided.
Kubernetes shared volume
A Kubernetes shared volume shares files between pods. So, the trained estimator can be shared between the pods.
On the schema above, the serialized models are actually saved on AWS S3, but a pure Kubernetes approach is to use shared volumes.
Kubernetes vertical pod autoscaler
A Kubernetes vertical pod autoscaler allocates the required memory and CPU to the pods dynamically over time. So, out-of-memory errors can be avoided and vertical scaling can be ensured.
Horionztal scaling
This requirement is met by 2 components. The number of deployment pods is controlled by Kubernetes horizontal pod autoscaler. It starts and stops pods in order to satisfy the number of simultaneous HTTP-requests. Besides, Kubernetes jobs have a parameter “parallelism” to control how many pods run in parallel. Jobs are used for training the model, and beyond Kubernetes, training a machine learning model in a distributed way requires some adaptation. This is the focus of the next section.
Training the model during deployment makes deployment easier. Contributors don’t need to think: How this new feature will impact the legacy estimator? How will the new normalization of the data impact the legacy estimator? How will the update of the library impact the legacy estimator?
Nonetheless, it has one downside: training the model during deployment (in the pod-initialization step) might last for a long time and make the deployment workflow (CI/CD) inefficient. A slow deployment pipeline is breaking the CI/CD best practices.
In this case, distributing the training over several pods helps. Some libraries are designed to distribute the training of one model: for example MLlib or Tensorflow. This is not the focus of this article.
In other cases, the training is fitting several models, not only one. In this case, it’s easy to distribute the training with a master/worker pattern. Assuming the entry points are bin/master.py and bin/worker.sh, this is a representation of the pods that are orchestrated by Kubernetes:
The light green boxes show the kind of Kubernetes object that is manipulated: they group pod definitions by type. The middle green boxes are the definition of the pod i.e. the YAML like below. The dark green boxes show actual instances of the definition.
apiVersion: batch/v1beta1kind: CronJobspec: schedule: "40 2 * * *"
In a distributed world, Kubernetes orchestrates multiple instances of the pods.
For jobs and cronJobs, first, the pod named “master” is executed: it creates the task in the database (redis, outside of Kubernetes). Then, the workers are starting: they perform the task. The worker processes need to be terminated so that Kubernetes stop the pods and then starts the deployment pods. With celery, the following pseudo-code helped:
Deploying a machine learning web-service adds new requirements like ensuring the consistency between the code and the estimator, scalability, sharing the models between all computers, and avoid model-drift. This article shows one way of solving these requirements with Kubernetes. Besides, it adds great value for reducing infrastructure costs.
|
[
{
"code": null,
"e": 442,
"s": 171,
"text": "Kubernetes became the reference for container orchestration. Container orchestration means starting containers, shutting them down, scaling them vertically (quantity of memory and CPU attributed), and scaling them horizontally (number of containers running in parallel)."
},
{
"code": null,
"e": 946,
"s": 442,
"text": "Does Kubernetes add value to machine learning? Machine Learning needs a lot of resources for training a model, but a little resource for serving prediction. Kubernetes adapts the resources automatically! Machine learning usually implies a long training duration, that can be shortened by distributing the task over several computers. Kubernetes shines in adapting the number of computers necessary. In general, Kubernetes reduces infrastructure costs by requiring only the necessary resources over time."
},
{
"code": null,
"e": 1193,
"s": 946,
"text": "This article describes a Kubernetes architecture for machine-learning web-application. The term “Kubernetes architecture” answers the question “how is the application deployed into Kubernetes?”. This article answers this question in 4 parts that:"
},
{
"code": null,
"e": 1455,
"s": 1193,
"text": "Define a machine learning web-application.Analyze the requirements for deploying the machine learning web-application to production.Suggest a Kubernetes architecture for deploying machine learning web-application.Adapt the architecture for distributed training."
},
{
"code": null,
"e": 1498,
"s": 1455,
"text": "Define a machine learning web-application."
},
{
"code": null,
"e": 1589,
"s": 1498,
"text": "Analyze the requirements for deploying the machine learning web-application to production."
},
{
"code": null,
"e": 1671,
"s": 1589,
"text": "Suggest a Kubernetes architecture for deploying machine learning web-application."
},
{
"code": null,
"e": 1720,
"s": 1671,
"text": "Adapt the architecture for distributed training."
},
{
"code": null,
"e": 1792,
"s": 1720,
"text": "If you are interested in this article, you might also be interested in:"
},
{
"code": null,
"e": 1815,
"s": 1792,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1894,
"s": 1815,
"text": "On a high level, a machine learning application is responsible for two things:"
},
{
"code": null,
"e": 2052,
"s": 1894,
"text": "training a model: based on a training dataset, it trains an estimatorserving predictions: based on the trained estimator and new data, it predicts new values"
},
{
"code": null,
"e": 2122,
"s": 2052,
"text": "training a model: based on a training dataset, it trains an estimator"
},
{
"code": null,
"e": 2211,
"s": 2122,
"text": "serving predictions: based on the trained estimator and new data, it predicts new values"
},
{
"code": null,
"e": 2242,
"s": 2211,
"text": "One example: demand-forecaster"
},
{
"code": null,
"e": 2444,
"s": 2242,
"text": "Imagine an application that forecasts the demand of scooters in an area of a city. Its inputs and outputs are in red. In the next step, each input and output will be mapped to its Kubernetes component."
},
{
"code": null,
"e": 2499,
"s": 2444,
"text": "Input: It reads the historical demand from a database."
},
{
"code": null,
"e": 2576,
"s": 2499,
"text": "Output: It serves the predictions with a REST API. Uvicorn is the webserver."
},
{
"code": null,
"e": 2739,
"s": 2576,
"text": "Serialization: It writes and reads the trained estimator on the hard drive. This is the output of the training phase, and it is the input of the prediction phase."
},
{
"code": null,
"e": 2801,
"s": 2739,
"text": "Requirements for deploying machine learning web-applications:"
},
{
"code": null,
"e": 4202,
"s": 2801,
"text": "Ensure consistency between the code and the estimator. Changing the estimator library (e.g. version of sklearn, xgboost, tensorflow) might require re-training the model. Adding a feature, updating a feature, or deleting a feature also requires re-training the model. And because a web-application is constantly serving prediction, discrepancies between the deployed code and the estimator must be avoided.Avoid model drift. A model trained yesterday will be less accurate tomorrow. This is called model drift. It matters more in some areas than in others. In forecasting, the latest observation matters, so the model is drifting fast. On the opposite, in computer vision, if the task is about to classify different types of cars, the model drifts when new models of cars are available. In order to be more accurate, model drift must be avoided.Scaling vertically. Training a model requires a lot of memory. To avoid out-of-memory errors, a sufficient quantity of memory must be provided.Scaling horizontally. Training machine learning models can be very long. Distributing the training over several computers helps. A sufficient number of computers must be provided.Share trained estimator. The model’s estimator is trained on a computer and predictions are served on another. The predictions can also be served by several computers. The serialized estimator must be shared between all the computers."
},
{
"code": null,
"e": 4608,
"s": 4202,
"text": "Ensure consistency between the code and the estimator. Changing the estimator library (e.g. version of sklearn, xgboost, tensorflow) might require re-training the model. Adding a feature, updating a feature, or deleting a feature also requires re-training the model. And because a web-application is constantly serving prediction, discrepancies between the deployed code and the estimator must be avoided."
},
{
"code": null,
"e": 5048,
"s": 4608,
"text": "Avoid model drift. A model trained yesterday will be less accurate tomorrow. This is called model drift. It matters more in some areas than in others. In forecasting, the latest observation matters, so the model is drifting fast. On the opposite, in computer vision, if the task is about to classify different types of cars, the model drifts when new models of cars are available. In order to be more accurate, model drift must be avoided."
},
{
"code": null,
"e": 5192,
"s": 5048,
"text": "Scaling vertically. Training a model requires a lot of memory. To avoid out-of-memory errors, a sufficient quantity of memory must be provided."
},
{
"code": null,
"e": 5372,
"s": 5192,
"text": "Scaling horizontally. Training machine learning models can be very long. Distributing the training over several computers helps. A sufficient number of computers must be provided."
},
{
"code": null,
"e": 5607,
"s": 5372,
"text": "Share trained estimator. The model’s estimator is trained on a computer and predictions are served on another. The predictions can also be served by several computers. The serialized estimator must be shared between all the computers."
},
{
"code": null,
"e": 5751,
"s": 5607,
"text": "Deploying a machine learning web-application on production adds new requirements. This section presents how they can be solved with Kubernetes."
},
{
"code": null,
"e": 5774,
"s": 5751,
"text": "Kubernetes terminology"
},
{
"code": null,
"e": 5863,
"s": 5774,
"text": "Previously, this article spoke about “computers”, in Kubernetes it translates to “pods”."
},
{
"code": null,
"e": 6068,
"s": 5863,
"text": "Pods are the smallest, most basic deployable objects in Kubernetes. A Pod represents a single instance of a running process in your cluster. Pods contain one or more containers, such as Docker containers."
},
{
"code": null,
"e": 6100,
"s": 6068,
"text": "Kubernetes Engine Documentation"
},
{
"code": null,
"e": 6238,
"s": 6100,
"text": "But to make things simpler: in this article, each pod will always have one container. This article speaks also about Kubernetes services:"
},
{
"code": null,
"e": 6555,
"s": 6238,
"text": "A Kubernetes service is a logical abstraction for a deployed group of pods in a cluster (which all perform the same function). Since pods are ephemeral, a service enables a group of pods, which provide specific functions (web services, image processing, etc.) to be assigned a name and unique IP address (clusterIP)."
},
{
"code": null,
"e": 6742,
"s": 6555,
"text": "In this example, Kubernetes will have one service. This service is responsible for forecasting the demand. It will do 2 things: training a machine learning model and serving predictions."
},
{
"code": null,
"e": 6806,
"s": 6742,
"text": "A Kubernetes architecture for machine learning web-applications"
},
{
"code": null,
"e": 6836,
"s": 6806,
"text": "Kubernetes job (aka pod-init)"
},
{
"code": null,
"e": 7074,
"s": 6836,
"text": "A Kubernetes job is a pod that is executed before the actual deployment, before that the pod of the web server starts. Kubernetes jobs can be used to train the model. So, the consistency between the code and the estimator can be ensured."
},
{
"code": null,
"e": 7093,
"s": 7074,
"text": "Kubernetes cronJob"
},
{
"code": null,
"e": 7309,
"s": 7093,
"text": "A Kubernetes cronJob is a pod scheduled for being executed on a regular basis. It can be used to retrain the model on a regular basis (e.g. every day) with the latest data. So, the drift of the model can be avoided."
},
{
"code": null,
"e": 7334,
"s": 7309,
"text": "Kubernetes shared volume"
},
{
"code": null,
"e": 7446,
"s": 7334,
"text": "A Kubernetes shared volume shares files between pods. So, the trained estimator can be shared between the pods."
},
{
"code": null,
"e": 7576,
"s": 7446,
"text": "On the schema above, the serialized models are actually saved on AWS S3, but a pure Kubernetes approach is to use shared volumes."
},
{
"code": null,
"e": 7611,
"s": 7576,
"text": "Kubernetes vertical pod autoscaler"
},
{
"code": null,
"e": 7798,
"s": 7611,
"text": "A Kubernetes vertical pod autoscaler allocates the required memory and CPU to the pods dynamically over time. So, out-of-memory errors can be avoided and vertical scaling can be ensured."
},
{
"code": null,
"e": 7817,
"s": 7798,
"text": "Horionztal scaling"
},
{
"code": null,
"e": 8309,
"s": 7817,
"text": "This requirement is met by 2 components. The number of deployment pods is controlled by Kubernetes horizontal pod autoscaler. It starts and stops pods in order to satisfy the number of simultaneous HTTP-requests. Besides, Kubernetes jobs have a parameter “parallelism” to control how many pods run in parallel. Jobs are used for training the model, and beyond Kubernetes, training a machine learning model in a distributed way requires some adaptation. This is the focus of the next section."
},
{
"code": null,
"e": 8596,
"s": 8309,
"text": "Training the model during deployment makes deployment easier. Contributors don’t need to think: How this new feature will impact the legacy estimator? How will the new normalization of the data impact the legacy estimator? How will the update of the library impact the legacy estimator?"
},
{
"code": null,
"e": 8846,
"s": 8596,
"text": "Nonetheless, it has one downside: training the model during deployment (in the pod-initialization step) might last for a long time and make the deployment workflow (CI/CD) inefficient. A slow deployment pipeline is breaking the CI/CD best practices."
},
{
"code": null,
"e": 9052,
"s": 8846,
"text": "In this case, distributing the training over several pods helps. Some libraries are designed to distribute the training of one model: for example MLlib or Tensorflow. This is not the focus of this article."
},
{
"code": null,
"e": 9340,
"s": 9052,
"text": "In other cases, the training is fitting several models, not only one. In this case, it’s easy to distribute the training with a master/worker pattern. Assuming the entry points are bin/master.py and bin/worker.sh, this is a representation of the pods that are orchestrated by Kubernetes:"
},
{
"code": null,
"e": 9595,
"s": 9340,
"text": "The light green boxes show the kind of Kubernetes object that is manipulated: they group pod definitions by type. The middle green boxes are the definition of the pod i.e. the YAML like below. The dark green boxes show actual instances of the definition."
},
{
"code": null,
"e": 9663,
"s": 9595,
"text": "apiVersion: batch/v1beta1kind: CronJobspec: schedule: \"40 2 * * *\""
},
{
"code": null,
"e": 9743,
"s": 9663,
"text": "In a distributed world, Kubernetes orchestrates multiple instances of the pods."
},
{
"code": null,
"e": 10092,
"s": 9743,
"text": "For jobs and cronJobs, first, the pod named “master” is executed: it creates the task in the database (redis, outside of Kubernetes). Then, the workers are starting: they perform the task. The worker processes need to be terminated so that Kubernetes stop the pods and then starts the deployment pods. With celery, the following pseudo-code helped:"
}
] |
Morphological operations in MATLAB - GeeksforGeeks
|
17 Aug, 2020
Morphological Operations is a broad set of image processing operations that process digital images based on their shapes. In a morphological operation, each image pixel is corresponding to the value of other pixel in its neighborhood. By choosing the shape and size of the neighborhood pixel, you can construct a morphological operation that is sensitive to specific shapes in the input image. Morphological operations apply a structuring element called strel in Matlab, to an input image, creating an output image of the same size.
Types of Morphological operations:
Dilation: Dilation adds pixels on the object boundaries.
Erosion: Erosion removes pixels on object boundaries.
Open: The opening operation erodes an image and then dilates the eroded image, using the same structuring element for both operations.
Close: The closing operation dilates an image and then erodes the dilated image, using the same structuring element for both operations.
The number of pixels added or removed from the object in an image depends on the shape and size of the structuring element used to process the image. In the morphological dilation and erosion operations, the state of any given pixel in the output image is determined by applying a rule to the corresponding pixel and its neighbors in the input image. The rule used to process the pixels defines the morphological operation as a dilation or an erosion.
Below is the Matlab code for Morphological operations:
# Importing the imageI = imread("flowers.jpg"); subplot(2, 3, 1), imshow(I); title("Original image"); % Dilated Image se = strel("line", 7, 7); dilate = imdilate(I, se); subplot(2, 3, 2), imshow(dilate); title("Dilated image"); % Eroded image erode = imerode(I, se); subplot(2, 3, 3), imshow(erode); title("Eroded image"); % Opened image open = imopen(I, se); subplot(2, 3, 4), imshow(open); title("Opened image"); % Closed image close = imclose(I, se); subplot(2, 3, 5), imshow(close); title("Closed image");
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Mounting a Volume Inside Docker Container
Getting Started with System Design
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman
Q-Learning in Python
|
[
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 24371,
"s": 23837,
"text": "Morphological Operations is a broad set of image processing operations that process digital images based on their shapes. In a morphological operation, each image pixel is corresponding to the value of other pixel in its neighborhood. By choosing the shape and size of the neighborhood pixel, you can construct a morphological operation that is sensitive to specific shapes in the input image. Morphological operations apply a structuring element called strel in Matlab, to an input image, creating an output image of the same size. "
},
{
"code": null,
"e": 24408,
"s": 24371,
"text": "Types of Morphological operations: "
},
{
"code": null,
"e": 24465,
"s": 24408,
"text": "Dilation: Dilation adds pixels on the object boundaries."
},
{
"code": null,
"e": 24519,
"s": 24465,
"text": "Erosion: Erosion removes pixels on object boundaries."
},
{
"code": null,
"e": 24654,
"s": 24519,
"text": "Open: The opening operation erodes an image and then dilates the eroded image, using the same structuring element for both operations."
},
{
"code": null,
"e": 24791,
"s": 24654,
"text": "Close: The closing operation dilates an image and then erodes the dilated image, using the same structuring element for both operations."
},
{
"code": null,
"e": 25244,
"s": 24791,
"text": "The number of pixels added or removed from the object in an image depends on the shape and size of the structuring element used to process the image. In the morphological dilation and erosion operations, the state of any given pixel in the output image is determined by applying a rule to the corresponding pixel and its neighbors in the input image. The rule used to process the pixels defines the morphological operation as a dilation or an erosion. "
},
{
"code": null,
"e": 25300,
"s": 25244,
"text": "Below is the Matlab code for Morphological operations: "
},
{
"code": "# Importing the imageI = imread(\"flowers.jpg\"); subplot(2, 3, 1), imshow(I); title(\"Original image\"); % Dilated Image se = strel(\"line\", 7, 7); dilate = imdilate(I, se); subplot(2, 3, 2), imshow(dilate); title(\"Dilated image\"); % Eroded image erode = imerode(I, se); subplot(2, 3, 3), imshow(erode); title(\"Eroded image\"); % Opened image open = imopen(I, se); subplot(2, 3, 4), imshow(open); title(\"Opened image\"); % Closed image close = imclose(I, se); subplot(2, 3, 5), imshow(close); title(\"Closed image\"); ",
"e": 25824,
"s": 25300,
"text": null
},
{
"code": null,
"e": 25841,
"s": 25824,
"text": "Image-Processing"
},
{
"code": null,
"e": 25848,
"s": 25841,
"text": "MATLAB"
},
{
"code": null,
"e": 25874,
"s": 25848,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 25972,
"s": 25874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25981,
"s": 25972,
"text": "Comments"
},
{
"code": null,
"e": 25994,
"s": 25981,
"text": "Old Comments"
},
{
"code": null,
"e": 26038,
"s": 25994,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 26079,
"s": 26038,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 26097,
"s": 26079,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 26124,
"s": 26097,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 26187,
"s": 26124,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 26229,
"s": 26187,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 26264,
"s": 26229,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 26312,
"s": 26264,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 26348,
"s": 26312,
"text": "Basics of API Testing Using Postman"
}
] |
SQLite - Installation
|
SQLite is famous for its great feature zero-configuration, which means no complex setup or administration is needed. This chapter will take you through the process of setting up SQLite on Windows, Linux and Mac OS X.
Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section.
Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section.
Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files.
Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files.
Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
Step 4 − Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result.
Step 4 − Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result.
C:\>sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue the following command to check if you already have SQLite installed on your machine.
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
If you do not see the above result, then it means you do not have SQLite installed on your Linux machine. Following are the following steps to install SQLite −
Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
Step 2 − Run the following command −
Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above command will end with SQLite installation on your Linux machine. Which you can verify as explained above.
Though the latest version of Mac OS X comes pre-installed with SQLite but if you do not have installation available then just follow these following steps −
Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section.
Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section.
Step 2 − Run the following command −
Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above procedure will end with SQLite installation on your Mac OS X machine. Which you can verify by issuing the following command −
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Finally, you have SQLite command prompt where you can issue SQLite commands for your exercises.
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2855,
"s": 2638,
"text": "SQLite is famous for its great feature zero-configuration, which means no complex setup or administration is needed. This chapter will take you through the process of setting up SQLite on Windows, Linux and Mac OS X."
},
{
"code": null,
"e": 2948,
"s": 2855,
"text": "Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section."
},
{
"code": null,
"e": 3041,
"s": 2948,
"text": "Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section."
},
{
"code": null,
"e": 3125,
"s": 3041,
"text": "Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files."
},
{
"code": null,
"e": 3209,
"s": 3125,
"text": "Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files."
},
{
"code": null,
"e": 3363,
"s": 3209,
"text": "Step 3 − Create a folder C:\\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.\n"
},
{
"code": null,
"e": 3516,
"s": 3363,
"text": "Step 3 − Create a folder C:\\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files."
},
{
"code": null,
"e": 3681,
"s": 3516,
"text": "Step 4 − Add C:\\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result."
},
{
"code": null,
"e": 3846,
"s": 3681,
"text": "Step 4 − Add C:\\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result."
},
{
"code": null,
"e": 3985,
"s": 3846,
"text": "C:\\>sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 4162,
"s": 3985,
"text": "Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue the following command to check if you already have SQLite installed on your machine."
},
{
"code": null,
"e": 4298,
"s": 4162,
"text": "$sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 4458,
"s": 4298,
"text": "If you do not see the above result, then it means you do not have SQLite installed on your Linux machine. Following are the following steps to install SQLite −"
},
{
"code": null,
"e": 4558,
"s": 4458,
"text": "Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 4658,
"s": 4558,
"text": "Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 4695,
"s": 4658,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 4732,
"s": 4695,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 4855,
"s": 4732,
"text": "$tar xvfz sqlite-autoconf-3071502.tar.gz\n$cd sqlite-autoconf-3071502\n$./configure --prefix=/usr/local\n$make\n$make install\n"
},
{
"code": null,
"e": 4971,
"s": 4855,
"text": "The above command will end with SQLite installation on your Linux machine. Which you can verify as explained above."
},
{
"code": null,
"e": 5128,
"s": 4971,
"text": "Though the latest version of Mac OS X comes pre-installed with SQLite but if you do not have installation available then just follow these following steps −"
},
{
"code": null,
"e": 5229,
"s": 5128,
"text": "Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 5330,
"s": 5229,
"text": "Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 5367,
"s": 5330,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 5404,
"s": 5367,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 5527,
"s": 5404,
"text": "$tar xvfz sqlite-autoconf-3071502.tar.gz\n$cd sqlite-autoconf-3071502\n$./configure --prefix=/usr/local\n$make\n$make install\n"
},
{
"code": null,
"e": 5663,
"s": 5527,
"text": "The above procedure will end with SQLite installation on your Mac OS X machine. Which you can verify by issuing the following command −"
},
{
"code": null,
"e": 5799,
"s": 5663,
"text": "$sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 5895,
"s": 5799,
"text": "Finally, you have SQLite command prompt where you can issue SQLite commands for your exercises."
},
{
"code": null,
"e": 5930,
"s": 5895,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5951,
"s": 5930,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 5984,
"s": 5951,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6001,
"s": 5984,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6032,
"s": 6001,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6045,
"s": 6032,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6052,
"s": 6045,
"text": " Print"
},
{
"code": null,
"e": 6063,
"s": 6052,
"text": " Add Notes"
}
] |
Bootstrap 4 | Modal - GeeksforGeeks
|
21 Jun, 2019
In simple words, the Modal component is a dialog box/popup window that is displayed on top of the current page, once the trigger button is clicked. However, clicking on the modal’s backdrop automatically closes the modal. Also, it must be kept in mind that Bootstrap doesn’t support nested modals as they create bad UI experience for the user. Therefore, only one modal window is supported at a time.
To use Bootstrap 4.0, either download Bootstrap in your project root folder or copy and paste the following link in the head section of the HTML code.
Required paths:
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”>
However, there are many BootStrap components that require several JavaScript plugins in order to function well. Those plugins are jQuery, Popper.js, and a Bootstrap’s personal JavaScript plugin. The following chunk of code must be placed right before the closing body tag inside the script tag.
Required plugins:
<script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js” integrity=”sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN” crossorigin=”anonymous”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script>
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>bootstrap | Modal</title> <style> h1,h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Launch Modal</button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title" id="exampleModalLabel" style="color:green;"> GeeksforGeeks</h6> <!-- The title of the modal --> <button type="button" class="close" data-dismiss="modal"aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- The content inside the modal box --> <p>Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formating style, coding style, and try to make your close to them. </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <!-- The close button in the bottom of the modal --> <button type="button" class="btn btn-primary">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> </center></body> </html>
Output:
Before launching the Modal:
After launching the Modal:
Modals are built with HTML, CSS, and JavaScript. They are positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead.
Clicking the modal “backdrop” will close the modal automatically.
This Modal supports only one modal window at a time.
Modals use position: fixed, which can sometimes be a bit particular about its rendering. If possible, place your modal HTML in a top-level position to avoid potential interference from other elements.
Due to position: fixed, there are few caveats with using modals on mobile devices.
Using the grid:Utilize the Bootstrap grid system within a modal by nesting <b-container fluid> within the modal-body else you can use the normal grid system <b-row> (or <b-form-row>) and <b-col> as you would anywhere else.
Tooltips and popovers:A Tooltip is used to provide interactive textual hints to the user about the element when the mouse pointer moves over.The popover is an attribute of bootstrap that can be used to make any website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element.Example:<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>bootstrap | Modal</title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch Modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title" id="exampleModalLabel" style="color:green;"> GeeksforGeeks</h3> <!-- The title of the modal --> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- The content inside the modal box --> <div class="container"> <p>This <button style="color:green;" data-toggle="popover" title="popover-title" data-content="popover-content"> GeeksforGeeks </button>triggers a popover on click.</p> </div> <script> $(document).ready(function() { $('[data-toggle="popover"]').popover(); }); </script> <div class="container"> <p>This <a style="color:green;" data-toggle="tooltip" title="Tooltip"> GeeksforGeeks </a> will show a tooltip on hover. </p> </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <!-- The close button in the bottom of the modal --> <button type="button" class="btn btn-primary">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> </center></body> </html>Output:
A Tooltip is used to provide interactive textual hints to the user about the element when the mouse pointer moves over.
The popover is an attribute of bootstrap that can be used to make any website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element.
Example:
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>bootstrap | Modal</title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch Modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title" id="exampleModalLabel" style="color:green;"> GeeksforGeeks</h3> <!-- The title of the modal --> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- The content inside the modal box --> <div class="container"> <p>This <button style="color:green;" data-toggle="popover" title="popover-title" data-content="popover-content"> GeeksforGeeks </button>triggers a popover on click.</p> </div> <script> $(document).ready(function() { $('[data-toggle="popover"]').popover(); }); </script> <div class="container"> <p>This <a style="color:green;" data-toggle="tooltip" title="Tooltip"> GeeksforGeeks </a> will show a tooltip on hover. </p> </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <!-- The close button in the bottom of the modal --> <button type="button" class="btn btn-primary">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> </center></body> </html>
Output:
Small Modal:<div class="modal-dialog modal-sm">
<div class="modal-dialog modal-sm">
Large Modal:<div class="modal-dialog modal-lg">
<div class="modal-dialog modal-lg">
Extra Large Modal:<div class="modal-dialog modal-xl">
<div class="modal-dialog modal-xl">
<div class="<div class="modal-dialog modal-dialog-centered">
<div class="modal-dialog modal-dialog-scrollable">
Bootstrap-4
Picked
Web technologies
Bootstrap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to align button to right side of text box in Bootstrap?
How to change the background color of the active nav-item?
Create a Homepage for Restaurant using HTML , CSS and Bootstrap
How to Use Bootstrap with React?
|
[
{
"code": null,
"e": 28480,
"s": 28452,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 28881,
"s": 28480,
"text": "In simple words, the Modal component is a dialog box/popup window that is displayed on top of the current page, once the trigger button is clicked. However, clicking on the modal’s backdrop automatically closes the modal. Also, it must be kept in mind that Bootstrap doesn’t support nested modals as they create bad UI experience for the user. Therefore, only one modal window is supported at a time."
},
{
"code": null,
"e": 29032,
"s": 28881,
"text": "To use Bootstrap 4.0, either download Bootstrap in your project root folder or copy and paste the following link in the head section of the HTML code."
},
{
"code": null,
"e": 29048,
"s": 29032,
"text": "Required paths:"
},
{
"code": null,
"e": 29257,
"s": 29048,
"text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”>"
},
{
"code": null,
"e": 29552,
"s": 29257,
"text": "However, there are many BootStrap components that require several JavaScript plugins in order to function well. Those plugins are jQuery, Popper.js, and a Bootstrap’s personal JavaScript plugin. The following chunk of code must be placed right before the closing body tag inside the script tag."
},
{
"code": null,
"e": 29570,
"s": 29552,
"text": "Required plugins:"
},
{
"code": null,
"e": 29751,
"s": 29570,
"text": "<script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js” integrity=”sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN” crossorigin=”anonymous”></script>"
},
{
"code": null,
"e": 29957,
"s": 29751,
"text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script>"
},
{
"code": null,
"e": 30157,
"s": 29957,
"text": "<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <title>bootstrap | Modal</title> <style> h1,h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\">Launch Modal</button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\" role=\"document\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h6 class=\"modal-title\" id=\"exampleModalLabel\" style=\"color:green;\"> GeeksforGeeks</h6> <!-- The title of the modal --> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> <!-- The content inside the modal box --> <p>Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formating style, coding style, and try to make your close to them. </p> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Close</button> <!-- The close button in the bottom of the modal --> <button type=\"button\" class=\"btn btn-primary\">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> </center></body> </html>",
"e": 33093,
"s": 30157,
"text": null
},
{
"code": null,
"e": 33101,
"s": 33093,
"text": "Output:"
},
{
"code": null,
"e": 33129,
"s": 33101,
"text": "Before launching the Modal:"
},
{
"code": null,
"e": 33156,
"s": 33129,
"text": "After launching the Modal:"
},
{
"code": null,
"e": 33335,
"s": 33156,
"text": "Modals are built with HTML, CSS, and JavaScript. They are positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead."
},
{
"code": null,
"e": 33401,
"s": 33335,
"text": "Clicking the modal “backdrop” will close the modal automatically."
},
{
"code": null,
"e": 33454,
"s": 33401,
"text": "This Modal supports only one modal window at a time."
},
{
"code": null,
"e": 33655,
"s": 33454,
"text": "Modals use position: fixed, which can sometimes be a bit particular about its rendering. If possible, place your modal HTML in a top-level position to avoid potential interference from other elements."
},
{
"code": null,
"e": 33738,
"s": 33655,
"text": "Due to position: fixed, there are few caveats with using modals on mobile devices."
},
{
"code": null,
"e": 33961,
"s": 33738,
"text": "Using the grid:Utilize the Bootstrap grid system within a modal by nesting <b-container fluid> within the modal-body else you can use the normal grid system <b-row> (or <b-form-row>) and <b-col> as you would anywhere else."
},
{
"code": null,
"e": 38661,
"s": 33961,
"text": "Tooltips and popovers:A Tooltip is used to provide interactive textual hints to the user about the element when the mouse pointer moves over.The popover is an attribute of bootstrap that can be used to make any website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element.Example:<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <title>bootstrap | Modal</title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch Modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\" role=\"document\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h3 class=\"modal-title\" id=\"exampleModalLabel\" style=\"color:green;\"> GeeksforGeeks</h3> <!-- The title of the modal --> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> <!-- The content inside the modal box --> <div class=\"container\"> <p>This <button style=\"color:green;\" data-toggle=\"popover\" title=\"popover-title\" data-content=\"popover-content\"> GeeksforGeeks </button>triggers a popover on click.</p> </div> <script> $(document).ready(function() { $('[data-toggle=\"popover\"]').popover(); }); </script> <div class=\"container\"> <p>This <a style=\"color:green;\" data-toggle=\"tooltip\" title=\"Tooltip\"> GeeksforGeeks </a> will show a tooltip on hover. </p> </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <!-- The close button in the bottom of the modal --> <button type=\"button\" class=\"btn btn-primary\">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> </center></body> </html>Output:"
},
{
"code": null,
"e": 38781,
"s": 38661,
"text": "A Tooltip is used to provide interactive textual hints to the user about the element when the mouse pointer moves over."
},
{
"code": null,
"e": 39021,
"s": 38781,
"text": "The popover is an attribute of bootstrap that can be used to make any website look more dynamic. Popovers are generally used to display additional information about any element and are displayed on click of mouse pointer over that element."
},
{
"code": null,
"e": 39030,
"s": 39021,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <title>bootstrap | Modal</title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch Modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\" role=\"document\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h3 class=\"modal-title\" id=\"exampleModalLabel\" style=\"color:green;\"> GeeksforGeeks</h3> <!-- The title of the modal --> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> <!-- The content inside the modal box --> <div class=\"container\"> <p>This <button style=\"color:green;\" data-toggle=\"popover\" title=\"popover-title\" data-content=\"popover-content\"> GeeksforGeeks </button>triggers a popover on click.</p> </div> <script> $(document).ready(function() { $('[data-toggle=\"popover\"]').popover(); }); </script> <div class=\"container\"> <p>This <a style=\"color:green;\" data-toggle=\"tooltip\" title=\"Tooltip\"> GeeksforGeeks </a> will show a tooltip on hover. </p> </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <!-- The close button in the bottom of the modal --> <button type=\"button\" class=\"btn btn-primary\">okay</button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> </center></body> </html>",
"e": 43335,
"s": 39030,
"text": null
},
{
"code": null,
"e": 43343,
"s": 43335,
"text": "Output:"
},
{
"code": null,
"e": 43391,
"s": 43343,
"text": "Small Modal:<div class=\"modal-dialog modal-sm\">"
},
{
"code": "<div class=\"modal-dialog modal-sm\">",
"e": 43427,
"s": 43391,
"text": null
},
{
"code": null,
"e": 43475,
"s": 43427,
"text": "Large Modal:<div class=\"modal-dialog modal-lg\">"
},
{
"code": "<div class=\"modal-dialog modal-lg\">",
"e": 43511,
"s": 43475,
"text": null
},
{
"code": null,
"e": 43565,
"s": 43511,
"text": "Extra Large Modal:<div class=\"modal-dialog modal-xl\">"
},
{
"code": "<div class=\"modal-dialog modal-xl\">",
"e": 43601,
"s": 43565,
"text": null
},
{
"code": "<div class=\"<div class=\"modal-dialog modal-dialog-centered\">",
"e": 43662,
"s": 43601,
"text": null
},
{
"code": "<div class=\"modal-dialog modal-dialog-scrollable\">",
"e": 43713,
"s": 43662,
"text": null
},
{
"code": null,
"e": 43725,
"s": 43713,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 43732,
"s": 43725,
"text": "Picked"
},
{
"code": null,
"e": 43749,
"s": 43732,
"text": "Web technologies"
},
{
"code": null,
"e": 43759,
"s": 43749,
"text": "Bootstrap"
},
{
"code": null,
"e": 43857,
"s": 43759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43866,
"s": 43857,
"text": "Comments"
},
{
"code": null,
"e": 43879,
"s": 43866,
"text": "Old Comments"
},
{
"code": null,
"e": 43929,
"s": 43879,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 43958,
"s": 43929,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 43999,
"s": 43958,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 44055,
"s": 43999,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 44118,
"s": 44055,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 44159,
"s": 44118,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 44219,
"s": 44159,
"text": "How to align button to right side of text box in Bootstrap?"
},
{
"code": null,
"e": 44278,
"s": 44219,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 44342,
"s": 44278,
"text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap"
}
] |
Data Demystified — DIKW model. A data scientist is a person who is... | by Anthony Figueroa | Towards Data Science
|
Data is one of the biggest new trends in both tech and business in general. Data “experts” are quickly becoming some of the best-paid individuals in the industry, and every single company wants to surf the wave of data capabilities.
It is becoming a fundamental way of understanding the world around us. We can think of data sciences as epistemology or a way of knowing. We can think of it, about a way to approach problems and solving them.
But as with any new trend, we have to ask ourselves: what do all these buzzwords actually mean?
What is a data scientist? In short, a person who is better at statistics than any software engineer and better at software engineering than any statistician.
The goal of this article is to demystify data analysis. We’ll explain what these buzzwords mean, what big data can and cannot do, and which technologies you should explore if you’re jumping on the data train
This article is the first of a four-part series on data analysis. We’ll start with some foundational knowledge, then build on that foundation, step-by-step, to explain the more sophisticated and robust systems in both computational and thinking processes and help you understand why everyone is so crazy about data.
Before getting into the meet of data analysis, let’s start with a simple, but incredibly important, concept: the DIKW Pyramid. While many people are familiar with the pyramid, few understand how to interpret it, how to use it, and where they themselves stand.
To elaborate on the concept, listen to Jennifer Rowley (2007): “Typically information is defined in terms of data, knowledge in terms of information, and wisdom in terms of knowledge.”
Now let’s explain each level of the pyramid.
Data is just a set of signals or symbols. Nothing more — just noise. It may be server logs, user behavior events, or any other data set. It’s unorganized and unprocessed. It’s inert. And if we don’t know what it means, it’s useless.
You get Information when you start to make data useful. When we apply systems to organize and classify data, we can transform this unstructured noise into Information. The “What”, “When” and “Who” question should be answered at this stage. In short, Information is data with meaning. This “meaning” can be useful, but it isn’t always useful.
Knowledge is the next step in the journey, and probably the most significant leap. It implicitly requires learning. It means that we can take data, categorize and process it generating Information, then organize all this Information in a way that it can be useful. Whereas Information can help us to understand relationships, Knowledge allows us to detect patterns. It’s the foundation that will let us build predictive models and generate real insights. A definition that I like is that Knowledge is a mental structure, made from accumulated learning and systematic analysis of Information.
Wisdom is the final frontier. It allows us to predict the future correctly, not only by detecting and understanding patterns but also deeply comprehending the “Why” behind those patterns. Wisdom is all about the future: it relies on Knowledge and pattern models, but it can help to shape your “gut feeling” and intuition, giving you an exponential competitive advantage. Knowledge ages quickly because of how fast reality changes, but wisdom remains more rigid. For now, this is a pure human skill, but AI is catching up fast. When AI wisdom becomes better than human wisdom, the outcomes will be unpredictable.
The following image exemplifies perfectly this mental model:
This example also introduces the ‘Insight’ concept, sometimes known as ‘Intelligence’. It’s a sporadic manifestation of Wisdom. Insight is what connects Knowledge and Wisdom.
Data: It’s raining
Information: The temperature dropped 5 degrees, the humidity went up by 5% in one hour and then it started raining at 3 pm.
Knowledge: A quick increase in the humidity, accompanied by a temperature drop caused by lower pressure areas, will likely make the atmosphere unable to hold the moisture and rain.
Wisdom: Based on the observations and maths model, we can predict why and when it will rain in the future, and we can do it so fast and systematically that it won’t require a lot of analysis. We already have an understanding of all the interactions that happen between evaporation, air currents, temperature gradients, changes, and raining.
Representativeness heuristic is used by our brain to infer patterns. Our brain uses a vast percentage of its capacity to create patterns and is obsessed with trying to understand and predict patterns in the real world. That means that when working with data, we need to be extremely mindful in avoiding jumping to conclusions too soon. Knowing that we have this tendency to chase and see patterns everywhere can help us to slow down when it comes to inferring patterns. This is a topic warrants its own article, but it’s good to keep in mind from the very beginning.
Availability Bias is somewhat related to the previous concept. It’s a mental shortcut that relies on immediate, urgent Information, and tries to generalize the findings using only the most obvious information. Under this bias, people tend to heavily weigh their judgments toward more recent Information, making new opinions biased toward the latest or closest news. You can read more in the following article.
medium.com
It’s not data sciences. Not even the engineering field. The origin of this mental framework is poetry. The poet T.S.Eliot was the first to mention the “DIKW hierarchy,” although he didn’t call it by that name. In 1934 Eliot wrote in “The Rock”:
Where is the Life we have lost in living? Where is the wisdom we have lost in Knowledge? Where is the Knowledge we have lost in Information?
Though this is the first mention of the hierarchy in the arts, it is not the only one. Before management and information science caught on, Frank Zappa alluded to the hierarchy in 1979:
Information is not Knowledge, Knowledge is not wisdom, Wisdom is not truth, Truth is not beauty, Beauty is not love, Love is not music, and Music is THE BEST
Russell .L. Ackoff, “From Data to Wisdom,” Journal of Applied Systems Analysis 16 (1989): 3–9.Milan Zeleny, “Management Support Systems: Towards Integrated Knowledge Management,” Human Systems Management 7, no 1 (1987): 59–70.M. Cooley, Architecture or Bee? (London: The Hogarth Press, 1987).Harland Cleveland, “Information as Resource,” The Futurist, December 1982, 34–39.T.S. Eliot, The Rock (Faber & Faber 1934).Frank Zappa, “Packard Goose” in album Joe’s Garage: Act II & III (Tower Records, 1979).Nikhil Sharma, “The Origin of Data Information Knowledge Wisdom (DIKW) Hierarchy”, (Google Inc, February 2008).
Russell .L. Ackoff, “From Data to Wisdom,” Journal of Applied Systems Analysis 16 (1989): 3–9.
Milan Zeleny, “Management Support Systems: Towards Integrated Knowledge Management,” Human Systems Management 7, no 1 (1987): 59–70.
M. Cooley, Architecture or Bee? (London: The Hogarth Press, 1987).
Harland Cleveland, “Information as Resource,” The Futurist, December 1982, 34–39.
T.S. Eliot, The Rock (Faber & Faber 1934).
Frank Zappa, “Packard Goose” in album Joe’s Garage: Act II & III (Tower Records, 1979).
Nikhil Sharma, “The Origin of Data Information Knowledge Wisdom (DIKW) Hierarchy”, (Google Inc, February 2008).
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "Data is one of the biggest new trends in both tech and business in general. Data “experts” are quickly becoming some of the best-paid individuals in the industry, and every single company wants to surf the wave of data capabilities."
},
{
"code": null,
"e": 614,
"s": 405,
"text": "It is becoming a fundamental way of understanding the world around us. We can think of data sciences as epistemology or a way of knowing. We can think of it, about a way to approach problems and solving them."
},
{
"code": null,
"e": 710,
"s": 614,
"text": "But as with any new trend, we have to ask ourselves: what do all these buzzwords actually mean?"
},
{
"code": null,
"e": 868,
"s": 710,
"text": "What is a data scientist? In short, a person who is better at statistics than any software engineer and better at software engineering than any statistician."
},
{
"code": null,
"e": 1076,
"s": 868,
"text": "The goal of this article is to demystify data analysis. We’ll explain what these buzzwords mean, what big data can and cannot do, and which technologies you should explore if you’re jumping on the data train"
},
{
"code": null,
"e": 1392,
"s": 1076,
"text": "This article is the first of a four-part series on data analysis. We’ll start with some foundational knowledge, then build on that foundation, step-by-step, to explain the more sophisticated and robust systems in both computational and thinking processes and help you understand why everyone is so crazy about data."
},
{
"code": null,
"e": 1652,
"s": 1392,
"text": "Before getting into the meet of data analysis, let’s start with a simple, but incredibly important, concept: the DIKW Pyramid. While many people are familiar with the pyramid, few understand how to interpret it, how to use it, and where they themselves stand."
},
{
"code": null,
"e": 1837,
"s": 1652,
"text": "To elaborate on the concept, listen to Jennifer Rowley (2007): “Typically information is defined in terms of data, knowledge in terms of information, and wisdom in terms of knowledge.”"
},
{
"code": null,
"e": 1882,
"s": 1837,
"text": "Now let’s explain each level of the pyramid."
},
{
"code": null,
"e": 2115,
"s": 1882,
"text": "Data is just a set of signals or symbols. Nothing more — just noise. It may be server logs, user behavior events, or any other data set. It’s unorganized and unprocessed. It’s inert. And if we don’t know what it means, it’s useless."
},
{
"code": null,
"e": 2457,
"s": 2115,
"text": "You get Information when you start to make data useful. When we apply systems to organize and classify data, we can transform this unstructured noise into Information. The “What”, “When” and “Who” question should be answered at this stage. In short, Information is data with meaning. This “meaning” can be useful, but it isn’t always useful."
},
{
"code": null,
"e": 3049,
"s": 2457,
"text": "Knowledge is the next step in the journey, and probably the most significant leap. It implicitly requires learning. It means that we can take data, categorize and process it generating Information, then organize all this Information in a way that it can be useful. Whereas Information can help us to understand relationships, Knowledge allows us to detect patterns. It’s the foundation that will let us build predictive models and generate real insights. A definition that I like is that Knowledge is a mental structure, made from accumulated learning and systematic analysis of Information."
},
{
"code": null,
"e": 3661,
"s": 3049,
"text": "Wisdom is the final frontier. It allows us to predict the future correctly, not only by detecting and understanding patterns but also deeply comprehending the “Why” behind those patterns. Wisdom is all about the future: it relies on Knowledge and pattern models, but it can help to shape your “gut feeling” and intuition, giving you an exponential competitive advantage. Knowledge ages quickly because of how fast reality changes, but wisdom remains more rigid. For now, this is a pure human skill, but AI is catching up fast. When AI wisdom becomes better than human wisdom, the outcomes will be unpredictable."
},
{
"code": null,
"e": 3722,
"s": 3661,
"text": "The following image exemplifies perfectly this mental model:"
},
{
"code": null,
"e": 3897,
"s": 3722,
"text": "This example also introduces the ‘Insight’ concept, sometimes known as ‘Intelligence’. It’s a sporadic manifestation of Wisdom. Insight is what connects Knowledge and Wisdom."
},
{
"code": null,
"e": 3916,
"s": 3897,
"text": "Data: It’s raining"
},
{
"code": null,
"e": 4040,
"s": 3916,
"text": "Information: The temperature dropped 5 degrees, the humidity went up by 5% in one hour and then it started raining at 3 pm."
},
{
"code": null,
"e": 4221,
"s": 4040,
"text": "Knowledge: A quick increase in the humidity, accompanied by a temperature drop caused by lower pressure areas, will likely make the atmosphere unable to hold the moisture and rain."
},
{
"code": null,
"e": 4562,
"s": 4221,
"text": "Wisdom: Based on the observations and maths model, we can predict why and when it will rain in the future, and we can do it so fast and systematically that it won’t require a lot of analysis. We already have an understanding of all the interactions that happen between evaporation, air currents, temperature gradients, changes, and raining."
},
{
"code": null,
"e": 5129,
"s": 4562,
"text": "Representativeness heuristic is used by our brain to infer patterns. Our brain uses a vast percentage of its capacity to create patterns and is obsessed with trying to understand and predict patterns in the real world. That means that when working with data, we need to be extremely mindful in avoiding jumping to conclusions too soon. Knowing that we have this tendency to chase and see patterns everywhere can help us to slow down when it comes to inferring patterns. This is a topic warrants its own article, but it’s good to keep in mind from the very beginning."
},
{
"code": null,
"e": 5539,
"s": 5129,
"text": "Availability Bias is somewhat related to the previous concept. It’s a mental shortcut that relies on immediate, urgent Information, and tries to generalize the findings using only the most obvious information. Under this bias, people tend to heavily weigh their judgments toward more recent Information, making new opinions biased toward the latest or closest news. You can read more in the following article."
},
{
"code": null,
"e": 5550,
"s": 5539,
"text": "medium.com"
},
{
"code": null,
"e": 5795,
"s": 5550,
"text": "It’s not data sciences. Not even the engineering field. The origin of this mental framework is poetry. The poet T.S.Eliot was the first to mention the “DIKW hierarchy,” although he didn’t call it by that name. In 1934 Eliot wrote in “The Rock”:"
},
{
"code": null,
"e": 5936,
"s": 5795,
"text": "Where is the Life we have lost in living? Where is the wisdom we have lost in Knowledge? Where is the Knowledge we have lost in Information?"
},
{
"code": null,
"e": 6122,
"s": 5936,
"text": "Though this is the first mention of the hierarchy in the arts, it is not the only one. Before management and information science caught on, Frank Zappa alluded to the hierarchy in 1979:"
},
{
"code": null,
"e": 6280,
"s": 6122,
"text": "Information is not Knowledge, Knowledge is not wisdom, Wisdom is not truth, Truth is not beauty, Beauty is not love, Love is not music, and Music is THE BEST"
},
{
"code": null,
"e": 6894,
"s": 6280,
"text": "Russell .L. Ackoff, “From Data to Wisdom,” Journal of Applied Systems Analysis 16 (1989): 3–9.Milan Zeleny, “Management Support Systems: Towards Integrated Knowledge Management,” Human Systems Management 7, no 1 (1987): 59–70.M. Cooley, Architecture or Bee? (London: The Hogarth Press, 1987).Harland Cleveland, “Information as Resource,” The Futurist, December 1982, 34–39.T.S. Eliot, The Rock (Faber & Faber 1934).Frank Zappa, “Packard Goose” in album Joe’s Garage: Act II & III (Tower Records, 1979).Nikhil Sharma, “The Origin of Data Information Knowledge Wisdom (DIKW) Hierarchy”, (Google Inc, February 2008)."
},
{
"code": null,
"e": 6989,
"s": 6894,
"text": "Russell .L. Ackoff, “From Data to Wisdom,” Journal of Applied Systems Analysis 16 (1989): 3–9."
},
{
"code": null,
"e": 7122,
"s": 6989,
"text": "Milan Zeleny, “Management Support Systems: Towards Integrated Knowledge Management,” Human Systems Management 7, no 1 (1987): 59–70."
},
{
"code": null,
"e": 7189,
"s": 7122,
"text": "M. Cooley, Architecture or Bee? (London: The Hogarth Press, 1987)."
},
{
"code": null,
"e": 7271,
"s": 7189,
"text": "Harland Cleveland, “Information as Resource,” The Futurist, December 1982, 34–39."
},
{
"code": null,
"e": 7314,
"s": 7271,
"text": "T.S. Eliot, The Rock (Faber & Faber 1934)."
},
{
"code": null,
"e": 7402,
"s": 7314,
"text": "Frank Zappa, “Packard Goose” in album Joe’s Garage: Act II & III (Tower Records, 1979)."
}
] |
MFC - Rich Edit
|
A Rich Edit Control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. It is represented by CRichEditCtrl class.
CanPaste
Determines if the contents of the Clipboard can be pasted into this rich edit control.
CanRedo
Determines whether there are any actions in the controls redo queue.
CanUndo
Determines if an editing operation can be undone.
CharFromPos
Retrieves information about the character closest to a specified point in the client area of an edit control.
Clear
Clears the current selection.
Copy
Copies the current selection to the Clipboard.
Create
Creates the Windows rich edit control and associates it with this CRichEditCtrl object.
CreateEx
Creates the Windows rich edit control with the specified extended Windows styles and associates it with this CRichEditCtrl object.
Cut
Cuts the current selection to the Clipboard.
DisplayBand
Displays a portion of the contents of this CRichEditCtrl object.
EmptyUndoBuffer
Resets (clears) the undo flag of this CRichEditCtrl object.
FindText
Locates text within this CRichEditCtrl object.
FindWordBreak
Finds the next word break before or after the specified character position, or retrieves information about the character at that position.
FormatRange
Formats a range of text for the target output device.
GetCharPos
Determines the location of a given character within this CRichEditCtrl object.
GetDefaultCharFormat
Retrieves the current default character formatting attributes in this CRichEditCtrl object.
GetEventMask
Retrieves the event mask for this CRichEditCtrl object.
GetFirstVisibleLine
Determines the topmost visible line in this CRichEditCtrl object.
GetIRichEditOle
Retrieves a pointer to the IRichEditOle interface for this rich edit control.
GetLimitText
Gets the limit on the amount of text a user can enter into this CRichEditCtrl object.
GetLine
Retrieves a line of text from this CRichEditCtrl object.
GetLineCount
Retrieves the number of lines in this CRichEditCtrl object.
GetModify
Determines if the contents of this CRichEditCtrl object have changed since the last save.
GetOptions
Retrieves the rich edit control options.
GetParaFormat
Retrieves the paragraph formatting attributes in the current selection in this CRichEditCtrl object.
GetPunctuation
Retrieves the current punctuation characters for the rich edit control. This message is available only in Asianlanguage versions of the operating system.
GetRect
Retrieves the formatting rectangle for this CRichEditCtrl object.
GetRedoName
Retrieves the type of the next action, if any, in the control's redo queue.
GetSel
Gets the starting and ending positions of the current selection in this CRichEditCtrl object.
GetSelectionCharFormat
Retrieves the character formatting attributes in the current selection in this CRichEditCtrl object.
GetSelectionType
Retrieves the type of contents in the current selection in this CRichEditCtrl object.
GetSelText
Gets the text of the current selection in this CRichEditCtrl object.
GetTextLength
Retrieves the length of the text, in characters, in this CRichEditCtrl object. Does not include the terminating null character.
GetTextLengthEx
Retrieves the number of characters or bytes in the rich edit view. Accepts a list of flags to indicate the method of determining length of the text in a rich edit control.
GetTextMode
Retrieves the current text mode and undo level of a rich edit control.
GetTextRange
Retrieves the specified range of text.
GetUndoName
Retrieves the type of the next undo action, if any.
GetWordWrapMode
Retrieves the current word wrapping and word breaking options for the rich edit control. This message is available only in Asian-language versions of the operating system.
HideSelection
Shows or hides the current selection.
LimitText
Limits the amount of text a user can enter into the CRichEditCtrl object.
LineFromChar
Determines which line contains the given character.
LineIndex
Retrieves the character index of a given line in this CRichEditCtrl object.
LineLength
Retrieves the length of a given line in this CRichEditCtrl object.
LineScroll
Scrolls the text in this CRichEditCtrl object.
Paste
Inserts the contents of the Clipboard into this rich edit control.
PasteSpecial
Inserts the contents of the Clipboard into this rich edit control in the specified data format.
PosFromChar
Retrieves the client area coordinates of a specified character in an edit control.
Redo
Redoes the next action in the control's redo queue.
ReplaceSel
Replaces the current selection in this CRichEditCtrl object with specified text.
RequestResize
Forces this CRichEditCtrl object to send request resize notifications.
SetAutoURLDetect
Indicates if the auto URL detection is active in a rich edit control.
SetBackgroundColor
Sets the background color in this CRichEditCtrl object.
SetDefaultCharFormat
Sets the current default character formatting attributes in this CRichEditCtrl object.
SetEventMask
Sets the event mask for this CRichEditCtrl object.
SetModify
Sets or clears the modification flag for this CRichEditCtrl object.
SetOLECallback
Sets the IRichEditOleCallback COM object for this rich edit control.
SetOptions
Sets the options for this CRichEditCtrl object.
SetParaFormat
Sets the paragraph formatting attributes in the current selection in this CRichEditCtrl object.
SetPunctuation
Sets the punctuation characters for a rich edit control. This message is available only in Asianlanguage versions of the operating system.
SetReadOnly
Sets the read-only option for this CRichEditCtrl object.
SetRect
Sets the formatting rectangle for this CRichEditCtrl object.
SetSel
Sets the selection in this CRichEditCtrl object.
SetSelectionCharFormat
Sets the character formatting attributes in the current selection in this CRichEditCtrl object.
SetTargetDevice
Sets the target output device for this CRichEditCtrl object.
SetTextMode
Sets the text mode or undo level of a rich edit control. The message fails if the control contains text.
SetUndoLimit
Sets the maximum number of actions that can stored in the undo queue.
SetWordCharFormat
Sets the character formatting attributes in the current word in this CRichEditCtrl object.
SetWordWrapMode
Sets the word-wrapping and word-breaking options for the rich edit control. This message is available only in Asianlanguage versions of the operating system.
StopGroupTyping
Stops the control from collecting additional typing actions into the current undo action. The control stores the next typing action, if any, into a new action in the undo queue.
StreamIn
Inserts text from an input stream into this CRichEditCtrl object
StreamOut
Stores text from this CRichEditCtrl object into an output stream.
Undo
Reverses the last editing operation.
Let us into a simple example by creating a new MFC dialog based application.
Step 1 − Delete the TODO line and drag one Rich Edit Control and three buttons from the Toolbox.
Step 2 − Change the Caption of these three buttons from Bold, Italic and Under Line to IDC_BUTTON_BOLD, IDC_BUTTON_ITALIC and IDC_BUTTON_UNDERLINE respectively.
Step 3 − Set the following properties to True: Multiline, Want Return, Vertical Scroll.
Step 4 − Add the control variable m_richEdit for Rich Edit Control.
Step 5 − Go to the CMFCRichEditApp and call the ::AfxInitRichEdit2() in CMFCRichEditApp::InitInstance() function as shown in the following code.
BOOL CMFCRichEditApp::InitInstance() {
//TODO: call AfxInitRichEdit2() to initialize richedit2 library.
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
::AfxInitRichEdit2();
CWinApp::InitInstance();
AfxEnableControlContainer();
// Create the shell manager, in case the dialog contains
// any shell tree view or shell list view controls.
CShellManager *pShellManager = new CShellManager;
// Activate "Windows Native" visual manager for enabling themes in MFC controls
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CMFCRichEditDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK) {
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}else if (nResponse == IDCANCEL) {
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}else if (nResponse == -1) {
TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so
application is terminating unexpectedly.\n");
TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on
the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n");
}
// Delete the shell manager created above.
if (pShellManager != NULL) {
delete pShellManager;
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
Step 6 − Add the Click event handler for all the three buttons. Here is the implementation for these events.
void CMFCRichEditDlg::OnBnClickedButtonBold() {
// TODO: Add your control notification handler code here
CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
Cfm.cbSize = sizeof(CHARFORMAT);
Cfm.dwMask = CFM_BOLD;
Cfm.dwEffects ^= CFE_BOLD;
m_richEdit.SetSelectionCharFormat(Cfm);
m_richEdit.SetFocus();
}
void CMFCRichEditDlg::OnBnClickedButtonItalic() {
// TODO: Add your control notification handler code here
CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
Cfm.cbSize = sizeof(CHARFORMAT);
Cfm.dwMask = CFM_ITALIC;
Cfm.dwEffects ^= CFE_ITALIC;
m_richEdit.SetSelectionCharFormat(Cfm);
m_richEdit.SetFocus();
}
void CMFCRichEditDlg::OnBnClickedButtonUnderline() {
// TODO: Add your control notification handler code here
CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
Cfm.cbSize = sizeof(CHARFORMAT);
Cfm.dwMask = CFM_UNDERLINE;
Cfm.dwEffects ^= CFE_UNDERLINE;
m_richEdit.SetSelectionCharFormat(Cfm);
m_richEdit.SetFocus();
}
Step 7 − When the above code is compiled and executed, you will see the following output. Now enter text and change its formatting by selecting the text and then click on any of the three buttons.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2283,
"s": 2067,
"text": "A Rich Edit Control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. It is represented by CRichEditCtrl class."
},
{
"code": null,
"e": 2292,
"s": 2283,
"text": "CanPaste"
},
{
"code": null,
"e": 2379,
"s": 2292,
"text": "Determines if the contents of the Clipboard can be pasted into this rich edit control."
},
{
"code": null,
"e": 2387,
"s": 2379,
"text": "CanRedo"
},
{
"code": null,
"e": 2456,
"s": 2387,
"text": "Determines whether there are any actions in the controls redo queue."
},
{
"code": null,
"e": 2464,
"s": 2456,
"text": "CanUndo"
},
{
"code": null,
"e": 2514,
"s": 2464,
"text": "Determines if an editing operation can be undone."
},
{
"code": null,
"e": 2526,
"s": 2514,
"text": "CharFromPos"
},
{
"code": null,
"e": 2636,
"s": 2526,
"text": "Retrieves information about the character closest to a specified point in the client area of an edit control."
},
{
"code": null,
"e": 2642,
"s": 2636,
"text": "Clear"
},
{
"code": null,
"e": 2672,
"s": 2642,
"text": "Clears the current selection."
},
{
"code": null,
"e": 2677,
"s": 2672,
"text": "Copy"
},
{
"code": null,
"e": 2724,
"s": 2677,
"text": "Copies the current selection to the Clipboard."
},
{
"code": null,
"e": 2731,
"s": 2724,
"text": "Create"
},
{
"code": null,
"e": 2819,
"s": 2731,
"text": "Creates the Windows rich edit control and associates it with this CRichEditCtrl object."
},
{
"code": null,
"e": 2828,
"s": 2819,
"text": "CreateEx"
},
{
"code": null,
"e": 2959,
"s": 2828,
"text": "Creates the Windows rich edit control with the specified extended Windows styles and associates it with this CRichEditCtrl object."
},
{
"code": null,
"e": 2963,
"s": 2959,
"text": "Cut"
},
{
"code": null,
"e": 3008,
"s": 2963,
"text": "Cuts the current selection to the Clipboard."
},
{
"code": null,
"e": 3020,
"s": 3008,
"text": "DisplayBand"
},
{
"code": null,
"e": 3085,
"s": 3020,
"text": "Displays a portion of the contents of this CRichEditCtrl object."
},
{
"code": null,
"e": 3101,
"s": 3085,
"text": "EmptyUndoBuffer"
},
{
"code": null,
"e": 3161,
"s": 3101,
"text": "Resets (clears) the undo flag of this CRichEditCtrl object."
},
{
"code": null,
"e": 3170,
"s": 3161,
"text": "FindText"
},
{
"code": null,
"e": 3217,
"s": 3170,
"text": "Locates text within this CRichEditCtrl object."
},
{
"code": null,
"e": 3231,
"s": 3217,
"text": "FindWordBreak"
},
{
"code": null,
"e": 3370,
"s": 3231,
"text": "Finds the next word break before or after the specified character position, or retrieves information about the character at that position."
},
{
"code": null,
"e": 3382,
"s": 3370,
"text": "FormatRange"
},
{
"code": null,
"e": 3436,
"s": 3382,
"text": "Formats a range of text for the target output device."
},
{
"code": null,
"e": 3447,
"s": 3436,
"text": "GetCharPos"
},
{
"code": null,
"e": 3526,
"s": 3447,
"text": "Determines the location of a given character within this CRichEditCtrl object."
},
{
"code": null,
"e": 3547,
"s": 3526,
"text": "GetDefaultCharFormat"
},
{
"code": null,
"e": 3639,
"s": 3547,
"text": "Retrieves the current default character formatting attributes in this CRichEditCtrl object."
},
{
"code": null,
"e": 3652,
"s": 3639,
"text": "GetEventMask"
},
{
"code": null,
"e": 3708,
"s": 3652,
"text": "Retrieves the event mask for this CRichEditCtrl object."
},
{
"code": null,
"e": 3728,
"s": 3708,
"text": "GetFirstVisibleLine"
},
{
"code": null,
"e": 3794,
"s": 3728,
"text": "Determines the topmost visible line in this CRichEditCtrl object."
},
{
"code": null,
"e": 3810,
"s": 3794,
"text": "GetIRichEditOle"
},
{
"code": null,
"e": 3888,
"s": 3810,
"text": "Retrieves a pointer to the IRichEditOle interface for this rich edit control."
},
{
"code": null,
"e": 3901,
"s": 3888,
"text": "GetLimitText"
},
{
"code": null,
"e": 3987,
"s": 3901,
"text": "Gets the limit on the amount of text a user can enter into this CRichEditCtrl object."
},
{
"code": null,
"e": 3995,
"s": 3987,
"text": "GetLine"
},
{
"code": null,
"e": 4052,
"s": 3995,
"text": "Retrieves a line of text from this CRichEditCtrl object."
},
{
"code": null,
"e": 4065,
"s": 4052,
"text": "GetLineCount"
},
{
"code": null,
"e": 4125,
"s": 4065,
"text": "Retrieves the number of lines in this CRichEditCtrl object."
},
{
"code": null,
"e": 4135,
"s": 4125,
"text": "GetModify"
},
{
"code": null,
"e": 4225,
"s": 4135,
"text": "Determines if the contents of this CRichEditCtrl object have changed since the last save."
},
{
"code": null,
"e": 4236,
"s": 4225,
"text": "GetOptions"
},
{
"code": null,
"e": 4277,
"s": 4236,
"text": "Retrieves the rich edit control options."
},
{
"code": null,
"e": 4291,
"s": 4277,
"text": "GetParaFormat"
},
{
"code": null,
"e": 4392,
"s": 4291,
"text": "Retrieves the paragraph formatting attributes in the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 4407,
"s": 4392,
"text": "GetPunctuation"
},
{
"code": null,
"e": 4561,
"s": 4407,
"text": "Retrieves the current punctuation characters for the rich edit control. This message is available only in Asianlanguage versions of the operating system."
},
{
"code": null,
"e": 4569,
"s": 4561,
"text": "GetRect"
},
{
"code": null,
"e": 4635,
"s": 4569,
"text": "Retrieves the formatting rectangle for this CRichEditCtrl object."
},
{
"code": null,
"e": 4647,
"s": 4635,
"text": "GetRedoName"
},
{
"code": null,
"e": 4723,
"s": 4647,
"text": "Retrieves the type of the next action, if any, in the control's redo queue."
},
{
"code": null,
"e": 4730,
"s": 4723,
"text": "GetSel"
},
{
"code": null,
"e": 4824,
"s": 4730,
"text": "Gets the starting and ending positions of the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 4847,
"s": 4824,
"text": "GetSelectionCharFormat"
},
{
"code": null,
"e": 4948,
"s": 4847,
"text": "Retrieves the character formatting attributes in the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 4965,
"s": 4948,
"text": "GetSelectionType"
},
{
"code": null,
"e": 5051,
"s": 4965,
"text": "Retrieves the type of contents in the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 5062,
"s": 5051,
"text": "GetSelText"
},
{
"code": null,
"e": 5131,
"s": 5062,
"text": "Gets the text of the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 5145,
"s": 5131,
"text": "GetTextLength"
},
{
"code": null,
"e": 5273,
"s": 5145,
"text": "Retrieves the length of the text, in characters, in this CRichEditCtrl object. Does not include the terminating null character."
},
{
"code": null,
"e": 5289,
"s": 5273,
"text": "GetTextLengthEx"
},
{
"code": null,
"e": 5461,
"s": 5289,
"text": "Retrieves the number of characters or bytes in the rich edit view. Accepts a list of flags to indicate the method of determining length of the text in a rich edit control."
},
{
"code": null,
"e": 5473,
"s": 5461,
"text": "GetTextMode"
},
{
"code": null,
"e": 5544,
"s": 5473,
"text": "Retrieves the current text mode and undo level of a rich edit control."
},
{
"code": null,
"e": 5557,
"s": 5544,
"text": "GetTextRange"
},
{
"code": null,
"e": 5596,
"s": 5557,
"text": "Retrieves the specified range of text."
},
{
"code": null,
"e": 5608,
"s": 5596,
"text": "GetUndoName"
},
{
"code": null,
"e": 5660,
"s": 5608,
"text": "Retrieves the type of the next undo action, if any."
},
{
"code": null,
"e": 5676,
"s": 5660,
"text": "GetWordWrapMode"
},
{
"code": null,
"e": 5848,
"s": 5676,
"text": "Retrieves the current word wrapping and word breaking options for the rich edit control. This message is available only in Asian-language versions of the operating system."
},
{
"code": null,
"e": 5862,
"s": 5848,
"text": "HideSelection"
},
{
"code": null,
"e": 5900,
"s": 5862,
"text": "Shows or hides the current selection."
},
{
"code": null,
"e": 5910,
"s": 5900,
"text": "LimitText"
},
{
"code": null,
"e": 5984,
"s": 5910,
"text": "Limits the amount of text a user can enter into the CRichEditCtrl object."
},
{
"code": null,
"e": 5997,
"s": 5984,
"text": "LineFromChar"
},
{
"code": null,
"e": 6049,
"s": 5997,
"text": "Determines which line contains the given character."
},
{
"code": null,
"e": 6059,
"s": 6049,
"text": "LineIndex"
},
{
"code": null,
"e": 6135,
"s": 6059,
"text": "Retrieves the character index of a given line in this CRichEditCtrl object."
},
{
"code": null,
"e": 6146,
"s": 6135,
"text": "LineLength"
},
{
"code": null,
"e": 6213,
"s": 6146,
"text": "Retrieves the length of a given line in this CRichEditCtrl object."
},
{
"code": null,
"e": 6224,
"s": 6213,
"text": "LineScroll"
},
{
"code": null,
"e": 6271,
"s": 6224,
"text": "Scrolls the text in this CRichEditCtrl object."
},
{
"code": null,
"e": 6277,
"s": 6271,
"text": "Paste"
},
{
"code": null,
"e": 6344,
"s": 6277,
"text": "Inserts the contents of the Clipboard into this rich edit control."
},
{
"code": null,
"e": 6357,
"s": 6344,
"text": "PasteSpecial"
},
{
"code": null,
"e": 6454,
"s": 6357,
"text": "Inserts the contents of the Clipboard into this rich edit control in the specified data format.\n"
},
{
"code": null,
"e": 6466,
"s": 6454,
"text": "PosFromChar"
},
{
"code": null,
"e": 6549,
"s": 6466,
"text": "Retrieves the client area coordinates of a specified character in an edit control."
},
{
"code": null,
"e": 6554,
"s": 6549,
"text": "Redo"
},
{
"code": null,
"e": 6606,
"s": 6554,
"text": "Redoes the next action in the control's redo queue."
},
{
"code": null,
"e": 6617,
"s": 6606,
"text": "ReplaceSel"
},
{
"code": null,
"e": 6698,
"s": 6617,
"text": "Replaces the current selection in this CRichEditCtrl object with specified text."
},
{
"code": null,
"e": 6712,
"s": 6698,
"text": "RequestResize"
},
{
"code": null,
"e": 6783,
"s": 6712,
"text": "Forces this CRichEditCtrl object to send request resize notifications."
},
{
"code": null,
"e": 6800,
"s": 6783,
"text": "SetAutoURLDetect"
},
{
"code": null,
"e": 6870,
"s": 6800,
"text": "Indicates if the auto URL detection is active in a rich edit control."
},
{
"code": null,
"e": 6889,
"s": 6870,
"text": "SetBackgroundColor"
},
{
"code": null,
"e": 6945,
"s": 6889,
"text": "Sets the background color in this CRichEditCtrl object."
},
{
"code": null,
"e": 6966,
"s": 6945,
"text": "SetDefaultCharFormat"
},
{
"code": null,
"e": 7053,
"s": 6966,
"text": "Sets the current default character formatting attributes in this CRichEditCtrl object."
},
{
"code": null,
"e": 7066,
"s": 7053,
"text": "SetEventMask"
},
{
"code": null,
"e": 7117,
"s": 7066,
"text": "Sets the event mask for this CRichEditCtrl object."
},
{
"code": null,
"e": 7127,
"s": 7117,
"text": "SetModify"
},
{
"code": null,
"e": 7195,
"s": 7127,
"text": "Sets or clears the modification flag for this CRichEditCtrl object."
},
{
"code": null,
"e": 7210,
"s": 7195,
"text": "SetOLECallback"
},
{
"code": null,
"e": 7279,
"s": 7210,
"text": "Sets the IRichEditOleCallback COM object for this rich edit control."
},
{
"code": null,
"e": 7290,
"s": 7279,
"text": "SetOptions"
},
{
"code": null,
"e": 7338,
"s": 7290,
"text": "Sets the options for this CRichEditCtrl object."
},
{
"code": null,
"e": 7352,
"s": 7338,
"text": "SetParaFormat"
},
{
"code": null,
"e": 7448,
"s": 7352,
"text": "Sets the paragraph formatting attributes in the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 7463,
"s": 7448,
"text": "SetPunctuation"
},
{
"code": null,
"e": 7602,
"s": 7463,
"text": "Sets the punctuation characters for a rich edit control. This message is available only in Asianlanguage versions of the operating system."
},
{
"code": null,
"e": 7614,
"s": 7602,
"text": "SetReadOnly"
},
{
"code": null,
"e": 7671,
"s": 7614,
"text": "Sets the read-only option for this CRichEditCtrl object."
},
{
"code": null,
"e": 7679,
"s": 7671,
"text": "SetRect"
},
{
"code": null,
"e": 7740,
"s": 7679,
"text": "Sets the formatting rectangle for this CRichEditCtrl object."
},
{
"code": null,
"e": 7747,
"s": 7740,
"text": "SetSel"
},
{
"code": null,
"e": 7796,
"s": 7747,
"text": "Sets the selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 7819,
"s": 7796,
"text": "SetSelectionCharFormat"
},
{
"code": null,
"e": 7915,
"s": 7819,
"text": "Sets the character formatting attributes in the current selection in this CRichEditCtrl object."
},
{
"code": null,
"e": 7931,
"s": 7915,
"text": "SetTargetDevice"
},
{
"code": null,
"e": 7992,
"s": 7931,
"text": "Sets the target output device for this CRichEditCtrl object."
},
{
"code": null,
"e": 8004,
"s": 7992,
"text": "SetTextMode"
},
{
"code": null,
"e": 8109,
"s": 8004,
"text": "Sets the text mode or undo level of a rich edit control. The message fails if the control contains text."
},
{
"code": null,
"e": 8122,
"s": 8109,
"text": "SetUndoLimit"
},
{
"code": null,
"e": 8192,
"s": 8122,
"text": "Sets the maximum number of actions that can stored in the undo queue."
},
{
"code": null,
"e": 8210,
"s": 8192,
"text": "SetWordCharFormat"
},
{
"code": null,
"e": 8301,
"s": 8210,
"text": "Sets the character formatting attributes in the current word in this CRichEditCtrl object."
},
{
"code": null,
"e": 8317,
"s": 8301,
"text": "SetWordWrapMode"
},
{
"code": null,
"e": 8475,
"s": 8317,
"text": "Sets the word-wrapping and word-breaking options for the rich edit control. This message is available only in Asianlanguage versions of the operating system."
},
{
"code": null,
"e": 8491,
"s": 8475,
"text": "StopGroupTyping"
},
{
"code": null,
"e": 8669,
"s": 8491,
"text": "Stops the control from collecting additional typing actions into the current undo action. The control stores the next typing action, if any, into a new action in the undo queue."
},
{
"code": null,
"e": 8678,
"s": 8669,
"text": "StreamIn"
},
{
"code": null,
"e": 8743,
"s": 8678,
"text": "Inserts text from an input stream into this CRichEditCtrl object"
},
{
"code": null,
"e": 8753,
"s": 8743,
"text": "StreamOut"
},
{
"code": null,
"e": 8819,
"s": 8753,
"text": "Stores text from this CRichEditCtrl object into an output stream."
},
{
"code": null,
"e": 8824,
"s": 8819,
"text": "Undo"
},
{
"code": null,
"e": 8861,
"s": 8824,
"text": "Reverses the last editing operation."
},
{
"code": null,
"e": 8938,
"s": 8861,
"text": "Let us into a simple example by creating a new MFC dialog based application."
},
{
"code": null,
"e": 9035,
"s": 8938,
"text": "Step 1 − Delete the TODO line and drag one Rich Edit Control and three buttons from the Toolbox."
},
{
"code": null,
"e": 9196,
"s": 9035,
"text": "Step 2 − Change the Caption of these three buttons from Bold, Italic and Under Line to IDC_BUTTON_BOLD, IDC_BUTTON_ITALIC and IDC_BUTTON_UNDERLINE respectively."
},
{
"code": null,
"e": 9284,
"s": 9196,
"text": "Step 3 − Set the following properties to True: Multiline, Want Return, Vertical Scroll."
},
{
"code": null,
"e": 9352,
"s": 9284,
"text": "Step 4 − Add the control variable m_richEdit for Rich Edit Control."
},
{
"code": null,
"e": 9497,
"s": 9352,
"text": "Step 5 − Go to the CMFCRichEditApp and call the ::AfxInitRichEdit2() in CMFCRichEditApp::InitInstance() function as shown in the following code."
},
{
"code": null,
"e": 11917,
"s": 9497,
"text": "BOOL CMFCRichEditApp::InitInstance() {\n//TODO: call AfxInitRichEdit2() to initialize richedit2 library.\n // InitCommonControlsEx() is required on Windows XP if an application\n // manifest specifies use of ComCtl32.dll version 6 or later to enable\n // visual styles. Otherwise, any window creation will fail.\n INITCOMMONCONTROLSEX InitCtrls;\n InitCtrls.dwSize = sizeof(InitCtrls);\n // Set this to include all the common control classes you want to use\n // in your application.\n InitCtrls.dwICC = ICC_WIN95_CLASSES;\n InitCommonControlsEx(&InitCtrls);\n\n ::AfxInitRichEdit2();\n CWinApp::InitInstance();\n\n \n AfxEnableControlContainer();\n \n // Create the shell manager, in case the dialog contains\n // any shell tree view or shell list view controls.\n CShellManager *pShellManager = new CShellManager;\n\n // Activate \"Windows Native\" visual manager for enabling themes in MFC controls\n CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));\n\n // Standard initialization\n // If you are not using these features and wish to reduce the size\n // of your final executable, you should remove from the following\n // the specific initialization routines you do not need\n // Change the registry key under which our settings are stored\n // TODO: You should modify this string to be something appropriate\n // such as the name of your company or organization\n SetRegistryKey(_T(\"Local AppWizard-Generated Applications\"));\n\n CMFCRichEditDlg dlg;\n m_pMainWnd = &dlg;\n INT_PTR nResponse = dlg.DoModal();\n if (nResponse == IDOK) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with OK\n }else if (nResponse == IDCANCEL) {\n // TODO: Place code here to handle when the dialog is\n // dismissed with Cancel\n }else if (nResponse == -1) {\n TRACE(traceAppMsg, 0, \"Warning: dialog creation failed, so\n application is terminating unexpectedly.\\n\");\n TRACE(traceAppMsg, 0, \"Warning: if you are using MFC controls on\n the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\\n\");\n }\n\t\n // Delete the shell manager created above.\n if (pShellManager != NULL) {\n delete pShellManager;\n }\n\t\n // Since the dialog has been closed, return FALSE so that we exit the\n // application, rather than start the application's message pump.\n return FALSE;\n}"
},
{
"code": null,
"e": 12026,
"s": 11917,
"text": "Step 6 − Add the Click event handler for all the three buttons. Here is the implementation for these events."
},
{
"code": null,
"e": 13104,
"s": 12026,
"text": "void CMFCRichEditDlg::OnBnClickedButtonBold() { \n // TODO: Add your control notification handler code here \n CHARFORMAT Cfm;\n\t\n m_richEdit.GetSelectionCharFormat(Cfm); \n\t\n Cfm.cbSize = sizeof(CHARFORMAT); \n Cfm.dwMask = CFM_BOLD; \n Cfm.dwEffects ^= CFE_BOLD; \n\t\n m_richEdit.SetSelectionCharFormat(Cfm); \n m_richEdit.SetFocus(); \n}\n \nvoid CMFCRichEditDlg::OnBnClickedButtonItalic() { \n // TODO: Add your control notification handler code here\n CHARFORMAT Cfm; \n \n m_richEdit.GetSelectionCharFormat(Cfm); \n\t\n Cfm.cbSize = sizeof(CHARFORMAT); \n Cfm.dwMask = CFM_ITALIC; \n Cfm.dwEffects ^= CFE_ITALIC; \n\t\n m_richEdit.SetSelectionCharFormat(Cfm); \n m_richEdit.SetFocus(); \n}\n \nvoid CMFCRichEditDlg::OnBnClickedButtonUnderline() { \n // TODO: Add your control notification handler code here \n CHARFORMAT Cfm; \n\t\n m_richEdit.GetSelectionCharFormat(Cfm); \n\t\n Cfm.cbSize = sizeof(CHARFORMAT); \n Cfm.dwMask = CFM_UNDERLINE; \n Cfm.dwEffects ^= CFE_UNDERLINE; \n\t\n m_richEdit.SetSelectionCharFormat(Cfm); \n m_richEdit.SetFocus(); \n} "
},
{
"code": null,
"e": 13301,
"s": 13104,
"text": "Step 7 − When the above code is compiled and executed, you will see the following output. Now enter text and change its formatting by selecting the text and then click on any of the three buttons."
},
{
"code": null,
"e": 13308,
"s": 13301,
"text": " Print"
},
{
"code": null,
"e": 13319,
"s": 13308,
"text": " Add Notes"
}
] |
What is the maximum length of a table name in MySQL?
|
The maximum length of a table name is 64 characters long according to MySQl version 8.0.12.
Check your installed MySQL version.
mysql> select version();
The following is the output.
+-----------+
| version() |
+-----------+
| 8.0.12 |
+-----------+
1 row in set (0.03 sec)
We can check the maximum length of the table name at the time of creating it. If we give more than 64 characters, then it will not create a table and an error is thrown.
Creating a table which has more than 64 characters of table name.
mysql> create table tableNameDemotableableNameDemotableableNameDemotableableNameDemotable
-> (
-> id int
-> );
ERROR 1059 (42000): Identifier name 'tableNameDemotableableNameDemotableableNameDemotableableNameDemotable' is too long
In the above, we get an error that the identifier name (yourTableName) is too long.
To check if it will work for 64 characters or below −
mysql> create table Demo
-> (
-> id int
-> );
Query OK, 0 rows affected (0.46 sec)
Yes, less than 64 characters for a table name works correctly.
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "The maximum length of a table name is 64 characters long according to MySQl version 8.0.12."
},
{
"code": null,
"e": 1190,
"s": 1154,
"text": "Check your installed MySQL version."
},
{
"code": null,
"e": 1215,
"s": 1190,
"text": "mysql> select version();"
},
{
"code": null,
"e": 1244,
"s": 1215,
"text": "The following is the output."
},
{
"code": null,
"e": 1339,
"s": 1244,
"text": "+-----------+\n| version() |\n+-----------+\n| 8.0.12 |\n+-----------+\n1 row in set (0.03 sec)\n"
},
{
"code": null,
"e": 1509,
"s": 1339,
"text": "We can check the maximum length of the table name at the time of creating it. If we give more than 64 characters, then it will not create a table and an error is thrown."
},
{
"code": null,
"e": 1575,
"s": 1509,
"text": "Creating a table which has more than 64 characters of table name."
},
{
"code": null,
"e": 1815,
"s": 1575,
"text": "mysql> create table tableNameDemotableableNameDemotableableNameDemotableableNameDemotable\n -> (\n -> id int\n -> );\nERROR 1059 (42000): Identifier name 'tableNameDemotableableNameDemotableableNameDemotableableNameDemotable' is too long"
},
{
"code": null,
"e": 1899,
"s": 1815,
"text": "In the above, we get an error that the identifier name (yourTableName) is too long."
},
{
"code": null,
"e": 1953,
"s": 1899,
"text": "To check if it will work for 64 characters or below −"
},
{
"code": null,
"e": 2045,
"s": 1953,
"text": "mysql> create table Demo\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 2108,
"s": 2045,
"text": "Yes, less than 64 characters for a table name works correctly."
}
] |
YAML - Processes
|
YAML follows a standard procedure for Process flow. The native data structure in YAML includes simple representations such as nodes. It is also called as Representation Node Graph.
It includes mapping, sequence and scalar quantities which is being serialized to create a serialization tree. With serialization the objects are converted with stream of bytes.
The serialization event tree helps in creating presentation of character streams as represented in the following diagram.
The reverse procedure parses the stream of bytes into serialized event tree. Later, the nodes are converted into node graph. These values are later converted in YAML native data structure. The figure below explains this −
The information in YAML is used in two ways: machine processing and human consumption. The processor in YAML is used as a tool for the procedure of converting information between complementary views in the diagram given above. This chapter describes the information structures a YAML processor must provide within a given application.
YAML includes a serialization procedure for representing data objects in serial format. The processing of YAML information includes three stages: Representation, Serialization, Presentation and parsing. Let us discuss each of them in detail.
YAML represents the data structure using three kinds of nodes: sequence, mapping and scalar.
Sequence refers to the ordered number of entries, which maps the unordered association of key value pair. It corresponds to the Perl or Python array list.
The code shown below is an example of sequence representation −
product:
- sku : BL394D
quantity : 4
description : Football
price : 450.00
- sku : BL4438H
quantity : 1
description : Super Hoop
price : 2392.00
Mapping on the other hand represents dictionary data structure or hash table. An example for the same is mentioned below −
batchLimit: 1000
threadCountLimit: 2
key: value
keyMapping: <What goes here?>
Scalars represent standard values of strings, integers, dates and atomic data types. Note that YAML also includes nodes which specify the data type structure. For more information on scalars, please refer to the chapter 6 of this tutorial.
Serialization process is required in YAML that eases human friendly key order and anchor names. The result of serialization is a YAML serialization tree. It can be traversed to produce a series of event calls of YAML data.
An example for serialization is given below −
consumer:
class: 'AppBundle\Entity\consumer'
attributes:
filters: ['customer.search', 'customer.order', 'customer.boolean']
collectionOperations:
get:
method: 'GET'
normalization_context:
groups: ['customer_list']
itemOperations:
get:
method: 'GET'
normalization_context:
groups: ['customer_get']
The final output of YAML serialization is called presentation. It represents a character stream in a human friendly manner. YAML processor includes various presentation details for creating stream, handling indentation and formatting content. This complete process is guided by the preferences of user.
An example for YAML presentation process is the result of JSON value created. Observe the code given below for a better understanding −
{
"consumer": {
"class": "AppBundle\\Entity\\consumer",
"attributes": {
"filters": [
"customer.search",
"customer.order",
"customer.boolean"
]
},
"collectionOperations": {
"get": {
"method": "GET",
"normalization_context": {
"groups": [
"customer_list"
]
}
}
},
"itemOperations": {
"get": {
"method": "GET",
"normalization_context": {
"groups": [
"customer_get"
]
}
}
}
}
}
Parsing is the inverse process of presentation; it includes a stream of characters and creates a series of events. It discards the details introduced in the presentation process which causes serialization events. Parsing procedure can fail due to ill-formed input. It is basically a procedure to check whether YAML is well-formed or not.
Consider a YAML example which is mentioned below −
---
environment: production
classes:
nfs::server:
exports:
- /srv/share1
- /srv/share3
parameters:
paramter1
With three hyphens, it represents the start of document with various attributes later defined in it.
YAML lint is the online parser of YAML and helps in parsing the YAML structure to check whether it is valid or not. The official link for YAML lint is mentioned below: http://www.yamllint.com/
You can see the output of parsing as shown below −
33 Lectures
44 mins
Tarun Telang
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2229,
"s": 2048,
"text": "YAML follows a standard procedure for Process flow. The native data structure in YAML includes simple representations such as nodes. It is also called as Representation Node Graph."
},
{
"code": null,
"e": 2406,
"s": 2229,
"text": "It includes mapping, sequence and scalar quantities which is being serialized to create a serialization tree. With serialization the objects are converted with stream of bytes."
},
{
"code": null,
"e": 2528,
"s": 2406,
"text": "The serialization event tree helps in creating presentation of character streams as represented in the following diagram."
},
{
"code": null,
"e": 2750,
"s": 2528,
"text": "The reverse procedure parses the stream of bytes into serialized event tree. Later, the nodes are converted into node graph. These values are later converted in YAML native data structure. The figure below explains this −"
},
{
"code": null,
"e": 3085,
"s": 2750,
"text": "The information in YAML is used in two ways: machine processing and human consumption. The processor in YAML is used as a tool for the procedure of converting information between complementary views in the diagram given above. This chapter describes the information structures a YAML processor must provide within a given application."
},
{
"code": null,
"e": 3327,
"s": 3085,
"text": "YAML includes a serialization procedure for representing data objects in serial format. The processing of YAML information includes three stages: Representation, Serialization, Presentation and parsing. Let us discuss each of them in detail."
},
{
"code": null,
"e": 3421,
"s": 3327,
"text": "YAML represents the data structure using three kinds of nodes: sequence, mapping and scalar."
},
{
"code": null,
"e": 3576,
"s": 3421,
"text": "Sequence refers to the ordered number of entries, which maps the unordered association of key value pair. It corresponds to the Perl or Python array list."
},
{
"code": null,
"e": 3640,
"s": 3576,
"text": "The code shown below is an example of sequence representation −"
},
{
"code": null,
"e": 3855,
"s": 3640,
"text": "product:\n - sku : BL394D\n quantity : 4\n description : Football\n price : 450.00\n - sku : BL4438H\n quantity : 1\n description : Super Hoop\n price : 2392.00"
},
{
"code": null,
"e": 3978,
"s": 3855,
"text": "Mapping on the other hand represents dictionary data structure or hash table. An example for the same is mentioned below −"
},
{
"code": null,
"e": 4057,
"s": 3978,
"text": "batchLimit: 1000\nthreadCountLimit: 2\nkey: value\nkeyMapping: <What goes here?>\n"
},
{
"code": null,
"e": 4297,
"s": 4057,
"text": "Scalars represent standard values of strings, integers, dates and atomic data types. Note that YAML also includes nodes which specify the data type structure. For more information on scalars, please refer to the chapter 6 of this tutorial."
},
{
"code": null,
"e": 4520,
"s": 4297,
"text": "Serialization process is required in YAML that eases human friendly key order and anchor names. The result of serialization is a YAML serialization tree. It can be traversed to produce a series of event calls of YAML data."
},
{
"code": null,
"e": 4566,
"s": 4520,
"text": "An example for serialization is given below −"
},
{
"code": null,
"e": 4949,
"s": 4566,
"text": "consumer:\n class: 'AppBundle\\Entity\\consumer'\n attributes:\n filters: ['customer.search', 'customer.order', 'customer.boolean']\n collectionOperations:\n get:\n method: 'GET'\n normalization_context:\n groups: ['customer_list']\n itemOperations:\n get:\n method: 'GET'\n normalization_context:\n groups: ['customer_get']\n"
},
{
"code": null,
"e": 5252,
"s": 4949,
"text": "The final output of YAML serialization is called presentation. It represents a character stream in a human friendly manner. YAML processor includes various presentation details for creating stream, handling indentation and formatting content. This complete process is guided by the preferences of user."
},
{
"code": null,
"e": 5388,
"s": 5252,
"text": "An example for YAML presentation process is the result of JSON value created. Observe the code given below for a better understanding −"
},
{
"code": null,
"e": 6068,
"s": 5388,
"text": "{\n \"consumer\": {\n \"class\": \"AppBundle\\\\Entity\\\\consumer\",\n \"attributes\": {\n \"filters\": [\n \"customer.search\",\n \"customer.order\",\n \"customer.boolean\"\n ]\n },\n \"collectionOperations\": {\n \"get\": {\n \"method\": \"GET\",\n \"normalization_context\": {\n \"groups\": [\n \"customer_list\"\n ]\n }\n }\n },\n \"itemOperations\": {\n \"get\": {\n \"method\": \"GET\",\n \"normalization_context\": {\n \"groups\": [\n \"customer_get\"\n ]\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 6407,
"s": 6068,
"text": "Parsing is the inverse process of presentation; it includes a stream of characters and creates a series of events. It discards the details introduced in the presentation process which causes serialization events. Parsing procedure can fail due to ill-formed input. It is basically a procedure to check whether YAML is well-formed or not."
},
{
"code": null,
"e": 6458,
"s": 6407,
"text": "Consider a YAML example which is mentioned below −"
},
{
"code": null,
"e": 6621,
"s": 6458,
"text": "---\n environment: production\n classes:\n nfs::server:\n exports:\n - /srv/share1\n - /srv/share3\n parameters:\n paramter1"
},
{
"code": null,
"e": 6722,
"s": 6621,
"text": "With three hyphens, it represents the start of document with various attributes later defined in it."
},
{
"code": null,
"e": 6915,
"s": 6722,
"text": "YAML lint is the online parser of YAML and helps in parsing the YAML structure to check whether it is valid or not. The official link for YAML lint is mentioned below: http://www.yamllint.com/"
},
{
"code": null,
"e": 6966,
"s": 6915,
"text": "You can see the output of parsing as shown below −"
},
{
"code": null,
"e": 6998,
"s": 6966,
"text": "\n 33 Lectures \n 44 mins\n"
},
{
"code": null,
"e": 7012,
"s": 6998,
"text": " Tarun Telang"
},
{
"code": null,
"e": 7019,
"s": 7012,
"text": " Print"
},
{
"code": null,
"e": 7030,
"s": 7019,
"text": " Add Notes"
}
] |
Can Static Functions Be Virtual in C++? - GeeksforGeeks
|
22 Dec, 2021
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren’t tied to the the instance of a class but they are tied to the class. C++ doesn’t have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.
For example, below program gives compilation error,
CPP
// CPP Program to demonstrate Virtual member functions// cannot be static#include <iostream> using namespace std; class Test {public: virtual static void fun() {}};
Output
prog.cpp:9:29: error: member ‘fun’ cannot be declared both virtual and static
virtual static void fun() {}
^
Also, static member function cannot be const and volatile. Following code also fails in compilation,
CPP
// CPP Program to demonstrate Static member function cannot// be const#include <iostream> using namespace std; class Test {public: static void fun() const {}};
Output
prog.cpp:8:23: error: static member function ‘static void Test::fun()’ cannot have cv-qualifier
static void fun() const {}
^
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
C++-Static Keyword
Static Keyword
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Function Pointer in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24332,
"s": 24304,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 24696,
"s": 24332,
"text": "In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren’t tied to the the instance of a class but they are tied to the class. C++ doesn’t have pointers-to-class, so there is no scenario in which you could invoke a static function virtually."
},
{
"code": null,
"e": 24748,
"s": 24696,
"text": "For example, below program gives compilation error,"
},
{
"code": null,
"e": 24752,
"s": 24748,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate Virtual member functions// cannot be static#include <iostream> using namespace std; class Test {public: virtual static void fun() {}};",
"e": 24922,
"s": 24752,
"text": null
},
{
"code": null,
"e": 24929,
"s": 24922,
"text": "Output"
},
{
"code": null,
"e": 25070,
"s": 24929,
"text": "prog.cpp:9:29: error: member ‘fun’ cannot be declared both virtual and static\n virtual static void fun() {}\n ^"
},
{
"code": null,
"e": 25171,
"s": 25070,
"text": "Also, static member function cannot be const and volatile. Following code also fails in compilation,"
},
{
"code": null,
"e": 25175,
"s": 25171,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate Static member function cannot// be const#include <iostream> using namespace std; class Test {public: static void fun() const {}};",
"e": 25340,
"s": 25175,
"text": null
},
{
"code": null,
"e": 25347,
"s": 25340,
"text": "Output"
},
{
"code": null,
"e": 25498,
"s": 25347,
"text": "prog.cpp:8:23: error: static member function ‘static void Test::fun()’ cannot have cv-qualifier\n static void fun() const {}\n ^"
},
{
"code": null,
"e": 25623,
"s": 25498,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25637,
"s": 25623,
"text": "anshikajain26"
},
{
"code": null,
"e": 25656,
"s": 25637,
"text": "C++-Static Keyword"
},
{
"code": null,
"e": 25671,
"s": 25656,
"text": "Static Keyword"
},
{
"code": null,
"e": 25682,
"s": 25671,
"text": "C Language"
},
{
"code": null,
"e": 25686,
"s": 25682,
"text": "C++"
},
{
"code": null,
"e": 25690,
"s": 25686,
"text": "CPP"
},
{
"code": null,
"e": 25788,
"s": 25690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25797,
"s": 25788,
"text": "Comments"
},
{
"code": null,
"e": 25810,
"s": 25797,
"text": "Old Comments"
},
{
"code": null,
"e": 25838,
"s": 25810,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25850,
"s": 25838,
"text": "fork() in C"
},
{
"code": null,
"e": 25882,
"s": 25850,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25929,
"s": 25882,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 25951,
"s": 25929,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25969,
"s": 25951,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 25988,
"s": 25969,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26034,
"s": 25988,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 26077,
"s": 26034,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
The TensorFlow Keras Summary Capture Layer | by Chaim Rand | Towards Data Science
|
In previous posts, I have told you about how my team at Mobileye, (officially known as Mobileye, an Intel Company), has tackled some of the challenges that came up, while using TensorFlow to train deep neural networks. In particular, I have covered topics such as performance profiling, and debugging. This post addresses an additional component of training machine learning models, that of monitoring the learning process.
Monitoring the learning process is an important, and often time-consuming, part of DNN training, during which we track a variety of tensors, metrics and statistics, in order to understand how our training is progressing, and figure out what improvements to make to model architecture and/or hyperparameters.
One of the most popular ways of doing this when training in TensorFlow, is using TensorBoard. TensorBoard supports a variety of methods for tracking and debugging the training process. On our team, we rely heavily on TensorBoard. We track losses, generate gradient histograms, and measure activation outputs. We log metrics, display confusion matrices, and generate visual images from the output data. Sometimes we use it debug intermediate operations performed by the loss function, or to measure the distribution of weights on a specific layer in the graph. We use TensorBoard extensively.
The way to use TensorBoard is by inserting “summary” commands into the training code using the tf.summary module. In version 2, TensorFlow made significant revisions to the training flow, and, in particular, to the tf summary mechanism. While this revision simplified some of the straightforward usages of tf.summary, some of the more advanced usages are not immediately obvious. For example, it is not at all clear (to me, at least), how TensorFlow intended for me to be able to log graph (non-eager) tensors, such as the distribution of the output of a specific activation layer within my graph, or the value of an arbitrary tensor within my loss function. (If you know, please don’t hesitate to share :).)
My intention, in this post, is to propose a solution for capturing summaries from graph tensors, that relies on the creation of a custom tf.keras.Layer. Along the way, I will provide a bit more insight into the problem, as well as some of the alternative solutions we considered. If you are eager to get straight to the custom summary capture layer, feel free to skip ahead.
As TensorFlow and TensorBoard continue to undergo changes and improvements, it is important to note that my story is based on trials that I ran using TensorFlow version 2.3.0.
The following brief history is partial, in the sense that it is incomplete, and that it is based on my own experience.
In version 1 of TensorFlow, we would freely scatter tf.summary ops on arbitrary tensors across our code, and would use the tf session.run() function to record the associated tensor values to event files, at predetermined intervals. As our use of TensorBoard evolved, we would also use it to record the results of general python calculations that we would make based on the graph output, such as image visualizations of model predictions overlaid on an input frame, or visualizations of the confusion matrix. Since summaries needed to be graph ops, we would do this by creating small auxiliary graphs that would define a summary op on a numpy array (such as an image). Later, we adopted the high level tf.estimator APIs, which included controls for setting the summary interval and handled the session.run calls on the summary ops for us. We also integrated the use of the estimator hooks, such as the tf.estimator.SummarySaverHook and other custom hooks, to support our wide variety of usages. Life was grand.
Along came tf.keras with its own unique blueprint for the training flow, and its own high level training API tf.keras.model.fit(). The model.fit() function did not include support for managing tf.summarys, requiring a bit more manual labor. But we quickly worked out how to enable all of our TensorBoard usages by creating custom tf.keras.callbacks, and directly configuring the execution function to collect the desired tensors, using all kinds of voodoo involving model._fit_function.fetches and model._fit_function.fetch_callbacks. No, it wasn’t pretty, but it worked. The tf.keras API also introduced a TensorBoard callback, which supported capturing a variety of popular training monitoring metrics.
Then came TensorFlow 2. Once again, the blueprint for the training flow changed, the use of the model._fit_function became obsolete, and the mechanism for recording tensors was revised. As described by TensorFlow, the new mechanism does have its advantages. Previously, recording tensors was a two step process. Now, a call to tf.summary would result in immediate recording of the tensor to the event file. In particular, this meant that the tf summary ops were no longer built into the TensorFlow computation graph. In addition, the tf.summary call could only be called on eager tensors (or raw numpy arrays). More on this in the next section.
While a full understanding of the changes that were introduced in TensorFlow 2 is beyond the scope of this post, I would like to touch on a few of the details that pertain to the topic of collecting summaries. To get the full picture, I refer you to the TensorFlow documentation.
While in tf1, the default execution mode is graph mode, a symbolic execution mode in which users define an abstract syntax tree and execute it using the TensorFlow session.run() call, TensorFlow v2 applications run eagerly. Tensors that are created within the eager execution scope, are called eager tensors, and can be accessed freely. To improve your runtime performance you can configure functions to run in graph mode by applying the tf.function qualifier to them. This is the recommended (most performant) way to configure your training step when performing training, and is what happens automatically if you rely on the high level model.fit() training API. This means that, unless you program your training step to run in (the slower) eager execution mode, all of the tensors that you defined as part of your model, will be graph (non-eager) tensors. This includes intermediate layer inputs and outputs, and intermediate tensors in your loss function. The exceptions are tensors that are defined as outputs of the tf.function, which will be eager tensors. As mentioned above, the tf2 tf.summary ops will not work on graph tensors. The TensorFlow recommendation is to debug in eager execution mode, and to perform training in graph mode. Since the tf.summaries are required for monitoring tensors, specifically during the training process, we need a solution for extracting the values of these graph tensors.
In tf1, the underlying mechanism for extracting the values of graph tensors was the tf.session object. We would provide the session.run() function with a list of graph operations and input values, and receive as output the values of the corresponding tensors. In tf2, the sessions have been replaced by functions, specifically tf.funcions when running in graph mode. Here is the change as demonstrated in code by the TensorFlow documentation.
# TensorFlow 1.Xoutputs = session.run(f(placeholder), feed_dict={placeholder: input})# TensorFlow 2.0outputs = f(input)
One useful property of the session.run() method was that we had quite a bit of freedom in determining the list of input ops, and thus the list of collecting tensor values. This was particularly useful for extracting summaries. At every, predetermined summary step, we could simply expand the list of input ops to include the tensors of interest. The way to do this when using tf.functions, in tf2, is not as straightforward. Since the output of a tf.function is fixed, we would need to be able to define multiple tf.functions with varying output definitions, and toggle between the tf.functions based on the training step. Or, we could just use a single tf.function that outputs the superset of all tensors of interest. But this might come at a considerable performance cost.
The main goal of this post is to propose a solution for extracting graph tensors that is based on defining a custom tf.keras layer. But before we get into that, let’s review a couple of alternative solutions.
One, relatively easy, way to solve this is to simply disable the eager execution by calling tf.compat.v1.disable_eager_execution at the beginning of your script. As stated in the documentation, this function is intended for projects for which the migration from tf1 to tf2 proves difficult. When this function is used, the training loop essentially falls back to the legacy, tf1, training loop. In particular, this means that all the voodoo we described above for extracting graph tensors in tf.keras v1, can be carried over to tf2.
The feeling on our team was that we did not go to all the trouble of updating our code to tf2, only to fall back to using a legacy, tf1 version, training sequence. Our working assumption is that newer is better when it comes to TensorFlow versions, and that staying up do date with the latest tf version, will ensure that we are benefiting from the most up to date enhancements and optimizations. Not to mention that there are a number of features, such as tf profiling and custom training steps, that won’t work in the legacy mode.
I think it goes without saying that this option is ill-advised.
TensorFlow provides support for running a fully customized training loop (instead of model.fit()), as well as APIs for customizing just the train_step of model.fit() as described here. Here we refer to the second mode of customization, although some of the conclusions are relevant to the first as well.
It is very tempting to try to take advantage of the relative freedom that customization provides in order to support the capturing of graph tensors. The thing is, that even when using a custom training step, the advised way to do so, is such that it is wrapped by a tf.function qualifier. Of course, this makes all of the tensors part of the tf.Graph and thus inaccessible.
However, using a custom training step, does grant us some freedom in defining the tensors that are output from the graph, and thus accessible. For example, we can extend the list of model outputs to include outputs of layers that we wish to record. Or, we can define our loss function such that in addition to calculating and returning the loss, it also returns tensors that we would like to record, either in the form of images or histograms.
In the simplified code block below, we define a customized training step, such that it collects the model outputs, and the tensors returned by the loss function, and stores references to them in the extended Model class. These tensors are eager tensors, that can be freely referenced in other locations of the code. For example, we could define a custom keras callback that, at fixed intervals, writes these tensors to an event file, as histograms or images.
class CustomModel(keras.Model): @tf.function def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass loss, histograms, images = self.compiled_loss(y, y_pred) # Compute gradients train_vars = self.trainable_variables gradients = tape.gradient(loss, train_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, train_vars)) return y_pred, loss, histograms, images def make_train_function(self): if self.train_function is not None: return self.train_function def train_function(iterator): data = next(iterator) # store references to the model outputs, loss images # and loss histograms so that these can be recorded # to TensorBoard self.outputs, loss, self.histograms, self.images = self.train_step(data) return {'loss': loss} self.train_function = train_function return self.train_function
You may have picked up on the built-in inefficiency of this proposal. In most cases, we want to post summaries at specific training step intervals, certainly not at every step. However, we have redefined our model such that the training step outputs the tensors of interest at every step. If we were to define the set of prediction tensors that we are interested in at every step as A, and the superset that includes the summary tensors as B, then we have expanded our tf.function to output B. This can create a significant overhead, in particular, if we have many tensors of interest. Ideally, we would want to output these tensors only at the training steps at which they will be recorded. Ideally, we would want to define two tf.functions, one that outputs A and one that outputs B, and use them interchangeably. However, as of the time of this writing, I have not discovered an elegant way to do this.
The solution we propose is based on the observations that layer weights, including non-trainable weights, as described here, are eager tensors. Thus, in order to store the value of a given graph tensor, all we need to do is assign it to a “non-trainable” weight. Let’s start by demonstrating how this can be done in order to record the value of the output of an activation layer. In the block of code below, we have created a custom tf.keras layer that extends the standard tf.keras Activation with a layer that includes a non-trainable weight, called record_tensor. The call function is enhanced, such that on every step the record_tensor field is updated with the value of the current activation result. Since it is an eager tensor, record_tensor can be read outside of the training loop, and, in particular, recorded to TensorBoard.
from tensorflow.keras.layers import Activationclass ActivationRecorder(Activation): def __init__(self, shape, dtype, **kwargs): self.shape = shape self.record_tensor = tf.Variable( shape=shape, # initialize with batch size 1 since batch_size is # unknown, and set validate_shape=False initial_value=tf.zeros(shape=[1]+shape[1:], dtype=dtype), validate_shape=False, dtype=dtype, trainable=False) super(ActivationRecorder, self).__init__(dtype=dtype, **kwargs)def capture(self,activation): self.record_tensor.assign(activation)def call(self, inputs): output = super(ActivationRecorder, self).call(inputs) self.capture(output) return outputdef get_config(self): config = super(ActivationRecorder, self).get_config() config.update({"shape": self.shape}) return config# when building the graph maintain a reference to the# ActivationRecorder layersactivation_layer = ActivationRecorder(shape=activation_input.shape, dtype=activation_input.dtype, activation='relu')activation_output = activation_layer(activation_input)... #build rest graph# train the model (model.fit())# access recorded activation as needed:# Create a file writer for the log directory.file_writer = tf.summary.create_file_writer(logdir)with file_writer.as_default(): tf.summary.histogram("activation", activation_layer.record_tensor, step=step)
We have demonstrated the tensor capturing method on an activation layer, but we could have just as easily extended just about any keras layer and added a non-trainable tensor capturing variable. (One exception appears to be the keras InputLayer. It seems that this layer is handled differently, and that the “call” function is not called for every instance and every version of TensorFlow. In order to capture graph inputs, consider using a dedicated capturing layer, as we describe below.)
An alternative solution, is to define a general purpose tensor capturing layer as described in the next section.
To support the general case of capturing a graph tensor, we can define a general purpose tensor capture layer. This layer is defined as a pass through for the input, where all it does is store the current value to its internal non-trainable weight variable. This can be used to capture tensors at any stage in the graph, including layer inputs and outputs, and tensors in the loss function. Additionally, it can be used to capture tensors in the input pipeline, which was not covered by the previous solutions.
class SummaryCaptureLayer(Layer): def __init__(self, shape, dtype, **kwargs): self.shape = shape self.record_tensor = tf.Variable( shape=shape, # initialize with batch size 1 since batch_size # is unknown, nnd set validate_shape=False initial_value=tf.zeros(shape=[1]+shape[1:], dtype=dtype), validate_shape=False, dtype=dtype, trainable=False) super(SummaryCaptureLayer, self).__init__(dtype=dtype, **kwargs) def capture(self,inputs): self.record_tensor.assign(inputs) def call(self, inputs, **kwargs): self.capture(inputs) return inputs def get_config(self): config = super(SummaryCaptureLayer, self).get_config() config.update({"shape": self.shape}) return config
The complete solution requires storing a reference to the created layer and then accessing the record_tensor field, as needed, as shown in the previous example.
One detail that you may have noticed, in both examples, is that in the definition of the non-trainable tf.Variable, we used an arbitrary batch_size (of 1) in the initialization value, and set validate_shape to False. This is because, while the initial value requires a well defined shape (it can’t include None in any of the dimensions), at the time of model creation, we don’t always know what the batch_size will be. (For non-input layers, this also enables the use of JSON model configuration without fixing the batch size.)
In this post we have chosen to call our custom layer a SummaryCaptureLayer since the usage we have demonstrated has been recording tensor summaries to TensorBoard. But it would have been more appropriate to call the custom layer by the name TensorCaptureLayer, since all we are actually doing is capturing the tensor. Capturing tensors can support additional needs such as debugging.
In a previous post, I expanded on some tools and techniques for debugging a broken training session. The custom layer that we described can be used as an additional debugging tool. Suppose you suspect that the root cause of your bug is a problem with one, or more, particular tensors, either in the input pipeline, the loss function, or one of your layers. By feeding the suspect tensors into the Custom Summary Layer, you can track the value of the tensors at each iteration, or more realistically, dump the tensor values on the iteration that causes the training process to fail. It is clear to see how, compared to other debugging options, this kind of debugging scheme, coupled with the proposal I shared for debugging in the previous post, could save considerable time in solving the types of monster bugs I describe in the post.
Naturally, adding custom summary layers to the model, however thin they are, will incur a performance penalty. Since the performance penalty will depend directly on the model architecture, the number of summary layers that are inserted, and the frequency at which the tensors are written to the event file, it should be evaluated on a case by case basis. However, to provide some measure of comparison, we will provide the results of a simple case study, in which we capture 49 arbitrary tensors of a deep neural network, using the custom summary capture callback. The measurements below are averaged across epochs of 100 steps during which the summaries were captured, but not written (so as to remove the overhead of the summary writer).
The relatively high overhead of outputting all of the tensors of interest using a custom train step is apparent. We also see that there is a little overhead to the use of custom summary layers. While collecting tensors using the non-eager execution mode is slightly faster than using custom summary layers, I do not believe that this advantage is great enough to warrant falling back to a legacy training scheme.
Again, these results provide little information about the performance overhead of other use cases. Each model should be evaluated independently before settling on the number and types of tensors to collect, and the frequency at which they should be collected.
In this post I have proposed a way to collect summaries of graph tensors in TensorFlow 2. The solution is not perfect, but in the absence of a better one, I think it is simple and elegant. If you know of a better solution, or if TensorFlow provides a built in solution, I would love to hear about it.
|
[
{
"code": null,
"e": 596,
"s": 172,
"text": "In previous posts, I have told you about how my team at Mobileye, (officially known as Mobileye, an Intel Company), has tackled some of the challenges that came up, while using TensorFlow to train deep neural networks. In particular, I have covered topics such as performance profiling, and debugging. This post addresses an additional component of training machine learning models, that of monitoring the learning process."
},
{
"code": null,
"e": 904,
"s": 596,
"text": "Monitoring the learning process is an important, and often time-consuming, part of DNN training, during which we track a variety of tensors, metrics and statistics, in order to understand how our training is progressing, and figure out what improvements to make to model architecture and/or hyperparameters."
},
{
"code": null,
"e": 1496,
"s": 904,
"text": "One of the most popular ways of doing this when training in TensorFlow, is using TensorBoard. TensorBoard supports a variety of methods for tracking and debugging the training process. On our team, we rely heavily on TensorBoard. We track losses, generate gradient histograms, and measure activation outputs. We log metrics, display confusion matrices, and generate visual images from the output data. Sometimes we use it debug intermediate operations performed by the loss function, or to measure the distribution of weights on a specific layer in the graph. We use TensorBoard extensively."
},
{
"code": null,
"e": 2205,
"s": 1496,
"text": "The way to use TensorBoard is by inserting “summary” commands into the training code using the tf.summary module. In version 2, TensorFlow made significant revisions to the training flow, and, in particular, to the tf summary mechanism. While this revision simplified some of the straightforward usages of tf.summary, some of the more advanced usages are not immediately obvious. For example, it is not at all clear (to me, at least), how TensorFlow intended for me to be able to log graph (non-eager) tensors, such as the distribution of the output of a specific activation layer within my graph, or the value of an arbitrary tensor within my loss function. (If you know, please don’t hesitate to share :).)"
},
{
"code": null,
"e": 2580,
"s": 2205,
"text": "My intention, in this post, is to propose a solution for capturing summaries from graph tensors, that relies on the creation of a custom tf.keras.Layer. Along the way, I will provide a bit more insight into the problem, as well as some of the alternative solutions we considered. If you are eager to get straight to the custom summary capture layer, feel free to skip ahead."
},
{
"code": null,
"e": 2756,
"s": 2580,
"text": "As TensorFlow and TensorBoard continue to undergo changes and improvements, it is important to note that my story is based on trials that I ran using TensorFlow version 2.3.0."
},
{
"code": null,
"e": 2875,
"s": 2756,
"text": "The following brief history is partial, in the sense that it is incomplete, and that it is based on my own experience."
},
{
"code": null,
"e": 3885,
"s": 2875,
"text": "In version 1 of TensorFlow, we would freely scatter tf.summary ops on arbitrary tensors across our code, and would use the tf session.run() function to record the associated tensor values to event files, at predetermined intervals. As our use of TensorBoard evolved, we would also use it to record the results of general python calculations that we would make based on the graph output, such as image visualizations of model predictions overlaid on an input frame, or visualizations of the confusion matrix. Since summaries needed to be graph ops, we would do this by creating small auxiliary graphs that would define a summary op on a numpy array (such as an image). Later, we adopted the high level tf.estimator APIs, which included controls for setting the summary interval and handled the session.run calls on the summary ops for us. We also integrated the use of the estimator hooks, such as the tf.estimator.SummarySaverHook and other custom hooks, to support our wide variety of usages. Life was grand."
},
{
"code": null,
"e": 4590,
"s": 3885,
"text": "Along came tf.keras with its own unique blueprint for the training flow, and its own high level training API tf.keras.model.fit(). The model.fit() function did not include support for managing tf.summarys, requiring a bit more manual labor. But we quickly worked out how to enable all of our TensorBoard usages by creating custom tf.keras.callbacks, and directly configuring the execution function to collect the desired tensors, using all kinds of voodoo involving model._fit_function.fetches and model._fit_function.fetch_callbacks. No, it wasn’t pretty, but it worked. The tf.keras API also introduced a TensorBoard callback, which supported capturing a variety of popular training monitoring metrics."
},
{
"code": null,
"e": 5235,
"s": 4590,
"text": "Then came TensorFlow 2. Once again, the blueprint for the training flow changed, the use of the model._fit_function became obsolete, and the mechanism for recording tensors was revised. As described by TensorFlow, the new mechanism does have its advantages. Previously, recording tensors was a two step process. Now, a call to tf.summary would result in immediate recording of the tensor to the event file. In particular, this meant that the tf summary ops were no longer built into the TensorFlow computation graph. In addition, the tf.summary call could only be called on eager tensors (or raw numpy arrays). More on this in the next section."
},
{
"code": null,
"e": 5515,
"s": 5235,
"text": "While a full understanding of the changes that were introduced in TensorFlow 2 is beyond the scope of this post, I would like to touch on a few of the details that pertain to the topic of collecting summaries. To get the full picture, I refer you to the TensorFlow documentation."
},
{
"code": null,
"e": 6929,
"s": 5515,
"text": "While in tf1, the default execution mode is graph mode, a symbolic execution mode in which users define an abstract syntax tree and execute it using the TensorFlow session.run() call, TensorFlow v2 applications run eagerly. Tensors that are created within the eager execution scope, are called eager tensors, and can be accessed freely. To improve your runtime performance you can configure functions to run in graph mode by applying the tf.function qualifier to them. This is the recommended (most performant) way to configure your training step when performing training, and is what happens automatically if you rely on the high level model.fit() training API. This means that, unless you program your training step to run in (the slower) eager execution mode, all of the tensors that you defined as part of your model, will be graph (non-eager) tensors. This includes intermediate layer inputs and outputs, and intermediate tensors in your loss function. The exceptions are tensors that are defined as outputs of the tf.function, which will be eager tensors. As mentioned above, the tf2 tf.summary ops will not work on graph tensors. The TensorFlow recommendation is to debug in eager execution mode, and to perform training in graph mode. Since the tf.summaries are required for monitoring tensors, specifically during the training process, we need a solution for extracting the values of these graph tensors."
},
{
"code": null,
"e": 7372,
"s": 6929,
"text": "In tf1, the underlying mechanism for extracting the values of graph tensors was the tf.session object. We would provide the session.run() function with a list of graph operations and input values, and receive as output the values of the corresponding tensors. In tf2, the sessions have been replaced by functions, specifically tf.funcions when running in graph mode. Here is the change as demonstrated in code by the TensorFlow documentation."
},
{
"code": null,
"e": 7514,
"s": 7372,
"text": "# TensorFlow 1.Xoutputs = session.run(f(placeholder), feed_dict={placeholder: input})# TensorFlow 2.0outputs = f(input)"
},
{
"code": null,
"e": 8290,
"s": 7514,
"text": "One useful property of the session.run() method was that we had quite a bit of freedom in determining the list of input ops, and thus the list of collecting tensor values. This was particularly useful for extracting summaries. At every, predetermined summary step, we could simply expand the list of input ops to include the tensors of interest. The way to do this when using tf.functions, in tf2, is not as straightforward. Since the output of a tf.function is fixed, we would need to be able to define multiple tf.functions with varying output definitions, and toggle between the tf.functions based on the training step. Or, we could just use a single tf.function that outputs the superset of all tensors of interest. But this might come at a considerable performance cost."
},
{
"code": null,
"e": 8499,
"s": 8290,
"text": "The main goal of this post is to propose a solution for extracting graph tensors that is based on defining a custom tf.keras layer. But before we get into that, let’s review a couple of alternative solutions."
},
{
"code": null,
"e": 9032,
"s": 8499,
"text": "One, relatively easy, way to solve this is to simply disable the eager execution by calling tf.compat.v1.disable_eager_execution at the beginning of your script. As stated in the documentation, this function is intended for projects for which the migration from tf1 to tf2 proves difficult. When this function is used, the training loop essentially falls back to the legacy, tf1, training loop. In particular, this means that all the voodoo we described above for extracting graph tensors in tf.keras v1, can be carried over to tf2."
},
{
"code": null,
"e": 9565,
"s": 9032,
"text": "The feeling on our team was that we did not go to all the trouble of updating our code to tf2, only to fall back to using a legacy, tf1 version, training sequence. Our working assumption is that newer is better when it comes to TensorFlow versions, and that staying up do date with the latest tf version, will ensure that we are benefiting from the most up to date enhancements and optimizations. Not to mention that there are a number of features, such as tf profiling and custom training steps, that won’t work in the legacy mode."
},
{
"code": null,
"e": 9629,
"s": 9565,
"text": "I think it goes without saying that this option is ill-advised."
},
{
"code": null,
"e": 9933,
"s": 9629,
"text": "TensorFlow provides support for running a fully customized training loop (instead of model.fit()), as well as APIs for customizing just the train_step of model.fit() as described here. Here we refer to the second mode of customization, although some of the conclusions are relevant to the first as well."
},
{
"code": null,
"e": 10307,
"s": 9933,
"text": "It is very tempting to try to take advantage of the relative freedom that customization provides in order to support the capturing of graph tensors. The thing is, that even when using a custom training step, the advised way to do so, is such that it is wrapped by a tf.function qualifier. Of course, this makes all of the tensors part of the tf.Graph and thus inaccessible."
},
{
"code": null,
"e": 10751,
"s": 10307,
"text": "However, using a custom training step, does grant us some freedom in defining the tensors that are output from the graph, and thus accessible. For example, we can extend the list of model outputs to include outputs of layers that we wish to record. Or, we can define our loss function such that in addition to calculating and returning the loss, it also returns tensors that we would like to record, either in the form of images or histograms."
},
{
"code": null,
"e": 11210,
"s": 10751,
"text": "In the simplified code block below, we define a customized training step, such that it collects the model outputs, and the tensors returned by the loss function, and stores references to them in the extended Model class. These tensors are eager tensors, that can be freely referenced in other locations of the code. For example, we could define a custom keras callback that, at fixed intervals, writes these tensors to an event file, as histograms or images."
},
{
"code": null,
"e": 12315,
"s": 11210,
"text": "class CustomModel(keras.Model): @tf.function def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass loss, histograms, images = self.compiled_loss(y, y_pred) # Compute gradients train_vars = self.trainable_variables gradients = tape.gradient(loss, train_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, train_vars)) return y_pred, loss, histograms, images def make_train_function(self): if self.train_function is not None: return self.train_function def train_function(iterator): data = next(iterator) # store references to the model outputs, loss images # and loss histograms so that these can be recorded # to TensorBoard self.outputs, loss, self.histograms, self.images = self.train_step(data) return {'loss': loss} self.train_function = train_function return self.train_function"
},
{
"code": null,
"e": 13221,
"s": 12315,
"text": "You may have picked up on the built-in inefficiency of this proposal. In most cases, we want to post summaries at specific training step intervals, certainly not at every step. However, we have redefined our model such that the training step outputs the tensors of interest at every step. If we were to define the set of prediction tensors that we are interested in at every step as A, and the superset that includes the summary tensors as B, then we have expanded our tf.function to output B. This can create a significant overhead, in particular, if we have many tensors of interest. Ideally, we would want to output these tensors only at the training steps at which they will be recorded. Ideally, we would want to define two tf.functions, one that outputs A and one that outputs B, and use them interchangeably. However, as of the time of this writing, I have not discovered an elegant way to do this."
},
{
"code": null,
"e": 14057,
"s": 13221,
"text": "The solution we propose is based on the observations that layer weights, including non-trainable weights, as described here, are eager tensors. Thus, in order to store the value of a given graph tensor, all we need to do is assign it to a “non-trainable” weight. Let’s start by demonstrating how this can be done in order to record the value of the output of an activation layer. In the block of code below, we have created a custom tf.keras layer that extends the standard tf.keras Activation with a layer that includes a non-trainable weight, called record_tensor. The call function is enhanced, such that on every step the record_tensor field is updated with the value of the current activation result. Since it is an eager tensor, record_tensor can be read outside of the training loop, and, in particular, recorded to TensorBoard."
},
{
"code": null,
"e": 15743,
"s": 14057,
"text": "from tensorflow.keras.layers import Activationclass ActivationRecorder(Activation): def __init__(self, shape, dtype, **kwargs): self.shape = shape self.record_tensor = tf.Variable( shape=shape, # initialize with batch size 1 since batch_size is # unknown, and set validate_shape=False initial_value=tf.zeros(shape=[1]+shape[1:], dtype=dtype), validate_shape=False, dtype=dtype, trainable=False) super(ActivationRecorder, self).__init__(dtype=dtype, **kwargs)def capture(self,activation): self.record_tensor.assign(activation)def call(self, inputs): output = super(ActivationRecorder, self).call(inputs) self.capture(output) return outputdef get_config(self): config = super(ActivationRecorder, self).get_config() config.update({\"shape\": self.shape}) return config# when building the graph maintain a reference to the# ActivationRecorder layersactivation_layer = ActivationRecorder(shape=activation_input.shape, dtype=activation_input.dtype, activation='relu')activation_output = activation_layer(activation_input)... #build rest graph# train the model (model.fit())# access recorded activation as needed:# Create a file writer for the log directory.file_writer = tf.summary.create_file_writer(logdir)with file_writer.as_default(): tf.summary.histogram(\"activation\", activation_layer.record_tensor, step=step)"
},
{
"code": null,
"e": 16234,
"s": 15743,
"text": "We have demonstrated the tensor capturing method on an activation layer, but we could have just as easily extended just about any keras layer and added a non-trainable tensor capturing variable. (One exception appears to be the keras InputLayer. It seems that this layer is handled differently, and that the “call” function is not called for every instance and every version of TensorFlow. In order to capture graph inputs, consider using a dedicated capturing layer, as we describe below.)"
},
{
"code": null,
"e": 16347,
"s": 16234,
"text": "An alternative solution, is to define a general purpose tensor capturing layer as described in the next section."
},
{
"code": null,
"e": 16858,
"s": 16347,
"text": "To support the general case of capturing a graph tensor, we can define a general purpose tensor capture layer. This layer is defined as a pass through for the input, where all it does is store the current value to its internal non-trainable weight variable. This can be used to capture tensors at any stage in the graph, including layer inputs and outputs, and tensors in the loss function. Additionally, it can be used to capture tensors in the input pipeline, which was not covered by the previous solutions."
},
{
"code": null,
"e": 17762,
"s": 16858,
"text": "class SummaryCaptureLayer(Layer): def __init__(self, shape, dtype, **kwargs): self.shape = shape self.record_tensor = tf.Variable( shape=shape, # initialize with batch size 1 since batch_size # is unknown, nnd set validate_shape=False initial_value=tf.zeros(shape=[1]+shape[1:], dtype=dtype), validate_shape=False, dtype=dtype, trainable=False) super(SummaryCaptureLayer, self).__init__(dtype=dtype, **kwargs) def capture(self,inputs): self.record_tensor.assign(inputs) def call(self, inputs, **kwargs): self.capture(inputs) return inputs def get_config(self): config = super(SummaryCaptureLayer, self).get_config() config.update({\"shape\": self.shape}) return config"
},
{
"code": null,
"e": 17923,
"s": 17762,
"text": "The complete solution requires storing a reference to the created layer and then accessing the record_tensor field, as needed, as shown in the previous example."
},
{
"code": null,
"e": 18451,
"s": 17923,
"text": "One detail that you may have noticed, in both examples, is that in the definition of the non-trainable tf.Variable, we used an arbitrary batch_size (of 1) in the initialization value, and set validate_shape to False. This is because, while the initial value requires a well defined shape (it can’t include None in any of the dimensions), at the time of model creation, we don’t always know what the batch_size will be. (For non-input layers, this also enables the use of JSON model configuration without fixing the batch size.)"
},
{
"code": null,
"e": 18835,
"s": 18451,
"text": "In this post we have chosen to call our custom layer a SummaryCaptureLayer since the usage we have demonstrated has been recording tensor summaries to TensorBoard. But it would have been more appropriate to call the custom layer by the name TensorCaptureLayer, since all we are actually doing is capturing the tensor. Capturing tensors can support additional needs such as debugging."
},
{
"code": null,
"e": 19670,
"s": 18835,
"text": "In a previous post, I expanded on some tools and techniques for debugging a broken training session. The custom layer that we described can be used as an additional debugging tool. Suppose you suspect that the root cause of your bug is a problem with one, or more, particular tensors, either in the input pipeline, the loss function, or one of your layers. By feeding the suspect tensors into the Custom Summary Layer, you can track the value of the tensors at each iteration, or more realistically, dump the tensor values on the iteration that causes the training process to fail. It is clear to see how, compared to other debugging options, this kind of debugging scheme, coupled with the proposal I shared for debugging in the previous post, could save considerable time in solving the types of monster bugs I describe in the post."
},
{
"code": null,
"e": 20410,
"s": 19670,
"text": "Naturally, adding custom summary layers to the model, however thin they are, will incur a performance penalty. Since the performance penalty will depend directly on the model architecture, the number of summary layers that are inserted, and the frequency at which the tensors are written to the event file, it should be evaluated on a case by case basis. However, to provide some measure of comparison, we will provide the results of a simple case study, in which we capture 49 arbitrary tensors of a deep neural network, using the custom summary capture callback. The measurements below are averaged across epochs of 100 steps during which the summaries were captured, but not written (so as to remove the overhead of the summary writer)."
},
{
"code": null,
"e": 20823,
"s": 20410,
"text": "The relatively high overhead of outputting all of the tensors of interest using a custom train step is apparent. We also see that there is a little overhead to the use of custom summary layers. While collecting tensors using the non-eager execution mode is slightly faster than using custom summary layers, I do not believe that this advantage is great enough to warrant falling back to a legacy training scheme."
},
{
"code": null,
"e": 21083,
"s": 20823,
"text": "Again, these results provide little information about the performance overhead of other use cases. Each model should be evaluated independently before settling on the number and types of tensors to collect, and the frequency at which they should be collected."
}
] |
Cleaning & Preprocessing Text Data by Building NLP Pipeline | by Kajal Yadav | Towards Data Science
|
For a while, I was dealing with textual data and I realize in today’s world, It is necessary to know how natural language processing works and what are the main steps to involve in order to get insights out of textual data.As we all know, there are a lot of statistics and maths that we can apply in order to get insights out of numerical data.But when it comes to the tedious form of textual data, we lack it in many places.
What is NLP text preprocessing?
NLP Text preprocessing is a method to clean the text in order to make it ready to feed to models. Noise in the text comes in varied forms like emojis, punctuations, different cases. All these noises are of no use to machines and hence need to clean it.
Why is NLP text preprocessing important?
Importance :
Properly cleaned data will help us to do good text analysis and help us in making accurate decisions for our business problems. Hence text preprocessing for machine learning is an important step.
Before I indulge you guys in the main steps involved in NLP text pre-processing, I would like to say you can add or remove few steps on the basis of the data that you have and its requirement.
In this tutorial, I barely gonna give you a definition for any step as there are plenty on the internet. Instead, I will gonna explain why you should be applying specific steps, how to do text preprocessing using python, what I understood in each step, and what was the outcome of my dataset.
Okay!! enough talking. Let us dive into the code now. 😄
Libraries & text preprocessing tools Required :
# Importing Libraries import unidecode import pandas as pd import re import time import nltk from nltk.corpus import stopwords nltk.download('stopwords') from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from autocorrect import Speller from bs4 import BeautifulSoup from nltk.corpus import stopwords from nltk import word_tokenize import string
Read the Dataset :
# Read Dataset Df = pd.read_csv('New Task.csv', encoding = 'latin-1')# Show DatasetDf.head()
These are some text preprocessing steps that you can add or remove as per the dataset you have:
You may encounter lots of new lines for no reason in your textual dataset and tabs as well. So when you scrape data, those newlines and tabs that are required on the website for structured content are not required in your dataset and also get converted into useless characters like \n, \t. So, I have written a function that will delete all such nonsense.
When you scrape data, you may end up seeing HTML tags in the text of your dataset if you haven’t deal with it already while scraping. So, there is a need to deal with those tags later on. In this function, I am removing everything that matches HTML tags in my text.
This step will remove everything which is similar to hyperlinks of any type. I have added this function here as I have dealt with it on my dataset.
A single line function can be performed to remove extra whitespaces as mentioned below. This step is crucial before performing further NLP tasks.
What are the main NLP text preprocessing steps?
The below list of text preprocessing steps is really important and I have written all these steps in a sequence how they should be.
This is a crucial step to convert all characters like accented characters into machine-understandable language. So that further steps can be implemented easily. Accented characters are characters like â, î, or ô which have diacritics above the characters.
This is the next step in the series which is really important as case, CASE is two different words for the machine. So, you should be converting the case of the text in either lowercase or uppercase to proceed further.
This step is important as there might be scenarios where characters are repeating more than necessary which can’t be detected by a spell checker later on. Therefore, there is a need to deal with such a scenario beforehand before applying the spell checker function. There is another scenario that I encounter while working, there can be repeating punctuations as well. So there is a need to encounter them as well.
When we are very exciting, we do overwrite things that overwhelm readers.
Example:- Cheeeeeerrrrrrss !!!!!!
The explanation for using some symbols in the above regex expression
\1 → is equivalent to re.search(...). group(1). It refers to the first capturing group. \1 matches the exact same text that was matched by the first capturing group.
{1,} → It means we are matching for repetition that occurs more than one time.
DOTALL -> It matches the newline character as well unlike the dot operator which matches everything in the given text except the newline character.
sub() → This function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The substring to replace. The sub-string to replace with.
r’\1\1' → It limits all the repetition to two characters.
r’\1' → Limits all the repetition to only one character.
{2,} → It means to match for repetition that occurs more than two times
In order to remove Stop words in the next step, It is crucial that you deal with contractions first. Contractions are nothing but shorthand forms for words like, Do not, would not, It is. Contractions are anything similar to these examples don’t, wouldn’t, It’s.
In this step, We will go to learn how to remove special characters, why to remove them, and what special characters you should be keeping.
So, I have written a function that will remove a set of specified special characters and will gonna keep some important punctuations like (,.?!) excluding brackets. Special characters should be removed as when we gonna tokenized the text, later on, the punctuations don’t occur with more weightage.
To Remove numbers from the text :
All you need is to modify the given regex to
Formatted_Text = re.sub(r"[^a-zA-Z:$-,%.?!]+", ' ', text)
Just exclude the 0–9 range so as to remove all representation of numbers from the text. I didn’t perform this particular step on my dataset as the numbers are really important in my case to consider.
Punctuations that I am considering are Important as per my Dataset as I have to perform text summarization later on.
,.?! → These are some frequent punctuations that occur a lot and needed to be preserved to understand the context of the text.
: → This one is also frequent as per the Dataset. It is important to keep because it is giving sense whenever there is an occurrence of time like 9:05 p.m.
% → This one is also frequently used in many articles and telling more precisely about the data, facts & figures.
$ → This one is used in many articles where prices are considered. So, omitting this symbol will not give much sense about those prices that are left as just some numbers only.
Stopwords should be removed if you are performing tokenization, text summarization, text classification, or any similar task. As without stop-words, you can understand the context of the textual data presented to you. There is a need to remove them so as to reduce their weightage.
You should be considering this step of removing stop words since It didn’t work well with my further analysis. As I found on generating n-Grams, With stopwords files tend to give more reliable results than without stopwords files.
You should be very careful while attempting this one step. As this function may change the true meaning of the word. So you have to be very careful and try to see how things unfold on applying this function. If you are working on some industry-specific dataset, then you may need to consider relating the dictionary which tells this function explicitly to keep those specific words as it is.
In this step, I will gonna talk about two things precisely, Lemmatization and stemming.
People got confused with these two techniques like which one is efficient and what to use. So, Let me tell you about my experience and what did I prefer and why?
So, Both techniques actually trim the word to its root form like Planning will be trimmed to plan but Stemming won’t work in the case of the word “Better” whereas if you apply lemmatization, It will transform the word to its root form i.e., “good”. This is a major difference that Lemmatization works efficiently and I have used it only during my work.
Although I have written this function but on further analysis, I found that it didn’t perform well instead it was creating noise. So, On bit analysis for a few of the tokens, I realized it’s better to not apply lemmatization.
For example:- There was the word “Feed” which is frequently occurring all over the articles and which is really important as well. But on lemmatizing, “Feed” → reduced to → “Fee”. You see how it changed its entire meaning.
The data cleaning step entirely depends on the type of Dataset. Depending on the data, more steps can be include. It is a must to remove extra spaces so as to reduce file size.
These are some important steps that I have considered always while doing pre-processing of the textual data. You may take advantage of the code shared if you have to deal with the textual data as well or also don’t forget to let me know if you have tried something else to clean textual data. These steps are specific to the dataset that I have used, so feel free to add or remove it at your convenience.
You can also visit the complete Github repository which contains all the steps in a sequence of implementation with a brief explanation.
github.com
Cheers !! You have made it to the end. 😉
You can reach me via the following:
Subscribe to my YouTube channel for video content coming soon hereFollow me on MediumConnect and reach me on LinkedInFollow me on my blogging journey:- https://kajalyadav.com/Become a member:- https://techykajal.medium.com/membership
Subscribe to my YouTube channel for video content coming soon here
Follow me on Medium
Connect and reach me on LinkedIn
Follow me on my blogging journey:- https://kajalyadav.com/
Become a member:- https://techykajal.medium.com/membership
Check out my other blogs as well:
|
[
{
"code": null,
"e": 598,
"s": 172,
"text": "For a while, I was dealing with textual data and I realize in today’s world, It is necessary to know how natural language processing works and what are the main steps to involve in order to get insights out of textual data.As we all know, there are a lot of statistics and maths that we can apply in order to get insights out of numerical data.But when it comes to the tedious form of textual data, we lack it in many places."
},
{
"code": null,
"e": 630,
"s": 598,
"text": "What is NLP text preprocessing?"
},
{
"code": null,
"e": 883,
"s": 630,
"text": "NLP Text preprocessing is a method to clean the text in order to make it ready to feed to models. Noise in the text comes in varied forms like emojis, punctuations, different cases. All these noises are of no use to machines and hence need to clean it."
},
{
"code": null,
"e": 924,
"s": 883,
"text": "Why is NLP text preprocessing important?"
},
{
"code": null,
"e": 937,
"s": 924,
"text": "Importance :"
},
{
"code": null,
"e": 1133,
"s": 937,
"text": "Properly cleaned data will help us to do good text analysis and help us in making accurate decisions for our business problems. Hence text preprocessing for machine learning is an important step."
},
{
"code": null,
"e": 1326,
"s": 1133,
"text": "Before I indulge you guys in the main steps involved in NLP text pre-processing, I would like to say you can add or remove few steps on the basis of the data that you have and its requirement."
},
{
"code": null,
"e": 1619,
"s": 1326,
"text": "In this tutorial, I barely gonna give you a definition for any step as there are plenty on the internet. Instead, I will gonna explain why you should be applying specific steps, how to do text preprocessing using python, what I understood in each step, and what was the outcome of my dataset."
},
{
"code": null,
"e": 1675,
"s": 1619,
"text": "Okay!! enough talking. Let us dive into the code now. 😄"
},
{
"code": null,
"e": 1723,
"s": 1675,
"text": "Libraries & text preprocessing tools Required :"
},
{
"code": null,
"e": 2099,
"s": 1723,
"text": "# Importing Libraries import unidecode import pandas as pd import re import time import nltk from nltk.corpus import stopwords nltk.download('stopwords') from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from autocorrect import Speller from bs4 import BeautifulSoup from nltk.corpus import stopwords from nltk import word_tokenize import string "
},
{
"code": null,
"e": 2118,
"s": 2099,
"text": "Read the Dataset :"
},
{
"code": null,
"e": 2211,
"s": 2118,
"text": "# Read Dataset Df = pd.read_csv('New Task.csv', encoding = 'latin-1')# Show DatasetDf.head()"
},
{
"code": null,
"e": 2307,
"s": 2211,
"text": "These are some text preprocessing steps that you can add or remove as per the dataset you have:"
},
{
"code": null,
"e": 2663,
"s": 2307,
"text": "You may encounter lots of new lines for no reason in your textual dataset and tabs as well. So when you scrape data, those newlines and tabs that are required on the website for structured content are not required in your dataset and also get converted into useless characters like \\n, \\t. So, I have written a function that will delete all such nonsense."
},
{
"code": null,
"e": 2929,
"s": 2663,
"text": "When you scrape data, you may end up seeing HTML tags in the text of your dataset if you haven’t deal with it already while scraping. So, there is a need to deal with those tags later on. In this function, I am removing everything that matches HTML tags in my text."
},
{
"code": null,
"e": 3077,
"s": 2929,
"text": "This step will remove everything which is similar to hyperlinks of any type. I have added this function here as I have dealt with it on my dataset."
},
{
"code": null,
"e": 3223,
"s": 3077,
"text": "A single line function can be performed to remove extra whitespaces as mentioned below. This step is crucial before performing further NLP tasks."
},
{
"code": null,
"e": 3271,
"s": 3223,
"text": "What are the main NLP text preprocessing steps?"
},
{
"code": null,
"e": 3403,
"s": 3271,
"text": "The below list of text preprocessing steps is really important and I have written all these steps in a sequence how they should be."
},
{
"code": null,
"e": 3662,
"s": 3403,
"text": "This is a crucial step to convert all characters like accented characters into machine-understandable language. So that further steps can be implemented easily. Accented characters are characters like â, î, or ô which have diacritics above the characters."
},
{
"code": null,
"e": 3881,
"s": 3662,
"text": "This is the next step in the series which is really important as case, CASE is two different words for the machine. So, you should be converting the case of the text in either lowercase or uppercase to proceed further."
},
{
"code": null,
"e": 4296,
"s": 3881,
"text": "This step is important as there might be scenarios where characters are repeating more than necessary which can’t be detected by a spell checker later on. Therefore, there is a need to deal with such a scenario beforehand before applying the spell checker function. There is another scenario that I encounter while working, there can be repeating punctuations as well. So there is a need to encounter them as well."
},
{
"code": null,
"e": 4370,
"s": 4296,
"text": "When we are very exciting, we do overwrite things that overwhelm readers."
},
{
"code": null,
"e": 4404,
"s": 4370,
"text": "Example:- Cheeeeeerrrrrrss !!!!!!"
},
{
"code": null,
"e": 4473,
"s": 4404,
"text": "The explanation for using some symbols in the above regex expression"
},
{
"code": null,
"e": 4639,
"s": 4473,
"text": "\\1 → is equivalent to re.search(...). group(1). It refers to the first capturing group. \\1 matches the exact same text that was matched by the first capturing group."
},
{
"code": null,
"e": 4718,
"s": 4639,
"text": "{1,} → It means we are matching for repetition that occurs more than one time."
},
{
"code": null,
"e": 4866,
"s": 4718,
"text": "DOTALL -> It matches the newline character as well unlike the dot operator which matches everything in the given text except the newline character."
},
{
"code": null,
"e": 5073,
"s": 4866,
"text": "sub() → This function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The substring to replace. The sub-string to replace with."
},
{
"code": null,
"e": 5131,
"s": 5073,
"text": "r’\\1\\1' → It limits all the repetition to two characters."
},
{
"code": null,
"e": 5188,
"s": 5131,
"text": "r’\\1' → Limits all the repetition to only one character."
},
{
"code": null,
"e": 5260,
"s": 5188,
"text": "{2,} → It means to match for repetition that occurs more than two times"
},
{
"code": null,
"e": 5523,
"s": 5260,
"text": "In order to remove Stop words in the next step, It is crucial that you deal with contractions first. Contractions are nothing but shorthand forms for words like, Do not, would not, It is. Contractions are anything similar to these examples don’t, wouldn’t, It’s."
},
{
"code": null,
"e": 5662,
"s": 5523,
"text": "In this step, We will go to learn how to remove special characters, why to remove them, and what special characters you should be keeping."
},
{
"code": null,
"e": 5961,
"s": 5662,
"text": "So, I have written a function that will remove a set of specified special characters and will gonna keep some important punctuations like (,.?!) excluding brackets. Special characters should be removed as when we gonna tokenized the text, later on, the punctuations don’t occur with more weightage."
},
{
"code": null,
"e": 5995,
"s": 5961,
"text": "To Remove numbers from the text :"
},
{
"code": null,
"e": 6040,
"s": 5995,
"text": "All you need is to modify the given regex to"
},
{
"code": null,
"e": 6098,
"s": 6040,
"text": "Formatted_Text = re.sub(r\"[^a-zA-Z:$-,%.?!]+\", ' ', text)"
},
{
"code": null,
"e": 6298,
"s": 6098,
"text": "Just exclude the 0–9 range so as to remove all representation of numbers from the text. I didn’t perform this particular step on my dataset as the numbers are really important in my case to consider."
},
{
"code": null,
"e": 6415,
"s": 6298,
"text": "Punctuations that I am considering are Important as per my Dataset as I have to perform text summarization later on."
},
{
"code": null,
"e": 6542,
"s": 6415,
"text": ",.?! → These are some frequent punctuations that occur a lot and needed to be preserved to understand the context of the text."
},
{
"code": null,
"e": 6698,
"s": 6542,
"text": ": → This one is also frequent as per the Dataset. It is important to keep because it is giving sense whenever there is an occurrence of time like 9:05 p.m."
},
{
"code": null,
"e": 6812,
"s": 6698,
"text": "% → This one is also frequently used in many articles and telling more precisely about the data, facts & figures."
},
{
"code": null,
"e": 6989,
"s": 6812,
"text": "$ → This one is used in many articles where prices are considered. So, omitting this symbol will not give much sense about those prices that are left as just some numbers only."
},
{
"code": null,
"e": 7271,
"s": 6989,
"text": "Stopwords should be removed if you are performing tokenization, text summarization, text classification, or any similar task. As without stop-words, you can understand the context of the textual data presented to you. There is a need to remove them so as to reduce their weightage."
},
{
"code": null,
"e": 7502,
"s": 7271,
"text": "You should be considering this step of removing stop words since It didn’t work well with my further analysis. As I found on generating n-Grams, With stopwords files tend to give more reliable results than without stopwords files."
},
{
"code": null,
"e": 7894,
"s": 7502,
"text": "You should be very careful while attempting this one step. As this function may change the true meaning of the word. So you have to be very careful and try to see how things unfold on applying this function. If you are working on some industry-specific dataset, then you may need to consider relating the dictionary which tells this function explicitly to keep those specific words as it is."
},
{
"code": null,
"e": 7982,
"s": 7894,
"text": "In this step, I will gonna talk about two things precisely, Lemmatization and stemming."
},
{
"code": null,
"e": 8144,
"s": 7982,
"text": "People got confused with these two techniques like which one is efficient and what to use. So, Let me tell you about my experience and what did I prefer and why?"
},
{
"code": null,
"e": 8497,
"s": 8144,
"text": "So, Both techniques actually trim the word to its root form like Planning will be trimmed to plan but Stemming won’t work in the case of the word “Better” whereas if you apply lemmatization, It will transform the word to its root form i.e., “good”. This is a major difference that Lemmatization works efficiently and I have used it only during my work."
},
{
"code": null,
"e": 8723,
"s": 8497,
"text": "Although I have written this function but on further analysis, I found that it didn’t perform well instead it was creating noise. So, On bit analysis for a few of the tokens, I realized it’s better to not apply lemmatization."
},
{
"code": null,
"e": 8946,
"s": 8723,
"text": "For example:- There was the word “Feed” which is frequently occurring all over the articles and which is really important as well. But on lemmatizing, “Feed” → reduced to → “Fee”. You see how it changed its entire meaning."
},
{
"code": null,
"e": 9123,
"s": 8946,
"text": "The data cleaning step entirely depends on the type of Dataset. Depending on the data, more steps can be include. It is a must to remove extra spaces so as to reduce file size."
},
{
"code": null,
"e": 9528,
"s": 9123,
"text": "These are some important steps that I have considered always while doing pre-processing of the textual data. You may take advantage of the code shared if you have to deal with the textual data as well or also don’t forget to let me know if you have tried something else to clean textual data. These steps are specific to the dataset that I have used, so feel free to add or remove it at your convenience."
},
{
"code": null,
"e": 9665,
"s": 9528,
"text": "You can also visit the complete Github repository which contains all the steps in a sequence of implementation with a brief explanation."
},
{
"code": null,
"e": 9676,
"s": 9665,
"text": "github.com"
},
{
"code": null,
"e": 9717,
"s": 9676,
"text": "Cheers !! You have made it to the end. 😉"
},
{
"code": null,
"e": 9753,
"s": 9717,
"text": "You can reach me via the following:"
},
{
"code": null,
"e": 9987,
"s": 9753,
"text": "Subscribe to my YouTube channel for video content coming soon hereFollow me on MediumConnect and reach me on LinkedInFollow me on my blogging journey:- https://kajalyadav.com/Become a member:- https://techykajal.medium.com/membership"
},
{
"code": null,
"e": 10054,
"s": 9987,
"text": "Subscribe to my YouTube channel for video content coming soon here"
},
{
"code": null,
"e": 10074,
"s": 10054,
"text": "Follow me on Medium"
},
{
"code": null,
"e": 10107,
"s": 10074,
"text": "Connect and reach me on LinkedIn"
},
{
"code": null,
"e": 10166,
"s": 10107,
"text": "Follow me on my blogging journey:- https://kajalyadav.com/"
},
{
"code": null,
"e": 10225,
"s": 10166,
"text": "Become a member:- https://techykajal.medium.com/membership"
}
] |
Pipenv vs Conda (for Data Scientists) | by Dr Soumaya Mauthoor | Towards Data Science
|
Python has many tools available for distributing code to developers and does not adhere to “There should be one — and preferably only one — obvious way to do it”. For example Conda+Anaconda is recommended by scipy.org which manages the ubiquitous scipy stack, whilst pipenv+PyPI is recommended by PyPA, the python packaging authority. Which could leave data scientists in a bit of a quandary. This article compares pipenv and conda as of Jan 2021 using the following set of criteria, some of which are more relevant to data scientists:
Package Availability Dependency resolutionPython versionDependency SpecificationDisk SpaceSecurityLongevityCustomisationMiscellaneous
The article does not recommend one tool over another but should help the reader make a decision based on their needs. The article assumes the reader is already familiar with the python packaging ecosystem, pipenv and conda. For those less familiar, I have also included a list of useful resources at the end of the article.
Are packages available in the appropriate format?
As stated by Anaconda, “over 1500 packages are available in the Anaconda repository, including the most popular data science, machine learning, and AI frameworks. These, along with thousands of additional packages available on Anaconda cloud from channeling including conda-forge and bioconda, can be installed using conda. Despite this large collection of packages, it is still small compared to the 150,000 packages available on PyPI”. On the other hand, not all packages in PyPI are available as wheels, which is especially problematic for data science libraries which usually require C/C++/Fortran code. Whilst it is possible to install PyPI packages using pip in conda environments, this requires all the sub-dependencies to be pip packages themselves too and can cause headaches so is not recommended. There is usually a delay between packages being available in Anaconda main channel compared to PyPI. For example the delay for pandas seems to be a few weeks.
I wanted to check if pipenv+PyPI and conda+Anaconda could provision a data scientist’s basic tool set: pandas, scikit-learn, sqlalchemy, jupyter, matplotlib and networkx. I used python3.8 because 3.9 came out just recently.
$ pipenv install pandas scikit-learn sqlalchemy jupyter matplotlib networkx --python 3.8$ conda create --name env_ds scikit-learn sqlalchemy jupyter matplotlib networkx python=3.8
Both environments were successfully created in about 3 minutes. Note that I am using Ubuntu WSL1, different platforms might not be as successful in creating the environments.
Resolving direct and indirect dependencies
Conda
To test this criteria I used pandas which has a dependency on numpy. I first attempted to install numpy1.15.3 and pandas using conda, so that the environment has a direct dependency on pandas and numpy and indirect dependency on numpy:
$ conda create --name env_a numpy==1.15.3 pandas python=3.7
Conda is successful at creating an environment and installs pandas1.0.5 which is the last pandas version to support numpy1.15.3.
If the package version of an existing environment requires upgrading or downgrading:
$ conda create --name env_b pandas python=3.7$ conda activate env_b$ conda install numpy==1.15.3
Conda will ask you before updating the environment:
The following packages will be DOWNGRADED:
numpy 1.19.2-py37h54aff64_0 → 1.15.3-py37h99e49ec_0 numpy-base 1.19.2-py37hfa32c7d_0 → 1.15.3-py37h2f8d375_0 pandas 1.2.0-py37ha9443f7_0 → 1.0.5-py37h0573a6f_0
Proceed ([y]/n)?
Note that it is recommended to specify all packages at the same time to help Conda resolve dependencies.
Pipenv
I then attempted to install the same packages with pipenv:
$ pipenv install numpy==1.15.3 pandas --python 3.7
Pipenv creates an environment using numpy1.19.1, which does not meet my specification. Pipenv determines that there are conflicts, is unable to create a Pipfile.lock and prints the following useful message:
✘ Locking Failed!There are incompatible versions in the resolved dependencies: numpy==1.15.3 (from -r /tmp/pipenvzq7o52yjrequirements/pipenv-5bf3v15e-constraints.txt (line 3)) numpy>=1.16.5 (from pandas==1.2.0->-r /tmp/pipenvzq7o52yjrequirements/pipenv-5bf3v15e-constraints.txt (line 2))
Pipenv also has the graph and graph-reverse commands which prints the dependency graph and allows users to trace how package depend on each other and helps resolve conflicts.
$ pipenv graph
pandas==1.2.0 -numpy [required: >=1.16.5, installed: 1.19.5] -python-dateutil [required: >=2.7.3, installed: 2.8.1] — six [required: >=1.5, installed: 1.15.0] -pytz [required: >=2017.3, installed: 2020.5]
Note that the pip dependency resolver is going through changes. I used the latest version (20.3.1) but the outcome might vary depending on the pip version.
Managing different python versions
Conda
Conda will treat the python distribution like a package and automatically install any python version that you have directly specified. Moreover when creating a new environment, conda will determine the best python version (if not specified). For example:
$ conda create —-name env_a pandas
creates an environment with python3.8.5 and pandas1.1.5 but
$ conda create —-name env_c pandas==0.25.0
creates an environment with python3.7.9 which is the last python version to support pandas0.25.0.
The install will fail if it requires upgrading/downgrading the python version of an existing environment:
$ conda create —-name env_d python==3.8$ conda activate env_d$ conda install pandas==0.25.0
but the error message is very helpful:
UnsatisfiableError: The following specifications were foundto be incompatible with the existing python installation in your environment:Specifications:- pandas==0.25.0 -> python[version=’>=3.6,< 3.7.0a0|>=3.7,< 3.8.0a0']
Pipenv
Pipenv does not natively install different python versions. It will use the system python (usually stored in /usr/lib) or the base python (usually stored in ~/miniconda3/bin if miniconda is installed) to create new environments. However pipenv can use pyenv to install other python versions if pyenv is installed. You can use pyenv to pre-install python versions, or pipenv will ask you to install a python version if it’s not already available locally:https://towardsdatascience.com/python-environment-101-1d68bda3094d
Unfortunately pipenv+pyenv cannot resolve the best python version, even when creating a environment from scratch. For example:
$ pipenv install pandas
creates an environment with python3.8.5 and pandas1.2.0. Attempting to install pandas0.25.0 where the default pyenv python version is 3.8 stalls:
$ pipenv install pandas==0.25.0
Note that the stalling is probably due to how the requirements for pandas0.25.0 were configured. pip relies on the python_requires attribute to determine if the python version is suitable, which is a recent addition. Attempting to install more recent packages where the python_requires attribute is not met usually fails with a “distribution not found” error. Note that pipenv will also attempt to install the latest version of a package if unspecified, regardless of the python version. For example attempting to pandas in a python3.5 environment:
$ pipenv install pandas --python 3.5
will fail with the following error message:
[pipenv.exceptions.InstallError]: ERROR: Could not find a version that satisfies the requirement pandas==1.1.5[pipenv.exceptions.InstallError]: ERROR: No matching distribution found for pandas==1.1.5
This message is not very helpful and has been raised as an issue with pip.
Ensuring a reproducible build that is upgradable
Pipenv uses two files to specify dependencies: Pipfile for direct dependencies and Pipfile.lock for both direct and indirect dependencies. Creating an an environment using the Pipfile.lock ensures that exactly the same packages will be installed, including the hash of the package. Creating an environement using the Pipfile gives it the flexibility to upgrade indirect dependencies if required. Pipenv hopes that the Pipfiles will replace requirements.txt in the future (see https://github.com/pypa/pipfile).
Conda uses an environment.yaml file to specify both direct and indirect dependencies. Users have to use trial and error when updating their environments. There is a conda-lock library which replicates the Pipfile.lock ability but it is not currently supported by Anaconda.
How much space do environments take up? Can sharing help?
Python environments used by data scientists tend be large, especially conda environments. For example a conda environment with jupyter and pandas takes up 1.7GB, whilst an equivalent pipenv environment takes up 208MB. Whilst not relevant to most development environments, this may become more important in production, for example when using containers:https://towardsdatascience.com/how-to-shrink-numpy-scipy-pandas-and-matplotlib-for-your-data-product-4ec8d7e86ee4
Because of their large size, data scientists often use a conda environment across multiple exploratory projects, or even across multiple production projects which are part of the same solution:https://stackoverflow.com/questions/55892572/keeping-the-same-shared-virtualenvs-when-switching-from-pyenv-virtualenv-to-pipThe conda environment can be created, activated and used from any location.
A pipenv environment is tied to a project repository. Once created, Pipenv saves the pipfiles to the root of the repository. The installed packages are saved to ~/.local/share/.virtualenvs / by default, where pipenv ensures that one environment is created per repo by creating a new directory and appending a hash of the path to the name (i.e. my_project-a3de50). The user must cd to the root of the project repository to activate the environment, but the shell will remain activated even if you leave the directory. It is possible to share an environment across multiple projects by storing the Pipfiles in a separate directory. The user must then remember to cd to the repository to activate and update the environment.
How safe are packages to install?
The Anaconda main channel https://anaconda.org/anaconda/ is maintained by Anaconda employees and packages go through a strict security check before uploading. In the case of pipenv which uses PyPI, anyone can upload any package and nefarious packages have been found in the past (see https://www.zdnet.com/article/twelve-malicious-python-libraries-found-and-removed-from-pypi/). The same goes with conda-forge although they are developing a process to validate artifacts before they are uploaded to the repository.
Work-arounds include:
Perform security checks using tools like x-ray https://jfrog.com/xray/
Only install packages which are at least a month old to give enough time for issues to be found and resolved
Is conda/pipenv here to stay? How mature is it? Who supports it?
Pipenv was first introduced in 2017 by the creator of the popular requests library. Pipenv did not release any new code between Nov 2018-May 2020 which raised some concern about its future:https://medium.com/telnyx-engineering/rip-pipenv-tried-too-hard-do-what-you-need-with-pip-tools-d500edc161d4https://chriswarrick.com/blog/2018/07/17/pipenv-promises-a-lot-delivers-very-little/Pipenv has now been picked up by new developers and is being updated more regularly with monthly releases since May 2020.
Conda/Anaconda was created in 2012 by the same team behind scipy.org which manages the scipy stack. Conda is an open source tool but the anaconda repository is hosted by Anaconda Inc., a for-profit organisation. Whilst this means conda/anaconda is unlikely to disappear anytime soon, this has raised concern that Anaconda Inc. might start charging users. They have recently changed their terms of conditions to charge heavy or commercial users which includes mirroring the anaconda repository. Note that the new terms of condition does not apply to the conda-forge channel.
What advantages does a custom package manager bring?
Conda/Anaconda was created by the python scientific community to solve problems specific to their community, such as non-python dependencies:http://technicaldiscovery.blogspot.com/2013/12/why-i-promote-conda.htmlThis gives it the flexibility and impetus to create products geared for Data Scientists.
Conda can distribute non-Python build requirements, such as gcc, which greatly streamlines the process of building other packages on top of the pre-compiled binaries it distributes. Conda can also install R packages. Anaconda developed MKL-powered binary versions of some of the most popular numerical/scientific Python libraries. These have been shown to lead to significant improvements in performance. Whilst MKL optimizations are no longer in production, Anaconda could still develop tools that are only compatible with a conda environment.
How is code packaged up?
Both conda and pipenv rely on additional tools for packaging code. Both also rely on following “recipes” depending on whether the code contains non-python code and the target platform.
Conda-build is used to create conda packages:https://docs.conda.io/projects/conda-build/en/latest/
PyPA recommends using setuptools to build wheels that can be installed using pipenv. Below is a great overview:https://realpython.com/python-wheels/
Note that python packaging is expected to change a lot in the future with the introduction of pyproject.toml file and PEP518:https://grassfedcode.medium.com/pep-517-and-518-in-plain-english-47208ca8b7a6
Any other factors to consider?
Conda resolves and prints what packages will be installed before installing them, giving users the opportunity to proceed or reconsider before going through the lengthy installation procedure
Changing the name/path of the project directory breaks the pipenv environment and a new environment is automatically created (see https://github.com/pypa/pipenv/issues/796)
Conda does not automatically create/update the environment.yaml file, unlike pipenv which updates the Pipfile. Hence it is possible for your environment and environment.yaml file to become out of synch if you forget to update your environment.yaml file
A review of the python packaging ecosystemhttps://packaging.python.org/overview/https://towardsdatascience.com/packaging-in-python-tools-and-formats-743ead5f39ee
A guide to pipenv https://realpython.com/pipenv-guide/
A guide to conda/Anaconda for data scientists(Whist geared for Windows the theory is relevant to any OS)https://realpython.com/python-windows-machine-learning-setup/
A comparison of conda and piphttps://jakevdp.github.io/blog/2016/08/25/conda-myths-and-misconceptions/https://www.anaconda.com/blog/understanding-conda-and-pip
Ensuring a reproducible build, and still be able to quickly change your dependencieshttps://pythonspeed.com/articles/conda-dependency-management/
Options for packaging your Python codehttps://pythonspeed.com/articles/distributing-software/
|
[
{
"code": null,
"e": 707,
"s": 171,
"text": "Python has many tools available for distributing code to developers and does not adhere to “There should be one — and preferably only one — obvious way to do it”. For example Conda+Anaconda is recommended by scipy.org which manages the ubiquitous scipy stack, whilst pipenv+PyPI is recommended by PyPA, the python packaging authority. Which could leave data scientists in a bit of a quandary. This article compares pipenv and conda as of Jan 2021 using the following set of criteria, some of which are more relevant to data scientists:"
},
{
"code": null,
"e": 841,
"s": 707,
"text": "Package Availability Dependency resolutionPython versionDependency SpecificationDisk SpaceSecurityLongevityCustomisationMiscellaneous"
},
{
"code": null,
"e": 1165,
"s": 841,
"text": "The article does not recommend one tool over another but should help the reader make a decision based on their needs. The article assumes the reader is already familiar with the python packaging ecosystem, pipenv and conda. For those less familiar, I have also included a list of useful resources at the end of the article."
},
{
"code": null,
"e": 1215,
"s": 1165,
"text": "Are packages available in the appropriate format?"
},
{
"code": null,
"e": 2182,
"s": 1215,
"text": "As stated by Anaconda, “over 1500 packages are available in the Anaconda repository, including the most popular data science, machine learning, and AI frameworks. These, along with thousands of additional packages available on Anaconda cloud from channeling including conda-forge and bioconda, can be installed using conda. Despite this large collection of packages, it is still small compared to the 150,000 packages available on PyPI”. On the other hand, not all packages in PyPI are available as wheels, which is especially problematic for data science libraries which usually require C/C++/Fortran code. Whilst it is possible to install PyPI packages using pip in conda environments, this requires all the sub-dependencies to be pip packages themselves too and can cause headaches so is not recommended. There is usually a delay between packages being available in Anaconda main channel compared to PyPI. For example the delay for pandas seems to be a few weeks."
},
{
"code": null,
"e": 2406,
"s": 2182,
"text": "I wanted to check if pipenv+PyPI and conda+Anaconda could provision a data scientist’s basic tool set: pandas, scikit-learn, sqlalchemy, jupyter, matplotlib and networkx. I used python3.8 because 3.9 came out just recently."
},
{
"code": null,
"e": 2586,
"s": 2406,
"text": "$ pipenv install pandas scikit-learn sqlalchemy jupyter matplotlib networkx --python 3.8$ conda create --name env_ds scikit-learn sqlalchemy jupyter matplotlib networkx python=3.8"
},
{
"code": null,
"e": 2761,
"s": 2586,
"text": "Both environments were successfully created in about 3 minutes. Note that I am using Ubuntu WSL1, different platforms might not be as successful in creating the environments."
},
{
"code": null,
"e": 2804,
"s": 2761,
"text": "Resolving direct and indirect dependencies"
},
{
"code": null,
"e": 2810,
"s": 2804,
"text": "Conda"
},
{
"code": null,
"e": 3046,
"s": 2810,
"text": "To test this criteria I used pandas which has a dependency on numpy. I first attempted to install numpy1.15.3 and pandas using conda, so that the environment has a direct dependency on pandas and numpy and indirect dependency on numpy:"
},
{
"code": null,
"e": 3106,
"s": 3046,
"text": "$ conda create --name env_a numpy==1.15.3 pandas python=3.7"
},
{
"code": null,
"e": 3235,
"s": 3106,
"text": "Conda is successful at creating an environment and installs pandas1.0.5 which is the last pandas version to support numpy1.15.3."
},
{
"code": null,
"e": 3320,
"s": 3235,
"text": "If the package version of an existing environment requires upgrading or downgrading:"
},
{
"code": null,
"e": 3417,
"s": 3320,
"text": "$ conda create --name env_b pandas python=3.7$ conda activate env_b$ conda install numpy==1.15.3"
},
{
"code": null,
"e": 3469,
"s": 3417,
"text": "Conda will ask you before updating the environment:"
},
{
"code": null,
"e": 3512,
"s": 3469,
"text": "The following packages will be DOWNGRADED:"
},
{
"code": null,
"e": 3672,
"s": 3512,
"text": "numpy 1.19.2-py37h54aff64_0 → 1.15.3-py37h99e49ec_0 numpy-base 1.19.2-py37hfa32c7d_0 → 1.15.3-py37h2f8d375_0 pandas 1.2.0-py37ha9443f7_0 → 1.0.5-py37h0573a6f_0"
},
{
"code": null,
"e": 3689,
"s": 3672,
"text": "Proceed ([y]/n)?"
},
{
"code": null,
"e": 3794,
"s": 3689,
"text": "Note that it is recommended to specify all packages at the same time to help Conda resolve dependencies."
},
{
"code": null,
"e": 3801,
"s": 3794,
"text": "Pipenv"
},
{
"code": null,
"e": 3860,
"s": 3801,
"text": "I then attempted to install the same packages with pipenv:"
},
{
"code": null,
"e": 3911,
"s": 3860,
"text": "$ pipenv install numpy==1.15.3 pandas --python 3.7"
},
{
"code": null,
"e": 4118,
"s": 3911,
"text": "Pipenv creates an environment using numpy1.19.1, which does not meet my specification. Pipenv determines that there are conflicts, is unable to create a Pipfile.lock and prints the following useful message:"
},
{
"code": null,
"e": 4406,
"s": 4118,
"text": "✘ Locking Failed!There are incompatible versions in the resolved dependencies: numpy==1.15.3 (from -r /tmp/pipenvzq7o52yjrequirements/pipenv-5bf3v15e-constraints.txt (line 3)) numpy>=1.16.5 (from pandas==1.2.0->-r /tmp/pipenvzq7o52yjrequirements/pipenv-5bf3v15e-constraints.txt (line 2))"
},
{
"code": null,
"e": 4581,
"s": 4406,
"text": "Pipenv also has the graph and graph-reverse commands which prints the dependency graph and allows users to trace how package depend on each other and helps resolve conflicts."
},
{
"code": null,
"e": 4596,
"s": 4581,
"text": "$ pipenv graph"
},
{
"code": null,
"e": 4801,
"s": 4596,
"text": "pandas==1.2.0 -numpy [required: >=1.16.5, installed: 1.19.5] -python-dateutil [required: >=2.7.3, installed: 2.8.1] — six [required: >=1.5, installed: 1.15.0] -pytz [required: >=2017.3, installed: 2020.5]"
},
{
"code": null,
"e": 4957,
"s": 4801,
"text": "Note that the pip dependency resolver is going through changes. I used the latest version (20.3.1) but the outcome might vary depending on the pip version."
},
{
"code": null,
"e": 4992,
"s": 4957,
"text": "Managing different python versions"
},
{
"code": null,
"e": 4998,
"s": 4992,
"text": "Conda"
},
{
"code": null,
"e": 5253,
"s": 4998,
"text": "Conda will treat the python distribution like a package and automatically install any python version that you have directly specified. Moreover when creating a new environment, conda will determine the best python version (if not specified). For example:"
},
{
"code": null,
"e": 5288,
"s": 5253,
"text": "$ conda create —-name env_a pandas"
},
{
"code": null,
"e": 5348,
"s": 5288,
"text": "creates an environment with python3.8.5 and pandas1.1.5 but"
},
{
"code": null,
"e": 5391,
"s": 5348,
"text": "$ conda create —-name env_c pandas==0.25.0"
},
{
"code": null,
"e": 5489,
"s": 5391,
"text": "creates an environment with python3.7.9 which is the last python version to support pandas0.25.0."
},
{
"code": null,
"e": 5595,
"s": 5489,
"text": "The install will fail if it requires upgrading/downgrading the python version of an existing environment:"
},
{
"code": null,
"e": 5687,
"s": 5595,
"text": "$ conda create —-name env_d python==3.8$ conda activate env_d$ conda install pandas==0.25.0"
},
{
"code": null,
"e": 5726,
"s": 5687,
"text": "but the error message is very helpful:"
},
{
"code": null,
"e": 5947,
"s": 5726,
"text": "UnsatisfiableError: The following specifications were foundto be incompatible with the existing python installation in your environment:Specifications:- pandas==0.25.0 -> python[version=’>=3.6,< 3.7.0a0|>=3.7,< 3.8.0a0']"
},
{
"code": null,
"e": 5954,
"s": 5947,
"text": "Pipenv"
},
{
"code": null,
"e": 6474,
"s": 5954,
"text": "Pipenv does not natively install different python versions. It will use the system python (usually stored in /usr/lib) or the base python (usually stored in ~/miniconda3/bin if miniconda is installed) to create new environments. However pipenv can use pyenv to install other python versions if pyenv is installed. You can use pyenv to pre-install python versions, or pipenv will ask you to install a python version if it’s not already available locally:https://towardsdatascience.com/python-environment-101-1d68bda3094d"
},
{
"code": null,
"e": 6601,
"s": 6474,
"text": "Unfortunately pipenv+pyenv cannot resolve the best python version, even when creating a environment from scratch. For example:"
},
{
"code": null,
"e": 6625,
"s": 6601,
"text": "$ pipenv install pandas"
},
{
"code": null,
"e": 6771,
"s": 6625,
"text": "creates an environment with python3.8.5 and pandas1.2.0. Attempting to install pandas0.25.0 where the default pyenv python version is 3.8 stalls:"
},
{
"code": null,
"e": 6803,
"s": 6771,
"text": "$ pipenv install pandas==0.25.0"
},
{
"code": null,
"e": 7352,
"s": 6803,
"text": "Note that the stalling is probably due to how the requirements for pandas0.25.0 were configured. pip relies on the python_requires attribute to determine if the python version is suitable, which is a recent addition. Attempting to install more recent packages where the python_requires attribute is not met usually fails with a “distribution not found” error. Note that pipenv will also attempt to install the latest version of a package if unspecified, regardless of the python version. For example attempting to pandas in a python3.5 environment:"
},
{
"code": null,
"e": 7389,
"s": 7352,
"text": "$ pipenv install pandas --python 3.5"
},
{
"code": null,
"e": 7433,
"s": 7389,
"text": "will fail with the following error message:"
},
{
"code": null,
"e": 7633,
"s": 7433,
"text": "[pipenv.exceptions.InstallError]: ERROR: Could not find a version that satisfies the requirement pandas==1.1.5[pipenv.exceptions.InstallError]: ERROR: No matching distribution found for pandas==1.1.5"
},
{
"code": null,
"e": 7708,
"s": 7633,
"text": "This message is not very helpful and has been raised as an issue with pip."
},
{
"code": null,
"e": 7757,
"s": 7708,
"text": "Ensuring a reproducible build that is upgradable"
},
{
"code": null,
"e": 8267,
"s": 7757,
"text": "Pipenv uses two files to specify dependencies: Pipfile for direct dependencies and Pipfile.lock for both direct and indirect dependencies. Creating an an environment using the Pipfile.lock ensures that exactly the same packages will be installed, including the hash of the package. Creating an environement using the Pipfile gives it the flexibility to upgrade indirect dependencies if required. Pipenv hopes that the Pipfiles will replace requirements.txt in the future (see https://github.com/pypa/pipfile)."
},
{
"code": null,
"e": 8540,
"s": 8267,
"text": "Conda uses an environment.yaml file to specify both direct and indirect dependencies. Users have to use trial and error when updating their environments. There is a conda-lock library which replicates the Pipfile.lock ability but it is not currently supported by Anaconda."
},
{
"code": null,
"e": 8598,
"s": 8540,
"text": "How much space do environments take up? Can sharing help?"
},
{
"code": null,
"e": 9064,
"s": 8598,
"text": "Python environments used by data scientists tend be large, especially conda environments. For example a conda environment with jupyter and pandas takes up 1.7GB, whilst an equivalent pipenv environment takes up 208MB. Whilst not relevant to most development environments, this may become more important in production, for example when using containers:https://towardsdatascience.com/how-to-shrink-numpy-scipy-pandas-and-matplotlib-for-your-data-product-4ec8d7e86ee4"
},
{
"code": null,
"e": 9457,
"s": 9064,
"text": "Because of their large size, data scientists often use a conda environment across multiple exploratory projects, or even across multiple production projects which are part of the same solution:https://stackoverflow.com/questions/55892572/keeping-the-same-shared-virtualenvs-when-switching-from-pyenv-virtualenv-to-pipThe conda environment can be created, activated and used from any location."
},
{
"code": null,
"e": 10179,
"s": 9457,
"text": "A pipenv environment is tied to a project repository. Once created, Pipenv saves the pipfiles to the root of the repository. The installed packages are saved to ~/.local/share/.virtualenvs / by default, where pipenv ensures that one environment is created per repo by creating a new directory and appending a hash of the path to the name (i.e. my_project-a3de50). The user must cd to the root of the project repository to activate the environment, but the shell will remain activated even if you leave the directory. It is possible to share an environment across multiple projects by storing the Pipfiles in a separate directory. The user must then remember to cd to the repository to activate and update the environment."
},
{
"code": null,
"e": 10213,
"s": 10179,
"text": "How safe are packages to install?"
},
{
"code": null,
"e": 10728,
"s": 10213,
"text": "The Anaconda main channel https://anaconda.org/anaconda/ is maintained by Anaconda employees and packages go through a strict security check before uploading. In the case of pipenv which uses PyPI, anyone can upload any package and nefarious packages have been found in the past (see https://www.zdnet.com/article/twelve-malicious-python-libraries-found-and-removed-from-pypi/). The same goes with conda-forge although they are developing a process to validate artifacts before they are uploaded to the repository."
},
{
"code": null,
"e": 10750,
"s": 10728,
"text": "Work-arounds include:"
},
{
"code": null,
"e": 10821,
"s": 10750,
"text": "Perform security checks using tools like x-ray https://jfrog.com/xray/"
},
{
"code": null,
"e": 10930,
"s": 10821,
"text": "Only install packages which are at least a month old to give enough time for issues to be found and resolved"
},
{
"code": null,
"e": 10995,
"s": 10930,
"text": "Is conda/pipenv here to stay? How mature is it? Who supports it?"
},
{
"code": null,
"e": 11498,
"s": 10995,
"text": "Pipenv was first introduced in 2017 by the creator of the popular requests library. Pipenv did not release any new code between Nov 2018-May 2020 which raised some concern about its future:https://medium.com/telnyx-engineering/rip-pipenv-tried-too-hard-do-what-you-need-with-pip-tools-d500edc161d4https://chriswarrick.com/blog/2018/07/17/pipenv-promises-a-lot-delivers-very-little/Pipenv has now been picked up by new developers and is being updated more regularly with monthly releases since May 2020."
},
{
"code": null,
"e": 12072,
"s": 11498,
"text": "Conda/Anaconda was created in 2012 by the same team behind scipy.org which manages the scipy stack. Conda is an open source tool but the anaconda repository is hosted by Anaconda Inc., a for-profit organisation. Whilst this means conda/anaconda is unlikely to disappear anytime soon, this has raised concern that Anaconda Inc. might start charging users. They have recently changed their terms of conditions to charge heavy or commercial users which includes mirroring the anaconda repository. Note that the new terms of condition does not apply to the conda-forge channel."
},
{
"code": null,
"e": 12125,
"s": 12072,
"text": "What advantages does a custom package manager bring?"
},
{
"code": null,
"e": 12426,
"s": 12125,
"text": "Conda/Anaconda was created by the python scientific community to solve problems specific to their community, such as non-python dependencies:http://technicaldiscovery.blogspot.com/2013/12/why-i-promote-conda.htmlThis gives it the flexibility and impetus to create products geared for Data Scientists."
},
{
"code": null,
"e": 12971,
"s": 12426,
"text": "Conda can distribute non-Python build requirements, such as gcc, which greatly streamlines the process of building other packages on top of the pre-compiled binaries it distributes. Conda can also install R packages. Anaconda developed MKL-powered binary versions of some of the most popular numerical/scientific Python libraries. These have been shown to lead to significant improvements in performance. Whilst MKL optimizations are no longer in production, Anaconda could still develop tools that are only compatible with a conda environment."
},
{
"code": null,
"e": 12996,
"s": 12971,
"text": "How is code packaged up?"
},
{
"code": null,
"e": 13181,
"s": 12996,
"text": "Both conda and pipenv rely on additional tools for packaging code. Both also rely on following “recipes” depending on whether the code contains non-python code and the target platform."
},
{
"code": null,
"e": 13280,
"s": 13181,
"text": "Conda-build is used to create conda packages:https://docs.conda.io/projects/conda-build/en/latest/"
},
{
"code": null,
"e": 13429,
"s": 13280,
"text": "PyPA recommends using setuptools to build wheels that can be installed using pipenv. Below is a great overview:https://realpython.com/python-wheels/"
},
{
"code": null,
"e": 13632,
"s": 13429,
"text": "Note that python packaging is expected to change a lot in the future with the introduction of pyproject.toml file and PEP518:https://grassfedcode.medium.com/pep-517-and-518-in-plain-english-47208ca8b7a6"
},
{
"code": null,
"e": 13663,
"s": 13632,
"text": "Any other factors to consider?"
},
{
"code": null,
"e": 13855,
"s": 13663,
"text": "Conda resolves and prints what packages will be installed before installing them, giving users the opportunity to proceed or reconsider before going through the lengthy installation procedure"
},
{
"code": null,
"e": 14028,
"s": 13855,
"text": "Changing the name/path of the project directory breaks the pipenv environment and a new environment is automatically created (see https://github.com/pypa/pipenv/issues/796)"
},
{
"code": null,
"e": 14281,
"s": 14028,
"text": "Conda does not automatically create/update the environment.yaml file, unlike pipenv which updates the Pipfile. Hence it is possible for your environment and environment.yaml file to become out of synch if you forget to update your environment.yaml file"
},
{
"code": null,
"e": 14443,
"s": 14281,
"text": "A review of the python packaging ecosystemhttps://packaging.python.org/overview/https://towardsdatascience.com/packaging-in-python-tools-and-formats-743ead5f39ee"
},
{
"code": null,
"e": 14498,
"s": 14443,
"text": "A guide to pipenv https://realpython.com/pipenv-guide/"
},
{
"code": null,
"e": 14664,
"s": 14498,
"text": "A guide to conda/Anaconda for data scientists(Whist geared for Windows the theory is relevant to any OS)https://realpython.com/python-windows-machine-learning-setup/"
},
{
"code": null,
"e": 14824,
"s": 14664,
"text": "A comparison of conda and piphttps://jakevdp.github.io/blog/2016/08/25/conda-myths-and-misconceptions/https://www.anaconda.com/blog/understanding-conda-and-pip"
},
{
"code": null,
"e": 14970,
"s": 14824,
"text": "Ensuring a reproducible build, and still be able to quickly change your dependencieshttps://pythonspeed.com/articles/conda-dependency-management/"
}
] |
Bash shell script to swap two numbers - GeeksforGeeks
|
05 Jul, 2018
Given two numbers and the task is to swap them using the third variable.
Examples:
Input: first = 2, second = 4
Output: first = 4, second = 2
Input: first = 5, second = 7
Output: first = 7, second = 5
Approach:
Store the value of the first number into a temp variable.Store the value of the second number in the first number.Store the value of temp into the second variable.
Store the value of the first number into a temp variable.
Store the value of the second number in the first number.
Store the value of temp into the second variable.
# !/bin/bash # Program to swap two numbers # Static input of the# numberfirst=5second=10 temp=$firstfirst=$secondsecond=$temp echo "After swapping, numbers are:"echo "first = $first, second = $second"
Output:
After swapping, numbers are:
first = 10, second = 5
How to execute the bash files?
Write the bash code into a file and save that file with .sh extension i.e. filename.shOpen terminal and execute the file using below command:./filename.sh
Write the bash code into a file and save that file with .sh extension i.e. filename.sh
Open terminal and execute the file using below command:./filename.sh
./filename.sh
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
Docker - COPY Instruction
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Array Basics in Shell Scripting | Set 1
|
[
{
"code": null,
"e": 25786,
"s": 25758,
"text": "\n05 Jul, 2018"
},
{
"code": null,
"e": 25859,
"s": 25786,
"text": "Given two numbers and the task is to swap them using the third variable."
},
{
"code": null,
"e": 25869,
"s": 25859,
"text": "Examples:"
},
{
"code": null,
"e": 25989,
"s": 25869,
"text": "Input: first = 2, second = 4\nOutput: first = 4, second = 2\n\nInput: first = 5, second = 7\nOutput: first = 7, second = 5\n"
},
{
"code": null,
"e": 25999,
"s": 25989,
"text": "Approach:"
},
{
"code": null,
"e": 26163,
"s": 25999,
"text": "Store the value of the first number into a temp variable.Store the value of the second number in the first number.Store the value of temp into the second variable."
},
{
"code": null,
"e": 26221,
"s": 26163,
"text": "Store the value of the first number into a temp variable."
},
{
"code": null,
"e": 26279,
"s": 26221,
"text": "Store the value of the second number in the first number."
},
{
"code": null,
"e": 26329,
"s": 26279,
"text": "Store the value of temp into the second variable."
},
{
"code": "# !/bin/bash # Program to swap two numbers # Static input of the# numberfirst=5second=10 temp=$firstfirst=$secondsecond=$temp echo \"After swapping, numbers are:\"echo \"first = $first, second = $second\"",
"e": 26537,
"s": 26329,
"text": null
},
{
"code": null,
"e": 26545,
"s": 26537,
"text": "Output:"
},
{
"code": null,
"e": 26598,
"s": 26545,
"text": "After swapping, numbers are:\nfirst = 10, second = 5\n"
},
{
"code": null,
"e": 26629,
"s": 26598,
"text": "How to execute the bash files?"
},
{
"code": null,
"e": 26785,
"s": 26629,
"text": "Write the bash code into a file and save that file with .sh extension i.e. filename.shOpen terminal and execute the file using below command:./filename.sh\n"
},
{
"code": null,
"e": 26872,
"s": 26785,
"text": "Write the bash code into a file and save that file with .sh extension i.e. filename.sh"
},
{
"code": null,
"e": 26942,
"s": 26872,
"text": "Open terminal and execute the file using below command:./filename.sh\n"
},
{
"code": null,
"e": 26957,
"s": 26942,
"text": "./filename.sh\n"
},
{
"code": null,
"e": 26970,
"s": 26957,
"text": "Shell Script"
},
{
"code": null,
"e": 26981,
"s": 26970,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27079,
"s": 26981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27114,
"s": 27079,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27143,
"s": 27114,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27177,
"s": 27143,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27203,
"s": 27177,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27240,
"s": 27203,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27277,
"s": 27240,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27319,
"s": 27277,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27345,
"s": 27319,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27381,
"s": 27345,
"text": "uniq Command in LINUX with examples"
}
] |
p5.js mousePressed() Function - GeeksforGeeks
|
04 Mar, 2021
The mousePressed() function in p5.js works when mouse clicked on the document. The mouseButton variable is used to specify which button is pressed. The touchStarted() function is used instead of mousePressed() function if mousePressed() function is not defined.
Syntax:
mousePressed(Event)
Below programs illustrate the mousePressed() function in p5.js:
Example 1: This example uses mousePressed() function.
function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set background color background(200); // Fill the color fill(value, value-50, value-100); // Create rectangle rect(25, 25, 460, 440); // Set the color of text fill('lightgreen'); // Set font size textSize(15); // Display content text('Keep on Clicking the Mouse Across' + 'the page \nto change Canvas Color.', windowHeight/10, windowWidth/4);} function mousePressed() { value = value + 5; if (value > 255) { value = 0; }}
Output:
Example 2:
let valueX;let valueY; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Set the text color fill('green'); // Set text size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to mouseMoved() fill(valueX, 255-valueY, 255-valueX); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mousePressed() { valueX = mouseX%255; valueY = mouseY%255;}
Output:
Reference: https://p5js.org/reference/#/p5/mousePressed
JavaScript-p5.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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 45488,
"s": 45460,
"text": "\n04 Mar, 2021"
},
{
"code": null,
"e": 45750,
"s": 45488,
"text": "The mousePressed() function in p5.js works when mouse clicked on the document. The mouseButton variable is used to specify which button is pressed. The touchStarted() function is used instead of mousePressed() function if mousePressed() function is not defined."
},
{
"code": null,
"e": 45758,
"s": 45750,
"text": "Syntax:"
},
{
"code": null,
"e": 45778,
"s": 45758,
"text": "mousePressed(Event)"
},
{
"code": null,
"e": 45842,
"s": 45778,
"text": "Below programs illustrate the mousePressed() function in p5.js:"
},
{
"code": null,
"e": 45896,
"s": 45842,
"text": "Example 1: This example uses mousePressed() function."
},
{
"code": "function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set background color background(200); // Fill the color fill(value, value-50, value-100); // Create rectangle rect(25, 25, 460, 440); // Set the color of text fill('lightgreen'); // Set font size textSize(15); // Display content text('Keep on Clicking the Mouse Across' + 'the page \\nto change Canvas Color.', windowHeight/10, windowWidth/4);} function mousePressed() { value = value + 5; if (value > 255) { value = 0; }}",
"e": 46549,
"s": 45896,
"text": null
},
{
"code": null,
"e": 46557,
"s": 46549,
"text": "Output:"
},
{
"code": null,
"e": 46568,
"s": 46557,
"text": "Example 2:"
},
{
"code": "let valueX;let valueY; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Set the text color fill('green'); // Set text size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to mouseMoved() fill(valueX, 255-valueY, 255-valueX); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mousePressed() { valueX = mouseX%255; valueY = mouseY%255;}",
"e": 47115,
"s": 46568,
"text": null
},
{
"code": null,
"e": 47123,
"s": 47115,
"text": "Output:"
},
{
"code": null,
"e": 47179,
"s": 47123,
"text": "Reference: https://p5js.org/reference/#/p5/mousePressed"
},
{
"code": null,
"e": 47196,
"s": 47179,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 47207,
"s": 47196,
"text": "JavaScript"
},
{
"code": null,
"e": 47224,
"s": 47207,
"text": "Web Technologies"
},
{
"code": null,
"e": 47322,
"s": 47224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47362,
"s": 47322,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 47407,
"s": 47362,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 47468,
"s": 47407,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 47540,
"s": 47468,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 47609,
"s": 47540,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 47649,
"s": 47609,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 47682,
"s": 47649,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 47727,
"s": 47682,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 47770,
"s": 47727,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to find the Volume of a Triangular Prism - GeeksforGeeks
|
17 Mar, 2021
Given the length, width, and height of a triangular prism, the task is to find the volume of the triangular prism. Examples:
Input: l = 18, b = 12, h = 9
Output: Volume of triangular prism: 972
Input: l = 10, b = 8, h = 6
Output: Volume of triangular prism: 240
In mathematics, a triangular prism is a three-dimensional solid shape with two identical ends connected by equal parallel lines. The triangular prism contains 5 faces, 9 edges, and 6 vertices.
Formula to find the volume of triangular prism:
Volume = ( l * b * h ) / 2
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the volume// of the triangular prism#include <bits/stdc++.h>using namespace std; // function to find the Volume// of triangular prismfloat findVolume(float l, float b, float h){ // formula to find Volume float volume = (l * b * h) / 2; return volume;} // Driver Codeint main(){ float l = 18, b = 12, h = 9; // function calling cout << "Volume of triangular prism: " << findVolume(l, b, h); return 0;}
// Java program to find the volume// of the triangular prismimport java.io.*; class GFG { // function to find the Volume // of triangular prism static float findVolume(float l, float b, float h) { // formula to find Volume float volume = (l * b * h) / 2; return volume; } // Driver code public static void main(String[] args) { float l = 18, b = 12, h = 9; // function calling System.out.println("Volume of triangular prism: " + findVolume(l, b, h)); }}
# Python3 program to find the volume# of the triangular prism # function to find the Volume# of triangular prismdef findVolume(l, b, h) : # formula to find Volume return ((l * b * h) / 2) # Driver Codel = 18b = 12h = 9 # function callingprint("Volume of triangular prism: ", findVolume(l, b, h))
// C# program to find the volume// of the triangular prismusing System; class GFG { // function to find the Volume // of triangular prism static float findVolume(float l, float b, float h) { // formula to find Volume float volume = (l * b * h) / 2; return volume; } // Driver code static public void Main() { float l = 18, b = 12, h = 9; // function calling Console.WriteLine("Volume of triangular prism: " + findVolume(l, b, h)); }}
<?php// PHP program to find the volume// of the triangular prism // function to find the Volume// of triangular prismfunction findVolume($l, $b, $h){ // formula to find Volume $volume = ($l * $b * $h) / 2; return $volume;} // Driver Code$l = 18; $b = 12; $h = 9; // function callingecho "Volume of triangular prism: " . findVolume($l, $b, $h); ?>
<script>// Javascript program to find the volume// of the triangular prism // function to find the Volume// of triangular prismfunction findVolume( l, b, h){ // formula to find Volume let volume = (l * b * h) / 2; return volume;} // Driver Code let l = 18, b = 12, h = 9; // function calling document.write( "Volume of triangular prism: " + findVolume(l, b, h)); // This code is contributed by todaysgaurav </script>
Volume of triangular prism: 972
todaysgaurav
area-volume-programs
math
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Check whether a given point lies inside a triangle or not
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26888,
"s": 26860,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 27015,
"s": 26888,
"text": "Given the length, width, and height of a triangular prism, the task is to find the volume of the triangular prism. Examples: "
},
{
"code": null,
"e": 27154,
"s": 27015,
"text": "Input: l = 18, b = 12, h = 9\nOutput: Volume of triangular prism: 972\n\nInput: l = 10, b = 8, h = 6\nOutput: Volume of triangular prism: 240"
},
{
"code": null,
"e": 27351,
"s": 27156,
"text": "In mathematics, a triangular prism is a three-dimensional solid shape with two identical ends connected by equal parallel lines. The triangular prism contains 5 faces, 9 edges, and 6 vertices. "
},
{
"code": null,
"e": 27400,
"s": 27351,
"text": "Formula to find the volume of triangular prism: "
},
{
"code": null,
"e": 27428,
"s": 27400,
"text": "Volume = ( l * b * h ) / 2 "
},
{
"code": null,
"e": 27434,
"s": 27430,
"text": "C++"
},
{
"code": null,
"e": 27439,
"s": 27434,
"text": "Java"
},
{
"code": null,
"e": 27447,
"s": 27439,
"text": "Python3"
},
{
"code": null,
"e": 27450,
"s": 27447,
"text": "C#"
},
{
"code": null,
"e": 27454,
"s": 27450,
"text": "PHP"
},
{
"code": null,
"e": 27465,
"s": 27454,
"text": "Javascript"
},
{
"code": "// CPP program to find the volume// of the triangular prism#include <bits/stdc++.h>using namespace std; // function to find the Volume// of triangular prismfloat findVolume(float l, float b, float h){ // formula to find Volume float volume = (l * b * h) / 2; return volume;} // Driver Codeint main(){ float l = 18, b = 12, h = 9; // function calling cout << \"Volume of triangular prism: \" << findVolume(l, b, h); return 0;}",
"e": 27921,
"s": 27465,
"text": null
},
{
"code": "// Java program to find the volume// of the triangular prismimport java.io.*; class GFG { // function to find the Volume // of triangular prism static float findVolume(float l, float b, float h) { // formula to find Volume float volume = (l * b * h) / 2; return volume; } // Driver code public static void main(String[] args) { float l = 18, b = 12, h = 9; // function calling System.out.println(\"Volume of triangular prism: \" + findVolume(l, b, h)); }}",
"e": 28474,
"s": 27921,
"text": null
},
{
"code": "# Python3 program to find the volume# of the triangular prism # function to find the Volume# of triangular prismdef findVolume(l, b, h) : # formula to find Volume return ((l * b * h) / 2) # Driver Codel = 18b = 12h = 9 # function callingprint(\"Volume of triangular prism: \", findVolume(l, b, h))",
"e": 28796,
"s": 28474,
"text": null
},
{
"code": "// C# program to find the volume// of the triangular prismusing System; class GFG { // function to find the Volume // of triangular prism static float findVolume(float l, float b, float h) { // formula to find Volume float volume = (l * b * h) / 2; return volume; } // Driver code static public void Main() { float l = 18, b = 12, h = 9; // function calling Console.WriteLine(\"Volume of triangular prism: \" + findVolume(l, b, h)); }}",
"e": 29328,
"s": 28796,
"text": null
},
{
"code": "<?php// PHP program to find the volume// of the triangular prism // function to find the Volume// of triangular prismfunction findVolume($l, $b, $h){ // formula to find Volume $volume = ($l * $b * $h) / 2; return $volume;} // Driver Code$l = 18; $b = 12; $h = 9; // function callingecho \"Volume of triangular prism: \" . findVolume($l, $b, $h); ?>",
"e": 29696,
"s": 29328,
"text": null
},
{
"code": "<script>// Javascript program to find the volume// of the triangular prism // function to find the Volume// of triangular prismfunction findVolume( l, b, h){ // formula to find Volume let volume = (l * b * h) / 2; return volume;} // Driver Code let l = 18, b = 12, h = 9; // function calling document.write( \"Volume of triangular prism: \" + findVolume(l, b, h)); // This code is contributed by todaysgaurav </script>",
"e": 30137,
"s": 29696,
"text": null
},
{
"code": null,
"e": 30169,
"s": 30137,
"text": "Volume of triangular prism: 972"
},
{
"code": null,
"e": 30184,
"s": 30171,
"text": "todaysgaurav"
},
{
"code": null,
"e": 30205,
"s": 30184,
"text": "area-volume-programs"
},
{
"code": null,
"e": 30210,
"s": 30205,
"text": "math"
},
{
"code": null,
"e": 30220,
"s": 30210,
"text": "Geometric"
},
{
"code": null,
"e": 30233,
"s": 30220,
"text": "Mathematical"
},
{
"code": null,
"e": 30246,
"s": 30233,
"text": "Mathematical"
},
{
"code": null,
"e": 30256,
"s": 30246,
"text": "Geometric"
},
{
"code": null,
"e": 30354,
"s": 30256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30403,
"s": 30354,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 30456,
"s": 30403,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 30507,
"s": 30456,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30541,
"s": 30507,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30599,
"s": 30541,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 30629,
"s": 30599,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30644,
"s": 30629,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30704,
"s": 30644,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30747,
"s": 30704,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python Program to Convert a list of multiple integers into a single integer
|
03 Dec, 2020
Given a list of integers, write a Python program to convert the given list into a single integer.
Examples:
Input : [1, 2, 3]
Output : 123
Input : [55, 32, 890]
Output : 5532890
There are multiple approaches possible to convert the given list into a single integer. Let’s see each one by one.
Approach #1 : Naive MethodSimply iterate each element in the list and print them without space in between.
# Python3 program to convert a list# of integers into a single integer # creating a listlst = [12, 15, 17] # iterating each elementfor i in lst: print(i, end="")
Output:
121517
Approach #2 : Using join()
Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method. It takes a time complexity of O(n).
# Python3 program to convert a list# of integers into a single integerdef convert(list): # Converting integer list to string list s = [str(i) for i in list] # Join list items using join() res = int("".join(s)) return(res) # Driver codelist = [1, 2, 3]print(convert(list))
Output:
123
Approach #3 : Using map()
Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.
# Python3 program to convert a list# of integers into a single integerdef convert(list): # Converting integer list to string list # and joining the list using join() res = int("".join(map(str, list))) return res # Driver codelist = [1, 2, 3]print(convert(list))
Output:
123
Approach #4 : Multiplying by corresponding power of 10
A more mathematical way, which does not require to convert the integer list to string list is, to multiply each integer element with its corresponding power of 10, and then summing it up. It takes a time complexity of O(n).
# Python3 program to convert a list# of integers into a single integerdef convert(list): # multiply each integer element with its # corresponding power and perform summation res = sum(d * 10**i for i, d in enumerate(list[::-1])) return(res) # Driver codelist = [1, 2, 3]print(convert(list))
Output:
123
A small variation to this program leads to less computation in calculation of sum, i.e. using reduce(). This makes use of Horner’s rule, which factors the polynomial representing the number to reduce the number of multiplications.
res = functools.reduce(lambda total, d: 10 * total + d, list, 0)
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 151,
"s": 53,
"text": "Given a list of integers, write a Python program to convert the given list into a single integer."
},
{
"code": null,
"e": 161,
"s": 151,
"text": "Examples:"
},
{
"code": null,
"e": 232,
"s": 161,
"text": "Input : [1, 2, 3]\nOutput : 123\n\nInput : [55, 32, 890]\nOutput : 5532890"
},
{
"code": null,
"e": 347,
"s": 232,
"text": "There are multiple approaches possible to convert the given list into a single integer. Let’s see each one by one."
},
{
"code": null,
"e": 454,
"s": 347,
"text": "Approach #1 : Naive MethodSimply iterate each element in the list and print them without space in between."
},
{
"code": "# Python3 program to convert a list# of integers into a single integer # creating a listlst = [12, 15, 17] # iterating each elementfor i in lst: print(i, end=\"\")",
"e": 621,
"s": 454,
"text": null
},
{
"code": null,
"e": 629,
"s": 621,
"text": "Output:"
},
{
"code": null,
"e": 636,
"s": 629,
"text": "121517"
},
{
"code": null,
"e": 664,
"s": 636,
"text": " Approach #2 : Using join()"
},
{
"code": null,
"e": 871,
"s": 664,
"text": "Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method. It takes a time complexity of O(n)."
},
{
"code": "# Python3 program to convert a list# of integers into a single integerdef convert(list): # Converting integer list to string list s = [str(i) for i in list] # Join list items using join() res = int(\"\".join(s)) return(res) # Driver codelist = [1, 2, 3]print(convert(list))",
"e": 1177,
"s": 871,
"text": null
},
{
"code": null,
"e": 1185,
"s": 1177,
"text": "Output:"
},
{
"code": null,
"e": 1189,
"s": 1185,
"text": "123"
},
{
"code": null,
"e": 1216,
"s": 1189,
"text": " Approach #3 : Using map()"
},
{
"code": null,
"e": 1464,
"s": 1216,
"text": "Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer."
},
{
"code": "# Python3 program to convert a list# of integers into a single integerdef convert(list): # Converting integer list to string list # and joining the list using join() res = int(\"\".join(map(str, list))) return res # Driver codelist = [1, 2, 3]print(convert(list))",
"e": 1751,
"s": 1464,
"text": null
},
{
"code": null,
"e": 1759,
"s": 1751,
"text": "Output:"
},
{
"code": null,
"e": 1763,
"s": 1759,
"text": "123"
},
{
"code": null,
"e": 1819,
"s": 1763,
"text": " Approach #4 : Multiplying by corresponding power of 10"
},
{
"code": null,
"e": 2043,
"s": 1819,
"text": "A more mathematical way, which does not require to convert the integer list to string list is, to multiply each integer element with its corresponding power of 10, and then summing it up. It takes a time complexity of O(n)."
},
{
"code": "# Python3 program to convert a list# of integers into a single integerdef convert(list): # multiply each integer element with its # corresponding power and perform summation res = sum(d * 10**i for i, d in enumerate(list[::-1])) return(res) # Driver codelist = [1, 2, 3]print(convert(list))",
"e": 2362,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2370,
"s": 2362,
"text": "Output:"
},
{
"code": null,
"e": 2374,
"s": 2370,
"text": "123"
},
{
"code": null,
"e": 2605,
"s": 2374,
"text": "A small variation to this program leads to less computation in calculation of sum, i.e. using reduce(). This makes use of Horner’s rule, which factors the polynomial representing the number to reduce the number of multiplications."
},
{
"code": "res = functools.reduce(lambda total, d: 10 * total + d, list, 0)",
"e": 2670,
"s": 2605,
"text": null
},
{
"code": null,
"e": 2691,
"s": 2670,
"text": "Python list-programs"
},
{
"code": null,
"e": 2703,
"s": 2691,
"text": "python-list"
},
{
"code": null,
"e": 2710,
"s": 2703,
"text": "Python"
},
{
"code": null,
"e": 2722,
"s": 2710,
"text": "python-list"
}
] |
Common Elements | Practice | GeeksforGeeks
|
Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list.
Example:
Input:
n = 5
v1[] = {3, 4, 2, 2, 4}
m = 4
v2[] = {3, 2, 2, 7}
Output:
2 2 3
Explanation:
The common elements in sorted order are {2 2 3}
Your Task:
This is a function problem. You need to complete the function common_element that takes both the lists as parameters and returns a list of common elements.
Constraints:
1 ≤ n, m ≤ 105
1 ≤ Vi ≤ 105
0
mayank2021in 8 hours
C++ : 0.55/4.16 vector<int> common_element(vector<int>v1,vector<int>v2) { //may2021 unordered_map<int, int>mp; vector<int>result; int n1=v1.size(), n2=v2.size(); for(int i=0; i<n1 ; i++) mp[v1[i]]++; for(int i=0; i<n2 ; i++) { if(mp.find(v2[i])!=mp.end()) { result.push_back(v2[i]); mp[v2[i]]--; if(mp[v2[i]]==0) mp.erase(v2[i]); } } sort(result.begin(), result.end()); return result; }
0
aamitprasad6183 days ago
CPP
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
int n=v1.size();
int m=v2.size();
int i=0;
int j=0;
vector<int>ans;
while(i<n && j<m){
if(v1[i]==v2[j]){
ans.push_back(v1[i]);
v1[i]=INT_MIN;
i++;
j++;
}
else if(v1[i] < v2[j]){
i++;
}
else{
j++;
}
}
return ans;
0
chaitankhilar1 week ago
why i need to optimize my code ?
ArrayList<Integer> al=new ArrayList<>(); Integer [] h=new Integer[v2.size()]; h=v2.toArray(h); for(int i=0;i<v2.size();i++){ if(v1.contains(h[i])==true){ al.add(h[i]); } } Collections.sort(al); return al;
0
harshjha51220012 weeks ago
vector<int> common_element(vector<int>v1,vector<int>v2) { // Your code here unordered_map<int,int>ump; vector<int>v; for(auto i:v1) ump[i]++; for(auto i:v2) { if(ump.find(i)!=ump.end()) { if(ump[i]!=0) { v.push_back(i); ump[i]--; } } } sort(v.begin() , v.end());
return v; }
0
jangleshubham132 weeks ago
C++ 0.55/4.16 - Bruteforce + Optimisation
// Method 1: Bruteforce. TC: O(M*N) SC: O(N)
vector<int> common_element1(vector<int>v1,vector<int>v2) {
vector<int> ans;
int n = v1.size();
int m = v2.size();
for(int i=0; i<n; i++) { //N*M
for(int j=0; j<m; j++) {
if(v1[i] == v2[j]) {
ans.push_back(v1[i]);
v1[i] = INT_MIN;
break;
}
}
}
sort(ans.begin(), ans.end()); //NlogN
return ans;
}
// Method 2: Sorting both array. TC: O(NlogN) Sc: O(N)
// - Sort both the arrays
// - Two pointers while(a<n && b<m)
// - if match add to ans or else if v1[a] < v2[b] a++; else b++;
vector<int> common_element(vector<int>v1,vector<int>v2) {
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
int n = v1.size();
int m = v2.size();
int i=0;
int j=0;
vector<int> ans;
while(i<n && j<m) {
if(v1[i] == v2[j]) {
ans.push_back(v1[i]);
v1[i] = INT_MIN;
i++;
j++;
} else if(v1[i] < v2[j]) {
i++;
} else {
j++;
}
}
return ans;
}
0
saitp992 weeks ago
C++
vector<int> common_element(vector<int>v1,vector<int>v2) { // Your code here vector<int>res; map<int,int>mp; for(auto i:v1) mp[i]++; for(auto i:v2) { if(mp[i]>=1) { res.push_back(i); mp[i]--; } } sort(res.begin(),res.end()); return res; }
-1
skzaid96412 weeks ago
//Time taken:3.01s/7.7s
public static ArrayList<Integer> common_element(ArrayList<Integer>v1, ArrayList<Integer>v2)
{
Map<Integer,Integer> store = new HashMap<>();
ArrayList<Integer> res = new ArrayList<Integer>();
for(int i=0;i<v1.size();i++)
store.put(v1.get(i),store.getOrDefault(v1.get(i),0)+1);
for(int i=0;i<v2.size();i++){
int ele = v2.get(i);
if(store.containsKey(ele)){
int curr = store.get(ele)-1;
if(curr==0)
store.remove(ele);
else
store.put(ele,curr);
res.add(ele);
}
}
Collections.sort(res);
return res;
}
0
codernikhil2262 weeks ago
class Solution{
public:
vector<int> common_element(vector<int> v1, vector<int> v2)
{
// Your code here
map<int, int> m1;
vector<int> ans;
for (int i = 0; i < v1.size(); i++) m1[v1[i]]++;
for (int i = 0; i < v2.size(); i++) {
if (m1.find(v2[i]) != m1.end()) {
ans.push_back(v2[i]);
m1[v2[i]]--;
}
if (m1[v2[i]] == 0) m1.erase(v2[i]);
}
sort(ans.begin(), ans.end());
return ans;
}
};
0
kvatsadeo3 weeks ago
public:
vector<int> common_element(vector<int>v1,vector<int>v2)
{
// Your code here
vector<int> v;
unordered_map<int,int> umap;
for(int i=0;i<v1.size();i++){
umap[v1[i]]++;
}
for(int i=0;i<v2.size();i++){
if(umap.find(v2[i])!=umap.end() && umap[v2[i]]>0){
v.push_back(v2[i]);
umap[v2[i]]--;
}
}
sort(v.begin(),v.end());
return v;
}
0
rajatk3 weeks ago
class Solution{
public:
vector<int> common_element(vector<int>v1,vector<int>v2)
{ map<int,int> mp;vector<int> v;
for(auto i: v1) mp[i]++;
for(auto i: v2)
if(mp[i]) v.push_back(i),mp[i]--;
sort(v.begin(),v.end());
return v;
// Your code here
}
};
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 417,
"s": 226,
"text": "Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list."
},
{
"code": null,
"e": 426,
"s": 417,
"text": "Example:"
},
{
"code": null,
"e": 563,
"s": 426,
"text": "Input:\nn = 5\nv1[] = {3, 4, 2, 2, 4}\nm = 4\nv2[] = {3, 2, 2, 7}\nOutput:\n2 2 3\nExplanation:\nThe common elements in sorted order are {2 2 3}"
},
{
"code": null,
"e": 731,
"s": 563,
"text": "Your Task:\nThis is a function problem. You need to complete the function common_element that takes both the lists as parameters and returns a list of common elements. "
},
{
"code": null,
"e": 772,
"s": 731,
"text": "Constraints:\n1 ≤ n, m ≤ 105\n1 ≤ Vi ≤ 105"
},
{
"code": null,
"e": 774,
"s": 772,
"text": "0"
},
{
"code": null,
"e": 795,
"s": 774,
"text": "mayank2021in 8 hours"
},
{
"code": null,
"e": 1398,
"s": 795,
"text": "C++ : 0.55/4.16 vector<int> common_element(vector<int>v1,vector<int>v2) { //may2021 unordered_map<int, int>mp; vector<int>result; int n1=v1.size(), n2=v2.size(); for(int i=0; i<n1 ; i++) mp[v1[i]]++; for(int i=0; i<n2 ; i++) { if(mp.find(v2[i])!=mp.end()) { result.push_back(v2[i]); mp[v2[i]]--; if(mp[v2[i]]==0) mp.erase(v2[i]); } } sort(result.begin(), result.end()); return result; }"
},
{
"code": null,
"e": 1400,
"s": 1398,
"text": "0"
},
{
"code": null,
"e": 1425,
"s": 1400,
"text": "aamitprasad6183 days ago"
},
{
"code": null,
"e": 1429,
"s": 1425,
"text": "CPP"
},
{
"code": null,
"e": 1956,
"s": 1431,
"text": "sort(v1.begin(),v1.end());\n sort(v2.begin(),v2.end());\n \n int n=v1.size();\n int m=v2.size();\n \n int i=0;\n int j=0;\n \n vector<int>ans;\n \n while(i<n && j<m){\n if(v1[i]==v2[j]){\n ans.push_back(v1[i]);\n v1[i]=INT_MIN;\n i++;\n j++;\n }\n else if(v1[i] < v2[j]){\n i++;\n }\n else{\n j++;\n }\n }\n \n return ans;"
},
{
"code": null,
"e": 1958,
"s": 1956,
"text": "0"
},
{
"code": null,
"e": 1982,
"s": 1958,
"text": "chaitankhilar1 week ago"
},
{
"code": null,
"e": 2015,
"s": 1982,
"text": "why i need to optimize my code ?"
},
{
"code": null,
"e": 2291,
"s": 2015,
"text": " ArrayList<Integer> al=new ArrayList<>(); Integer [] h=new Integer[v2.size()]; h=v2.toArray(h); for(int i=0;i<v2.size();i++){ if(v1.contains(h[i])==true){ al.add(h[i]); } } Collections.sort(al); return al;"
},
{
"code": null,
"e": 2293,
"s": 2291,
"text": "0"
},
{
"code": null,
"e": 2320,
"s": 2293,
"text": "harshjha51220012 weeks ago"
},
{
"code": null,
"e": 2729,
"s": 2320,
"text": "vector<int> common_element(vector<int>v1,vector<int>v2) { // Your code here unordered_map<int,int>ump; vector<int>v; for(auto i:v1) ump[i]++; for(auto i:v2) { if(ump.find(i)!=ump.end()) { if(ump[i]!=0) { v.push_back(i); ump[i]--; } } } sort(v.begin() , v.end());"
},
{
"code": null,
"e": 2757,
"s": 2729,
"text": " return v; }"
},
{
"code": null,
"e": 2759,
"s": 2757,
"text": "0"
},
{
"code": null,
"e": 2786,
"s": 2759,
"text": "jangleshubham132 weeks ago"
},
{
"code": null,
"e": 2828,
"s": 2786,
"text": "C++ 0.55/4.16 - Bruteforce + Optimisation"
},
{
"code": null,
"e": 4025,
"s": 2830,
"text": "// Method 1: Bruteforce. TC: O(M*N) SC: O(N)\n vector<int> common_element1(vector<int>v1,vector<int>v2) {\n vector<int> ans;\n int n = v1.size();\n int m = v2.size();\n for(int i=0; i<n; i++) {\t\t\t//N*M\n \tfor(int j=0; j<m; j++) {\n \t\tif(v1[i] == v2[j]) {\n \t\t\tans.push_back(v1[i]);\n \t\t\tv1[i] = INT_MIN;\n \t\t\tbreak;\n \t\t}\n \t}\n }\n\n sort(ans.begin(), ans.end());\t\t//NlogN\n return ans;\n }\n\n\n\t// Method 2: Sorting both array. TC: O(NlogN) Sc: O(N)\n\t// \t- Sort both the arrays\n\t// \t- Two pointers while(a<n && b<m)\n\t// \t- if match add to ans or else if v1[a] < v2[b] a++; else b++;\n vector<int> common_element(vector<int>v1,vector<int>v2) {\n sort(v1.begin(), v1.end());\n sort(v2.begin(), v2.end());\n int n = v1.size();\n int m = v2.size();\n\n int i=0;\n int j=0;\n\n vector<int> ans;\n while(i<n && j<m) {\n \tif(v1[i] == v2[j]) {\n \t\tans.push_back(v1[i]);\n \t\tv1[i] = INT_MIN;\n \t\ti++;\n \t\tj++;\n \t} else if(v1[i] < v2[j]) {\n \t\ti++;\n \t} else {\n \t\tj++;\n \t}\n }\n\n \treturn ans;\n }"
},
{
"code": null,
"e": 4027,
"s": 4025,
"text": "0"
},
{
"code": null,
"e": 4046,
"s": 4027,
"text": "saitp992 weeks ago"
},
{
"code": null,
"e": 4050,
"s": 4046,
"text": "C++"
},
{
"code": null,
"e": 4412,
"s": 4052,
"text": "vector<int> common_element(vector<int>v1,vector<int>v2) { // Your code here vector<int>res; map<int,int>mp; for(auto i:v1) mp[i]++; for(auto i:v2) { if(mp[i]>=1) { res.push_back(i); mp[i]--; } } sort(res.begin(),res.end()); return res; }"
},
{
"code": null,
"e": 4415,
"s": 4412,
"text": "-1"
},
{
"code": null,
"e": 4437,
"s": 4415,
"text": "skzaid96412 weeks ago"
},
{
"code": null,
"e": 5204,
"s": 4437,
"text": "//Time taken:3.01s/7.7s\npublic static ArrayList<Integer> common_element(ArrayList<Integer>v1, ArrayList<Integer>v2)\n {\n Map<Integer,Integer> store = new HashMap<>();\n ArrayList<Integer> res = new ArrayList<Integer>();\n \n for(int i=0;i<v1.size();i++)\n store.put(v1.get(i),store.getOrDefault(v1.get(i),0)+1);\n \n for(int i=0;i<v2.size();i++){\n int ele = v2.get(i);\n if(store.containsKey(ele)){\n int curr = store.get(ele)-1;\n if(curr==0)\n store.remove(ele);\n else\n store.put(ele,curr);\n res.add(ele);\n }\n }\n \n Collections.sort(res);\n return res;\n }"
},
{
"code": null,
"e": 5206,
"s": 5204,
"text": "0"
},
{
"code": null,
"e": 5232,
"s": 5206,
"text": "codernikhil2262 weeks ago"
},
{
"code": null,
"e": 5798,
"s": 5232,
"text": "class Solution{\n public:\n vector<int> common_element(vector<int> v1, vector<int> v2)\n {\n // Your code here\n \n map<int, int> m1;\n vector<int> ans;\n \n for (int i = 0; i < v1.size(); i++) m1[v1[i]]++;\n for (int i = 0; i < v2.size(); i++) {\n if (m1.find(v2[i]) != m1.end()) {\n ans.push_back(v2[i]);\n m1[v2[i]]--;\n }\n if (m1[v2[i]] == 0) m1.erase(v2[i]);\n }\n \n sort(ans.begin(), ans.end());\n return ans;\n \n }\n};"
},
{
"code": null,
"e": 5800,
"s": 5798,
"text": "0"
},
{
"code": null,
"e": 5821,
"s": 5800,
"text": "kvatsadeo3 weeks ago"
},
{
"code": null,
"e": 6311,
"s": 5821,
"text": " public:\n vector<int> common_element(vector<int>v1,vector<int>v2)\n {\n // Your code here\n vector<int> v;\n unordered_map<int,int> umap;\n for(int i=0;i<v1.size();i++){\n umap[v1[i]]++;\n }\n for(int i=0;i<v2.size();i++){\n if(umap.find(v2[i])!=umap.end() && umap[v2[i]]>0){\n v.push_back(v2[i]);\n umap[v2[i]]--;\n }\n }\n sort(v.begin(),v.end());\n return v;\n }"
},
{
"code": null,
"e": 6313,
"s": 6311,
"text": "0"
},
{
"code": null,
"e": 6331,
"s": 6313,
"text": "rajatk3 weeks ago"
},
{
"code": null,
"e": 6650,
"s": 6331,
"text": "class Solution{\n public:\n vector<int> common_element(vector<int>v1,vector<int>v2)\n { map<int,int> mp;vector<int> v;\n for(auto i: v1) mp[i]++;\n for(auto i: v2)\n if(mp[i]) v.push_back(i),mp[i]--;\n sort(v.begin(),v.end());\n return v;\n \n // Your code here\n }\n};"
},
{
"code": null,
"e": 6796,
"s": 6650,
"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": 6832,
"s": 6796,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6842,
"s": 6832,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6852,
"s": 6842,
"text": "\nContest\n"
},
{
"code": null,
"e": 6915,
"s": 6852,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7100,
"s": 6915,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7384,
"s": 7100,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 7530,
"s": 7384,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 7607,
"s": 7530,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 7648,
"s": 7607,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 7676,
"s": 7648,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 7747,
"s": 7676,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 7934,
"s": 7747,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
PointNet – Deep Learning
|
08 Jun, 2021
PointNet was proposed by a researcher at Stanford University in 2016. The motivation behind this paper is to classify and segment 3D representation of images. They use a data structure called Point cloud, which is a set of the point that represents a 3D shape or an object. Due to its irregularities, it is only suitable for a particular use case.
Many authors converted the point cloud into some other representation called voxel (volumetric pixel) before it is fed into the Deep neural networks. However, such transformation leads data too voluminous, and introducing quantization to the 3D structure can also lead to variance from natural artifacts.
In this paper, the author proposes a novel method for directly consuming Point clouds and output the relevant classification of image or segmentation.
The author proposes an architecture that takes Point Sets from Point cloud as input. The point cloud is represented by a set of 3D-points Pi where each point is represented as(xi, yi, zi).
For the object classification task, the input point cloud is directly sampled from the shape or pre-segmented from the scene point cloud. For semantic segmentation, the input can be a single object from the part region segmentation or a small part of 3D scene from the Object region segmentation.
Some properties of Point Sets are:
Permutation Invariance: Since the points in the point cloud is unstructured, a scan of N points has N! different permutations. The data processing must be invariant to different permutated representations of Point Cloud.
Transformation invariance: The classification and segmentation output can not be impacted by different transformations like rotation and translation.
Interaction b/w different Points: The connections between neighboring points often carries useful information. Therefore, each point should not be treated in isolation. These interactions can play a more useful role in segmentation than classification.
PointNet architecture
The PointNet architecture is quite intuitive. The classification network uses a shared multi-layer perceptron to map each of the n points from 3 dimensions to 64-dimension. It’s important that a single multi-layer perceptron is shared for each of the n points. Similarly, in the next layer, each n point is mapped from 64 dimensions to 1024 dimensions. Now, we apply max-pooling to create a global feature vector in R1024. Finally, a three-layer fully-connected network (FCNs) is used to map the global feature vector to k output classification scores.
Pointnet architecture
For the segmentation network, each of the n inputs needs to assign, one of the m segmentation classes, because segmentation relies on local and global features, the points in the 64-dimensional space are concatenated with the global feature space, resulting in possible feature space of n * R1088.
The PointNet architecture has these key modules: the max-pooling layer, a local and global combination structure, and two joint alignment networks that align both local and global networks. Similar to per point
To make a model invariant from the permutation, three strategies exist:
Sort input into canonical order.
Treat the input as a sequence to train the RNN
Use a simple symmetric function to aggregate the information from each point.
Below is an example of symmetric function
where
h here can be multi-layer perceptron, g is a composition of single variable function and a max-pooling function and f can be the output layer.
The output from the above section forms a vector [f1, f2, ....fn], i.e the global signature of the input set. Now, this will work fine as we can easily train the SVM to make a classifier output. But, for the point segmentation, we require a combination of both local and global features.
To get the desired result, after computing the global feature vector the authors feed it back to the point feature by concatenating global features with per point features (see in the above image of architecture). This method is able to predict per point quantities that relies both on global semantics and local features
The semantic labeling of the point cloud has to be geometric transformation invariant (i.e. invariant of any rotation, translation etc.). The author uses a mini-network to predict the affine transformation matrix and applies this transformation to the coordinates of the input point.
In the final step of T-net, The input dependent features at the final fully connected layer of T-net are combined with globally trainable weights and biases resulting in a 3×3 transformation matrix.
The concept of pose normalization extended to 64-d embedding space. The T-net is similar to the above figure except for nearly, except for an increase in the dimensionality of trainable weights and biases which becomes 256*4096*4096 respectively returning in a 64*64 transformation matrix. The increased number of trainable leads to overfitting, that’s why the authors introduced a regularization term that encourages the resulting 64*64 transformation.
Python3
# codeimport osimport datetimeimport globimport trimeshimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersimport matplotlib.pyplot as plt tf.random.set_seed(1) # Load modelDATA_DIR = tf.keras.utils.get_file( "modelnet.zip", "http://3dvision.princeton.edu/projects/2014/3DShapeNets/ModelNet10.zip", extract=True,)DATA_DIR = os.path.join(os.path.dirname(DATA_DIR), "ModelNet10") mesh = trimesh.load(os.path.join(DATA_DIR, "chair/train/chair_0001.off")) # sample point frompoints = mesh.sample(2048)fig = plt.figure(figsize=(5, 5))ax = fig.add_subplot(111, projection="3d")ax.scatter(points[:, 0], points[:, 1], points[:, 2],color = 'red')ax.set_axis_off()plt.show() # function to parse datasetdef parse_dataset(num_points=2048): train_points = [] train_labels = [] test_points = [] test_labels = [] class_map = {} folders = glob.glob(os.path.join(DATA_DIR, "[!README]*")) for i, folder in enumerate(folders): print("processing class: {}".format(os.path.basename(folder))) # store folder name with ID so we can retrieve later class_map[i] = folder.split("/")[-1] # gather all files train_files = glob.glob(os.path.join(folder, "train/*")) test_files = glob.glob(os.path.join(folder, "test/*")) for f in train_files: train_points.append(trimesh.load(f).sample(num_points)) train_labels.append(i) for f in test_files: test_points.append(trimesh.load(f).sample(num_points)) test_labels.append(i) return ( np.array(train_points), np.array(test_points), np.array(train_labels), np.array(test_labels), class_map, ) class OrthogonalRegularizer(keras.regularizers.Regularizer): def __init__(self, num_features, l2reg=0.001): self.num_features = num_features self.l2reg = l2reg self.eye = tf.eye(num_features) def __call__(self, x): x = tf.reshape(x, (-1, self.num_features, self.num_features)) xxt = tf.tensordot(x, x, axes=(2, 2)) xxt = tf.reshape(xxt, (-1, self.num_features, self.num_features)) return tf.reduce_sum(self.l2reg * tf.square(xxt - self.eye))# Create the T-net modeldef t_net(inputs, num_features): # Initialise bias as the indentity matrix bias = keras.initializers.Constant(np.eye(num_features).flatten()) reg = OrthogonalRegularizer(num_features) x = conv_bn(inputs, 32) x = conv_bn(x, 64) x = conv_bn(x, 512) x = layers.GlobalMaxPooling1D()(x) x = dense_bn(x, 256) x = dense_bn(x, 128) x = layers.Dense( num_features * num_features, kernel_initializer="zeros", bias_initializer=bias, activity_regularizer=reg, )(x) feat_T = layers.Reshape((num_features, num_features))(x) # Apply affine transformation to input features return layers.Dot(axes=(2, 1))([inputs, feat_T]) # the main modelinputs = keras.Input(shape=(NUM_POINTS, 3)) x = t_net(inputs, 3)x = conv_bn(x, 32)x = conv_bn(x, 32)x = t_net(x, 32)x = conv_bn(x, 32)x = conv_bn(x, 64)x = conv_bn(x, 512)x =layers.GlobalMaxPooling1D()(x)x = dense_bn(x, 256)x = layers.Dropout(0.3)(x)x = dense_bn(x, 128)x = layers.Dropout(0.3)(x) outputs = layers.Dense(NUM_CLASSES, activation="softmax")(x) model = keras.Model(inputs=inputs, outputs=outputs, name="pointnet")model.summary() %load_ext tensorboard # compile and train the modelmodel.compile( loss="sparse_categorical_crossentropy", optimizer=keras.optimizers.Adam(learning_rate=0.001), metrics=["sparse_categorical_accuracy"],)log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)print(log_dir)model.fit(train_dataset, epochs=30, validation_data=test_dataset, callbacks=[tensorboard_callback])
logs/fit/20210309-060624
WARNING:tensorflow:Model failed to serialize as JSON. Ignoring... <__main__.OrthogonalRegularizer object at 0x7fc3ecd25790> does not implement get_config()
Epoch 1/30
125/125 [==============================] - 36s 251ms/step - loss: 3.9923 - sparse_categorical_accuracy: 0.2046 - val_loss: 43220470648012800.0000 - val_sparse_categorical_accuracy: 0.2687
Epoch 2/30
125/125 [==============================] - 30s 239ms/step - loss: 3.1246 - sparse_categorical_accuracy: 0.3611 - val_loss: 12.8184 - val_sparse_categorical_accuracy: 0.2137
Epoch 3/30
125/125 [==============================] - 30s 239ms/step - loss: 2.8952 - sparse_categorical_accuracy: 0.4318 - val_loss: 3.3341 - val_sparse_categorical_accuracy: 0.1707
Epoch 4/30
125/125 [==============================] - 30s 239ms/step - loss: 2.6418 - sparse_categorical_accuracy: 0.4795 - val_loss: 268835504128.0000 - val_sparse_categorical_accuracy: 0.4747
Epoch 5/30
125/125 [==============================] - 30s 239ms/step - loss: 2.5744 - sparse_categorical_accuracy: 0.5262 - val_loss: 1399391744.0000 - val_sparse_categorical_accuracy: 0.5165
Epoch 6/30
125/125 [==============================] - 30s 239ms/step - loss: 2.3542 - sparse_categorical_accuracy: 0.6136 - val_loss: 911933.9375 - val_sparse_categorical_accuracy: 0.5936
Epoch 7/30
125/125 [==============================] - 30s 239ms/step - loss: 2.2442 - sparse_categorical_accuracy: 0.6602 - val_loss: 257217894776045568.0000 - val_sparse_categorical_accuracy: 0.6410
Epoch 8/30
125/125 [==============================] - 30s 238ms/step - loss: 2.1114 - sparse_categorical_accuracy: 0.6685 - val_loss: 50140152856576.0000 - val_sparse_categorical_accuracy: 0.6960
Epoch 9/30
125/125 [==============================] - 30s 239ms/step - loss: 2.0264 - sparse_categorical_accuracy: 0.6971 - val_loss: 117848482353512448.0000 - val_sparse_categorical_accuracy: 0.7159
Epoch 10/30
125/125 [==============================] - 30s 239ms/step - loss: 2.0393 - sparse_categorical_accuracy: 0.6928 - val_loss: 2660748754944.0000 - val_sparse_categorical_accuracy: 0.6322
Epoch 11/30
125/125 [==============================] - 30s 239ms/step - loss: 1.9129 - sparse_categorical_accuracy: 0.7376 - val_loss: 20.5381 - val_sparse_categorical_accuracy: 0.7048
Epoch 12/30
125/125 [==============================] - 30s 238ms/step - loss: 1.8221 - sparse_categorical_accuracy: 0.7659 - val_loss: 534893165459537920.0000 - val_sparse_categorical_accuracy: 0.7148
Epoch 13/30
125/125 [==============================] - 30s 239ms/step - loss: 1.7931 - sparse_categorical_accuracy: 0.7741 - val_loss: 14077352313094144.0000 - val_sparse_categorical_accuracy: 0.7192
Epoch 14/30
125/125 [==============================] - 30s 239ms/step - loss: 1.7970 - sparse_categorical_accuracy: 0.7683 - val_loss: 9279.2363 - val_sparse_categorical_accuracy: 0.7808
Epoch 15/30
125/125 [==============================] - 30s 239ms/step - loss: 1.7285 - sparse_categorical_accuracy: 0.7924 - val_loss: 8201817088.0000 - val_sparse_categorical_accuracy: 0.8304
Epoch 16/30
125/125 [==============================] - 30s 238ms/step - loss: 1.7426 - sparse_categorical_accuracy: 0.7912 - val_loss: 1834421736964096.0000 - val_sparse_categorical_accuracy: 0.7555
Epoch 17/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6427 - sparse_categorical_accuracy: 0.8237 - val_loss: 309827239936.0000 - val_sparse_categorical_accuracy: 0.7610
Epoch 18/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6883 - sparse_categorical_accuracy: 0.8182 - val_loss: 12362231232444401451008.0000 - val_sparse_categorical_accuracy: 0.6740
Epoch 19/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6198 - sparse_categorical_accuracy: 0.8378 - val_loss: 168301294885625921536.0000 - val_sparse_categorical_accuracy: 0.7048
Epoch 20/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6321 - sparse_categorical_accuracy: 0.8265 - val_loss: 34155740306341888.0000 - val_sparse_categorical_accuracy: 0.7963
Epoch 21/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6206 - sparse_categorical_accuracy: 0.8237 - val_loss: 73268587348667400192.0000 - val_sparse_categorical_accuracy: 0.7874
Epoch 22/30
125/125 [==============================] - 30s 238ms/step - loss: 1.5612 - sparse_categorical_accuracy: 0.8497 - val_loss: 1441606803694551040.0000 - val_sparse_categorical_accuracy: 0.8007
Epoch 23/30
125/125 [==============================] - 30s 238ms/step - loss: 1.6024 - sparse_categorical_accuracy: 0.8288 - val_loss: 672064995328.0000 - val_sparse_categorical_accuracy: 0.8249
Epoch 24/30
125/125 [==============================] - 30s 238ms/step - loss: 1.5145 - sparse_categorical_accuracy: 0.8572 - val_loss: 416892130609315446784.0000 - val_sparse_categorical_accuracy: 0.8040
Epoch 25/30
125/125 [==============================] - 30s 239ms/step - loss: 1.5235 - sparse_categorical_accuracy: 0.8531 - val_loss: 13480175.0000 - val_sparse_categorical_accuracy: 0.8403
Epoch 26/30
125/125 [==============================] - 30s 238ms/step - loss: 1.5077 - sparse_categorical_accuracy: 0.8588 - val_loss: 8007.9917 - val_sparse_categorical_accuracy: 0.6123
Epoch 27/30
125/125 [==============================] - 30s 239ms/step - loss: 1.5592 - sparse_categorical_accuracy: 0.8402 - val_loss: 2.1578 - val_sparse_categorical_accuracy: 0.6564
Epoch 28/30
125/125 [==============================] - 30s 238ms/step - loss: 1.5293 - sparse_categorical_accuracy: 0.8555 - val_loss: 12311261760978944.0000 - val_sparse_categorical_accuracy: 0.8337
Epoch 29/30
125/125 [==============================] - 30s 238ms/step - loss: 1.5008 - sparse_categorical_accuracy: 0.8716 - val_loss: 302755749388353536.0000 - val_sparse_categorical_accuracy: 0.7907
Epoch 30/30
125/125 [==============================] - 30s 238ms/step - loss: 1.4952 - sparse_categorical_accuracy: 0.8661 - val_loss: 10193839104.0000 - val_sparse_categorical_accuracy: 0.8767
3D-Mesh (cannot visualize here because of dimension constraint)
Point cloud
TensorFlow Graph
Classification result
PointNet
saurabh1990aror
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Support Vector Machine Algorithm
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Types of Environments in AI
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Difference between Informed and Uninformed Search in AI
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 376,
"s": 28,
"text": "PointNet was proposed by a researcher at Stanford University in 2016. The motivation behind this paper is to classify and segment 3D representation of images. They use a data structure called Point cloud, which is a set of the point that represents a 3D shape or an object. Due to its irregularities, it is only suitable for a particular use case."
},
{
"code": null,
"e": 681,
"s": 376,
"text": "Many authors converted the point cloud into some other representation called voxel (volumetric pixel) before it is fed into the Deep neural networks. However, such transformation leads data too voluminous, and introducing quantization to the 3D structure can also lead to variance from natural artifacts."
},
{
"code": null,
"e": 832,
"s": 681,
"text": "In this paper, the author proposes a novel method for directly consuming Point clouds and output the relevant classification of image or segmentation."
},
{
"code": null,
"e": 1021,
"s": 832,
"text": "The author proposes an architecture that takes Point Sets from Point cloud as input. The point cloud is represented by a set of 3D-points Pi where each point is represented as(xi, yi, zi)."
},
{
"code": null,
"e": 1318,
"s": 1021,
"text": "For the object classification task, the input point cloud is directly sampled from the shape or pre-segmented from the scene point cloud. For semantic segmentation, the input can be a single object from the part region segmentation or a small part of 3D scene from the Object region segmentation."
},
{
"code": null,
"e": 1353,
"s": 1318,
"text": "Some properties of Point Sets are:"
},
{
"code": null,
"e": 1574,
"s": 1353,
"text": "Permutation Invariance: Since the points in the point cloud is unstructured, a scan of N points has N! different permutations. The data processing must be invariant to different permutated representations of Point Cloud."
},
{
"code": null,
"e": 1724,
"s": 1574,
"text": "Transformation invariance: The classification and segmentation output can not be impacted by different transformations like rotation and translation."
},
{
"code": null,
"e": 1977,
"s": 1724,
"text": "Interaction b/w different Points: The connections between neighboring points often carries useful information. Therefore, each point should not be treated in isolation. These interactions can play a more useful role in segmentation than classification."
},
{
"code": null,
"e": 1999,
"s": 1977,
"text": "PointNet architecture"
},
{
"code": null,
"e": 2553,
"s": 1999,
"text": "The PointNet architecture is quite intuitive. The classification network uses a shared multi-layer perceptron to map each of the n points from 3 dimensions to 64-dimension. It’s important that a single multi-layer perceptron is shared for each of the n points. Similarly, in the next layer, each n point is mapped from 64 dimensions to 1024 dimensions. Now, we apply max-pooling to create a global feature vector in R1024. Finally, a three-layer fully-connected network (FCNs) is used to map the global feature vector to k output classification scores. "
},
{
"code": null,
"e": 2575,
"s": 2553,
"text": "Pointnet architecture"
},
{
"code": null,
"e": 2873,
"s": 2575,
"text": "For the segmentation network, each of the n inputs needs to assign, one of the m segmentation classes, because segmentation relies on local and global features, the points in the 64-dimensional space are concatenated with the global feature space, resulting in possible feature space of n * R1088."
},
{
"code": null,
"e": 3085,
"s": 2873,
"text": "The PointNet architecture has these key modules: the max-pooling layer, a local and global combination structure, and two joint alignment networks that align both local and global networks. Similar to per point "
},
{
"code": null,
"e": 3157,
"s": 3085,
"text": "To make a model invariant from the permutation, three strategies exist:"
},
{
"code": null,
"e": 3190,
"s": 3157,
"text": "Sort input into canonical order."
},
{
"code": null,
"e": 3237,
"s": 3190,
"text": "Treat the input as a sequence to train the RNN"
},
{
"code": null,
"e": 3315,
"s": 3237,
"text": "Use a simple symmetric function to aggregate the information from each point."
},
{
"code": null,
"e": 3357,
"s": 3315,
"text": "Below is an example of symmetric function"
},
{
"code": null,
"e": 3366,
"s": 3359,
"text": "where "
},
{
"code": null,
"e": 3513,
"s": 3370,
"text": "h here can be multi-layer perceptron, g is a composition of single variable function and a max-pooling function and f can be the output layer."
},
{
"code": null,
"e": 3805,
"s": 3517,
"text": "The output from the above section forms a vector [f1, f2, ....fn], i.e the global signature of the input set. Now, this will work fine as we can easily train the SVM to make a classifier output. But, for the point segmentation, we require a combination of both local and global features."
},
{
"code": null,
"e": 4129,
"s": 3807,
"text": "To get the desired result, after computing the global feature vector the authors feed it back to the point feature by concatenating global features with per point features (see in the above image of architecture). This method is able to predict per point quantities that relies both on global semantics and local features"
},
{
"code": null,
"e": 4417,
"s": 4133,
"text": "The semantic labeling of the point cloud has to be geometric transformation invariant (i.e. invariant of any rotation, translation etc.). The author uses a mini-network to predict the affine transformation matrix and applies this transformation to the coordinates of the input point."
},
{
"code": null,
"e": 4618,
"s": 4419,
"text": "In the final step of T-net, The input dependent features at the final fully connected layer of T-net are combined with globally trainable weights and biases resulting in a 3×3 transformation matrix."
},
{
"code": null,
"e": 5074,
"s": 4620,
"text": "The concept of pose normalization extended to 64-d embedding space. The T-net is similar to the above figure except for nearly, except for an increase in the dimensionality of trainable weights and biases which becomes 256*4096*4096 respectively returning in a 64*64 transformation matrix. The increased number of trainable leads to overfitting, that’s why the authors introduced a regularization term that encourages the resulting 64*64 transformation."
},
{
"code": null,
"e": 5088,
"s": 5080,
"text": "Python3"
},
{
"code": "# codeimport osimport datetimeimport globimport trimeshimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersimport matplotlib.pyplot as plt tf.random.set_seed(1) # Load modelDATA_DIR = tf.keras.utils.get_file( \"modelnet.zip\", \"http://3dvision.princeton.edu/projects/2014/3DShapeNets/ModelNet10.zip\", extract=True,)DATA_DIR = os.path.join(os.path.dirname(DATA_DIR), \"ModelNet10\") mesh = trimesh.load(os.path.join(DATA_DIR, \"chair/train/chair_0001.off\")) # sample point frompoints = mesh.sample(2048)fig = plt.figure(figsize=(5, 5))ax = fig.add_subplot(111, projection=\"3d\")ax.scatter(points[:, 0], points[:, 1], points[:, 2],color = 'red')ax.set_axis_off()plt.show() # function to parse datasetdef parse_dataset(num_points=2048): train_points = [] train_labels = [] test_points = [] test_labels = [] class_map = {} folders = glob.glob(os.path.join(DATA_DIR, \"[!README]*\")) for i, folder in enumerate(folders): print(\"processing class: {}\".format(os.path.basename(folder))) # store folder name with ID so we can retrieve later class_map[i] = folder.split(\"/\")[-1] # gather all files train_files = glob.glob(os.path.join(folder, \"train/*\")) test_files = glob.glob(os.path.join(folder, \"test/*\")) for f in train_files: train_points.append(trimesh.load(f).sample(num_points)) train_labels.append(i) for f in test_files: test_points.append(trimesh.load(f).sample(num_points)) test_labels.append(i) return ( np.array(train_points), np.array(test_points), np.array(train_labels), np.array(test_labels), class_map, ) class OrthogonalRegularizer(keras.regularizers.Regularizer): def __init__(self, num_features, l2reg=0.001): self.num_features = num_features self.l2reg = l2reg self.eye = tf.eye(num_features) def __call__(self, x): x = tf.reshape(x, (-1, self.num_features, self.num_features)) xxt = tf.tensordot(x, x, axes=(2, 2)) xxt = tf.reshape(xxt, (-1, self.num_features, self.num_features)) return tf.reduce_sum(self.l2reg * tf.square(xxt - self.eye))# Create the T-net modeldef t_net(inputs, num_features): # Initialise bias as the indentity matrix bias = keras.initializers.Constant(np.eye(num_features).flatten()) reg = OrthogonalRegularizer(num_features) x = conv_bn(inputs, 32) x = conv_bn(x, 64) x = conv_bn(x, 512) x = layers.GlobalMaxPooling1D()(x) x = dense_bn(x, 256) x = dense_bn(x, 128) x = layers.Dense( num_features * num_features, kernel_initializer=\"zeros\", bias_initializer=bias, activity_regularizer=reg, )(x) feat_T = layers.Reshape((num_features, num_features))(x) # Apply affine transformation to input features return layers.Dot(axes=(2, 1))([inputs, feat_T]) # the main modelinputs = keras.Input(shape=(NUM_POINTS, 3)) x = t_net(inputs, 3)x = conv_bn(x, 32)x = conv_bn(x, 32)x = t_net(x, 32)x = conv_bn(x, 32)x = conv_bn(x, 64)x = conv_bn(x, 512)x =layers.GlobalMaxPooling1D()(x)x = dense_bn(x, 256)x = layers.Dropout(0.3)(x)x = dense_bn(x, 128)x = layers.Dropout(0.3)(x) outputs = layers.Dense(NUM_CLASSES, activation=\"softmax\")(x) model = keras.Model(inputs=inputs, outputs=outputs, name=\"pointnet\")model.summary() %load_ext tensorboard # compile and train the modelmodel.compile( loss=\"sparse_categorical_crossentropy\", optimizer=keras.optimizers.Adam(learning_rate=0.001), metrics=[\"sparse_categorical_accuracy\"],)log_dir = \"logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)print(log_dir)model.fit(train_dataset, epochs=30, validation_data=test_dataset, callbacks=[tensorboard_callback])",
"e": 8975,
"s": 5088,
"text": null
},
{
"code": null,
"e": 15019,
"s": 8975,
"text": "logs/fit/20210309-060624\nWARNING:tensorflow:Model failed to serialize as JSON. Ignoring... <__main__.OrthogonalRegularizer object at 0x7fc3ecd25790> does not implement get_config()\nEpoch 1/30\n125/125 [==============================] - 36s 251ms/step - loss: 3.9923 - sparse_categorical_accuracy: 0.2046 - val_loss: 43220470648012800.0000 - val_sparse_categorical_accuracy: 0.2687\nEpoch 2/30\n125/125 [==============================] - 30s 239ms/step - loss: 3.1246 - sparse_categorical_accuracy: 0.3611 - val_loss: 12.8184 - val_sparse_categorical_accuracy: 0.2137\nEpoch 3/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.8952 - sparse_categorical_accuracy: 0.4318 - val_loss: 3.3341 - val_sparse_categorical_accuracy: 0.1707\nEpoch 4/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.6418 - sparse_categorical_accuracy: 0.4795 - val_loss: 268835504128.0000 - val_sparse_categorical_accuracy: 0.4747\nEpoch 5/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.5744 - sparse_categorical_accuracy: 0.5262 - val_loss: 1399391744.0000 - val_sparse_categorical_accuracy: 0.5165\nEpoch 6/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.3542 - sparse_categorical_accuracy: 0.6136 - val_loss: 911933.9375 - val_sparse_categorical_accuracy: 0.5936\nEpoch 7/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.2442 - sparse_categorical_accuracy: 0.6602 - val_loss: 257217894776045568.0000 - val_sparse_categorical_accuracy: 0.6410\nEpoch 8/30\n125/125 [==============================] - 30s 238ms/step - loss: 2.1114 - sparse_categorical_accuracy: 0.6685 - val_loss: 50140152856576.0000 - val_sparse_categorical_accuracy: 0.6960\nEpoch 9/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.0264 - sparse_categorical_accuracy: 0.6971 - val_loss: 117848482353512448.0000 - val_sparse_categorical_accuracy: 0.7159\nEpoch 10/30\n125/125 [==============================] - 30s 239ms/step - loss: 2.0393 - sparse_categorical_accuracy: 0.6928 - val_loss: 2660748754944.0000 - val_sparse_categorical_accuracy: 0.6322\nEpoch 11/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.9129 - sparse_categorical_accuracy: 0.7376 - val_loss: 20.5381 - val_sparse_categorical_accuracy: 0.7048\nEpoch 12/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.8221 - sparse_categorical_accuracy: 0.7659 - val_loss: 534893165459537920.0000 - val_sparse_categorical_accuracy: 0.7148\nEpoch 13/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.7931 - sparse_categorical_accuracy: 0.7741 - val_loss: 14077352313094144.0000 - val_sparse_categorical_accuracy: 0.7192\nEpoch 14/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.7970 - sparse_categorical_accuracy: 0.7683 - val_loss: 9279.2363 - val_sparse_categorical_accuracy: 0.7808\nEpoch 15/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.7285 - sparse_categorical_accuracy: 0.7924 - val_loss: 8201817088.0000 - val_sparse_categorical_accuracy: 0.8304\nEpoch 16/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.7426 - sparse_categorical_accuracy: 0.7912 - val_loss: 1834421736964096.0000 - val_sparse_categorical_accuracy: 0.7555\nEpoch 17/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6427 - sparse_categorical_accuracy: 0.8237 - val_loss: 309827239936.0000 - val_sparse_categorical_accuracy: 0.7610\nEpoch 18/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6883 - sparse_categorical_accuracy: 0.8182 - val_loss: 12362231232444401451008.0000 - val_sparse_categorical_accuracy: 0.6740\nEpoch 19/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6198 - sparse_categorical_accuracy: 0.8378 - val_loss: 168301294885625921536.0000 - val_sparse_categorical_accuracy: 0.7048\nEpoch 20/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6321 - sparse_categorical_accuracy: 0.8265 - val_loss: 34155740306341888.0000 - val_sparse_categorical_accuracy: 0.7963\nEpoch 21/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6206 - sparse_categorical_accuracy: 0.8237 - val_loss: 73268587348667400192.0000 - val_sparse_categorical_accuracy: 0.7874\nEpoch 22/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.5612 - sparse_categorical_accuracy: 0.8497 - val_loss: 1441606803694551040.0000 - val_sparse_categorical_accuracy: 0.8007\nEpoch 23/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.6024 - sparse_categorical_accuracy: 0.8288 - val_loss: 672064995328.0000 - val_sparse_categorical_accuracy: 0.8249\nEpoch 24/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.5145 - sparse_categorical_accuracy: 0.8572 - val_loss: 416892130609315446784.0000 - val_sparse_categorical_accuracy: 0.8040\nEpoch 25/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.5235 - sparse_categorical_accuracy: 0.8531 - val_loss: 13480175.0000 - val_sparse_categorical_accuracy: 0.8403\nEpoch 26/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.5077 - sparse_categorical_accuracy: 0.8588 - val_loss: 8007.9917 - val_sparse_categorical_accuracy: 0.6123\nEpoch 27/30\n125/125 [==============================] - 30s 239ms/step - loss: 1.5592 - sparse_categorical_accuracy: 0.8402 - val_loss: 2.1578 - val_sparse_categorical_accuracy: 0.6564\nEpoch 28/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.5293 - sparse_categorical_accuracy: 0.8555 - val_loss: 12311261760978944.0000 - val_sparse_categorical_accuracy: 0.8337\nEpoch 29/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.5008 - sparse_categorical_accuracy: 0.8716 - val_loss: 302755749388353536.0000 - val_sparse_categorical_accuracy: 0.7907\nEpoch 30/30\n125/125 [==============================] - 30s 238ms/step - loss: 1.4952 - sparse_categorical_accuracy: 0.8661 - val_loss: 10193839104.0000 - val_sparse_categorical_accuracy: 0.8767"
},
{
"code": null,
"e": 15083,
"s": 15019,
"text": "3D-Mesh (cannot visualize here because of dimension constraint)"
},
{
"code": null,
"e": 15096,
"s": 15083,
"text": "Point cloud "
},
{
"code": null,
"e": 15113,
"s": 15096,
"text": "TensorFlow Graph"
},
{
"code": null,
"e": 15135,
"s": 15113,
"text": "Classification result"
},
{
"code": null,
"e": 15144,
"s": 15135,
"text": "PointNet"
},
{
"code": null,
"e": 15160,
"s": 15144,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 15177,
"s": 15160,
"text": "Machine Learning"
},
{
"code": null,
"e": 15194,
"s": 15177,
"text": "Machine Learning"
},
{
"code": null,
"e": 15292,
"s": 15194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15328,
"s": 15292,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 15369,
"s": 15328,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 15393,
"s": 15369,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 15426,
"s": 15393,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 15477,
"s": 15426,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 15510,
"s": 15477,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 15538,
"s": 15510,
"text": "Types of Environments in AI"
},
{
"code": null,
"e": 15578,
"s": 15538,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 15619,
"s": 15578,
"text": "Principal Component Analysis with Python"
}
] |
Scala String replace() method with example
|
03 Oct, 2019
The replace() method is used to replace the old character of the string with the new one which is stated in the argument.
Method Definition: String replace(char oldChar, char newChar)Return Type: It returns the stated string after replacing the old character with the new one.
Example #1:
// Scala program of replace()// method // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // Applying replace methodval result = "Nidhi".replace('N', 'n') // Displays outputprintln(result) }}
nidhi
Example #2:
// Scala program of replace()// method // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // Applying replace methodval result = "Nidhi".replace('h', '#') // Displays outputprintln(result) }}
Nid#i
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "The replace() method is used to replace the old character of the string with the new one which is stated in the argument."
},
{
"code": null,
"e": 305,
"s": 150,
"text": "Method Definition: String replace(char oldChar, char newChar)Return Type: It returns the stated string after replacing the old character with the new one."
},
{
"code": null,
"e": 317,
"s": 305,
"text": "Example #1:"
},
{
"code": "// Scala program of replace()// method // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // Applying replace methodval result = \"Nidhi\".replace('N', 'n') // Displays outputprintln(result) }} ",
"e": 548,
"s": 317,
"text": null
},
{
"code": null,
"e": 555,
"s": 548,
"text": "nidhi\n"
},
{
"code": null,
"e": 567,
"s": 555,
"text": "Example #2:"
},
{
"code": "// Scala program of replace()// method // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // Applying replace methodval result = \"Nidhi\".replace('h', '#') // Displays outputprintln(result) }} ",
"e": 798,
"s": 567,
"text": null
},
{
"code": null,
"e": 805,
"s": 798,
"text": "Nid#i\n"
},
{
"code": null,
"e": 811,
"s": 805,
"text": "Scala"
},
{
"code": null,
"e": 824,
"s": 811,
"text": "Scala-Method"
},
{
"code": null,
"e": 838,
"s": 824,
"text": "Scala-Strings"
},
{
"code": null,
"e": 844,
"s": 838,
"text": "Scala"
}
] |
Java Swing | JToggleButton Class
|
16 Aug, 2021
A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button.
Constructors in JToggleButton:
JToggleButton(): Creates an initially unselected toggle button without setting the text or image.JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied.JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text.JToggleButton(String text): Creates an unselected toggle button with the specified text.JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state.JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected.JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state.
JToggleButton(): Creates an initially unselected toggle button without setting the text or image.
JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied.
JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.
JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text.
JToggleButton(String text): Creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state.
JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected.
JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state.
Commonly Used Methods:
Below programs illustrates the JToggleButton class:
1. Java program to implement JToggleButton Events with the ItemListener: In this program, we are creating the frame using JFrame(). Here, setDefaultCloseOperation() is used to set close option for frame. Using JToggleButton() a button is created. Instantiate the ItemListener which contain only itemStateChanged() method that automatically invoked when button is clicked. Event is generated on the button and accordingly, output is printed to the Console. Attach all the Listeners and adding ItemListener to the button. Add button to the frame and setting the size of the frame.
Java
import java.awt.BorderLayout;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import javax.swing.JFrame;import javax.swing.JToggleButton; public class JToggleButtonExamp { // Main Method public static void main(String args[]) { // create a frame and set title JFrame frame = new JFrame("Selecting Toggle"); // set the default close operation of the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a ToggleButton JToggleButton toggleButton = new JToggleButton("Toggle Button"); // ItemListener is notified whenever you click on the Button ItemListener itemListener = new ItemListener() { // itemStateChanged() method is nvoked automatically // whenever you click or unlick on the Button. public void itemStateChanged(ItemEvent itemEvent) { // event is generated in button int state = itemEvent.getStateChange(); // if selected print selected in console if (state == ItemEvent.SELECTED) { System.out.println("Selected"); } else { // else print deselected in console System.out.println("Deselected"); } } }; // Attach Listeners toggleButton.addItemListener(itemListener); frame.add(toggleButton, BorderLayout.NORTH); frame.setSize(300, 125); frame.setVisible(true); }}
Output:
2. Java program to implement JToggleButton Event using ActionListener: Here, a JToggleButton is created on the JFrame. Then, we define the ActionListener. actionPerformed() is the only method in ActionListener() which is invoked whenever a registered component is clicked. abstractButton.getModel().isSelected() returns true if button is selected else return false. Attach the Listener to the ToggleButton.
Java
import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.AbstractButton;import javax.swing.JFrame;import javax.swing.JToggleButton; public class JToggleButtonExamp { // Main Method public static void main(String args[]) { // create the JFrame JFrame frame = new JFrame("Selecting Toggle"); // set default close operation for frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a ToggleButton JToggleButton toggleButton = new JToggleButton("Toggle Button"); // Define ActionListener ActionListener actionListener = new ActionListener() { // actionPerformed() method is invoked // automatically whenever you click on // registered component public void actionPerformed(ActionEvent actionEvent) { AbstractButton abstractButton = (AbstractButton)actionEvent.getSource(); // return true or false according // to the selection or deselection // of the button boolean selected = abstractButton.getModel().isSelected(); System.out.println("Action - selected=" + selected + "\n"); } }; // Attach Listeners toggleButton.addActionListener(actionListener); // add ToggleButton to the frame frame.add(toggleButton, BorderLayout.NORTH); // set size of the frame frame.setSize(300, 125); frame.setVisible(true); }}
Output :
Note: The above programs might not run in an online IDE. Please use an offline compiler.
Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html
nidhi_biet
kk773572498
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 498,
"s": 28,
"text": "A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button."
},
{
"code": null,
"e": 530,
"s": 498,
"text": "Constructors in JToggleButton: "
},
{
"code": null,
"e": 1434,
"s": 530,
"text": "JToggleButton(): Creates an initially unselected toggle button without setting the text or image.JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied.JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text.JToggleButton(String text): Creates an unselected toggle button with the specified text.JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state.JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected.JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state."
},
{
"code": null,
"e": 1532,
"s": 1434,
"text": "JToggleButton(): Creates an initially unselected toggle button without setting the text or image."
},
{
"code": null,
"e": 1634,
"s": 1532,
"text": "JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied."
},
{
"code": null,
"e": 1744,
"s": 1634,
"text": "JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text."
},
{
"code": null,
"e": 1871,
"s": 1744,
"text": "JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text."
},
{
"code": null,
"e": 1960,
"s": 1871,
"text": "JToggleButton(String text): Creates an unselected toggle button with the specified text."
},
{
"code": null,
"e": 2075,
"s": 1960,
"text": "JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state."
},
{
"code": null,
"e": 2211,
"s": 2075,
"text": "JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected."
},
{
"code": null,
"e": 2345,
"s": 2211,
"text": "JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state."
},
{
"code": null,
"e": 2369,
"s": 2345,
"text": "Commonly Used Methods: "
},
{
"code": null,
"e": 2422,
"s": 2369,
"text": "Below programs illustrates the JToggleButton class: "
},
{
"code": null,
"e": 3001,
"s": 2422,
"text": "1. Java program to implement JToggleButton Events with the ItemListener: In this program, we are creating the frame using JFrame(). Here, setDefaultCloseOperation() is used to set close option for frame. Using JToggleButton() a button is created. Instantiate the ItemListener which contain only itemStateChanged() method that automatically invoked when button is clicked. Event is generated on the button and accordingly, output is printed to the Console. Attach all the Listeners and adding ItemListener to the button. Add button to the frame and setting the size of the frame."
},
{
"code": null,
"e": 3006,
"s": 3001,
"text": "Java"
},
{
"code": "import java.awt.BorderLayout;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import javax.swing.JFrame;import javax.swing.JToggleButton; public class JToggleButtonExamp { // Main Method public static void main(String args[]) { // create a frame and set title JFrame frame = new JFrame(\"Selecting Toggle\"); // set the default close operation of the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a ToggleButton JToggleButton toggleButton = new JToggleButton(\"Toggle Button\"); // ItemListener is notified whenever you click on the Button ItemListener itemListener = new ItemListener() { // itemStateChanged() method is nvoked automatically // whenever you click or unlick on the Button. public void itemStateChanged(ItemEvent itemEvent) { // event is generated in button int state = itemEvent.getStateChange(); // if selected print selected in console if (state == ItemEvent.SELECTED) { System.out.println(\"Selected\"); } else { // else print deselected in console System.out.println(\"Deselected\"); } } }; // Attach Listeners toggleButton.addItemListener(itemListener); frame.add(toggleButton, BorderLayout.NORTH); frame.setSize(300, 125); frame.setVisible(true); }}",
"e": 4549,
"s": 3006,
"text": null
},
{
"code": null,
"e": 4557,
"s": 4549,
"text": "Output:"
},
{
"code": null,
"e": 4964,
"s": 4557,
"text": "2. Java program to implement JToggleButton Event using ActionListener: Here, a JToggleButton is created on the JFrame. Then, we define the ActionListener. actionPerformed() is the only method in ActionListener() which is invoked whenever a registered component is clicked. abstractButton.getModel().isSelected() returns true if button is selected else return false. Attach the Listener to the ToggleButton."
},
{
"code": null,
"e": 4969,
"s": 4964,
"text": "Java"
},
{
"code": "import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.AbstractButton;import javax.swing.JFrame;import javax.swing.JToggleButton; public class JToggleButtonExamp { // Main Method public static void main(String args[]) { // create the JFrame JFrame frame = new JFrame(\"Selecting Toggle\"); // set default close operation for frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a ToggleButton JToggleButton toggleButton = new JToggleButton(\"Toggle Button\"); // Define ActionListener ActionListener actionListener = new ActionListener() { // actionPerformed() method is invoked // automatically whenever you click on // registered component public void actionPerformed(ActionEvent actionEvent) { AbstractButton abstractButton = (AbstractButton)actionEvent.getSource(); // return true or false according // to the selection or deselection // of the button boolean selected = abstractButton.getModel().isSelected(); System.out.println(\"Action - selected=\" + selected + \"\\n\"); } }; // Attach Listeners toggleButton.addActionListener(actionListener); // add ToggleButton to the frame frame.add(toggleButton, BorderLayout.NORTH); // set size of the frame frame.setSize(300, 125); frame.setVisible(true); }}",
"e": 6578,
"s": 4969,
"text": null
},
{
"code": null,
"e": 6587,
"s": 6578,
"text": "Output :"
},
{
"code": null,
"e": 6676,
"s": 6587,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler."
},
{
"code": null,
"e": 6761,
"s": 6676,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html "
},
{
"code": null,
"e": 6772,
"s": 6761,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6784,
"s": 6772,
"text": "kk773572498"
},
{
"code": null,
"e": 6795,
"s": 6784,
"text": "java-swing"
},
{
"code": null,
"e": 6800,
"s": 6795,
"text": "Java"
},
{
"code": null,
"e": 6805,
"s": 6800,
"text": "Java"
}
] |
How to create an empty vector in R ?
|
21 Apr, 2021
In this article, we are going to see how to create an empty vector in R Programming Language. There are five ways of creating an empty vector and each of them will be discussed in detail below:
Using c()
Using vector()
Creating empty vectors using NULL
Using numeric() method
Using rep() method
Here in this, we need not pass anything while creating an empty vector as we are creating empty vector.
Syntax:
vector name <- c()
Where, vector name can be any valid identifier.
Example :
R
# Here we are creating empty# vector using c().vect <- c() vect
Output:
NULL
Output is null as we are not passing any data to it.
Here in this, we need not pass anything as we are creating an empty vector:
Syntax:
vector name <- vector()
Where, vector name can be any valid identifier.
Example
R
# Here we are creating empty vector# using vector().vect <- vector() vect
Output:
logical(0)
Output is empty as we are not passing any data.
Here we are creating empty vector by passing null.
Syntax:
vector name <- NULL
Where, vector name can be any valid identifier.
Example
R
# Here we are creating empty # vector using NULLa<- NULL a
Output:
NULL
Here we are creating empty vector by using numeric().
Syntax:
vector name <- numeric()
Where, vector name can be any valid identifier.
Example
R
# creating empty vector vec using # numeric function.vec <- numeric() vec
Output:
numeric(0)
Here we can directly use rep() to create empty vector.
Syntax:
vector name<- rep()
where, vector name can be any valid identifier.
Example:
R
# creating empty vector vec using# numeric function.vec <- rep() vec
Output:
NULL
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 247,
"s": 53,
"text": "In this article, we are going to see how to create an empty vector in R Programming Language. There are five ways of creating an empty vector and each of them will be discussed in detail below:"
},
{
"code": null,
"e": 257,
"s": 247,
"text": "Using c()"
},
{
"code": null,
"e": 272,
"s": 257,
"text": "Using vector()"
},
{
"code": null,
"e": 306,
"s": 272,
"text": "Creating empty vectors using NULL"
},
{
"code": null,
"e": 329,
"s": 306,
"text": "Using numeric() method"
},
{
"code": null,
"e": 348,
"s": 329,
"text": "Using rep() method"
},
{
"code": null,
"e": 452,
"s": 348,
"text": "Here in this, we need not pass anything while creating an empty vector as we are creating empty vector."
},
{
"code": null,
"e": 460,
"s": 452,
"text": "Syntax:"
},
{
"code": null,
"e": 479,
"s": 460,
"text": "vector name <- c()"
},
{
"code": null,
"e": 527,
"s": 479,
"text": "Where, vector name can be any valid identifier."
},
{
"code": null,
"e": 537,
"s": 527,
"text": "Example :"
},
{
"code": null,
"e": 539,
"s": 537,
"text": "R"
},
{
"code": "# Here we are creating empty# vector using c().vect <- c() vect",
"e": 604,
"s": 539,
"text": null
},
{
"code": null,
"e": 612,
"s": 604,
"text": "Output:"
},
{
"code": null,
"e": 617,
"s": 612,
"text": "NULL"
},
{
"code": null,
"e": 670,
"s": 617,
"text": "Output is null as we are not passing any data to it."
},
{
"code": null,
"e": 746,
"s": 670,
"text": "Here in this, we need not pass anything as we are creating an empty vector:"
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Syntax:"
},
{
"code": null,
"e": 779,
"s": 754,
"text": "vector name <- vector()"
},
{
"code": null,
"e": 827,
"s": 779,
"text": "Where, vector name can be any valid identifier."
},
{
"code": null,
"e": 835,
"s": 827,
"text": "Example"
},
{
"code": null,
"e": 837,
"s": 835,
"text": "R"
},
{
"code": "# Here we are creating empty vector# using vector().vect <- vector() vect",
"e": 912,
"s": 837,
"text": null
},
{
"code": null,
"e": 920,
"s": 912,
"text": "Output:"
},
{
"code": null,
"e": 931,
"s": 920,
"text": "logical(0)"
},
{
"code": null,
"e": 979,
"s": 931,
"text": "Output is empty as we are not passing any data."
},
{
"code": null,
"e": 1031,
"s": 979,
"text": " Here we are creating empty vector by passing null."
},
{
"code": null,
"e": 1039,
"s": 1031,
"text": "Syntax:"
},
{
"code": null,
"e": 1061,
"s": 1039,
"text": " vector name <- NULL"
},
{
"code": null,
"e": 1109,
"s": 1061,
"text": "Where, vector name can be any valid identifier."
},
{
"code": null,
"e": 1118,
"s": 1109,
"text": "Example "
},
{
"code": null,
"e": 1120,
"s": 1118,
"text": "R"
},
{
"code": "# Here we are creating empty # vector using NULLa<- NULL a",
"e": 1180,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1188,
"s": 1180,
"text": "Output:"
},
{
"code": null,
"e": 1193,
"s": 1188,
"text": "NULL"
},
{
"code": null,
"e": 1247,
"s": 1193,
"text": "Here we are creating empty vector by using numeric()."
},
{
"code": null,
"e": 1255,
"s": 1247,
"text": "Syntax:"
},
{
"code": null,
"e": 1280,
"s": 1255,
"text": "vector name <- numeric()"
},
{
"code": null,
"e": 1328,
"s": 1280,
"text": "Where, vector name can be any valid identifier."
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Example"
},
{
"code": null,
"e": 1338,
"s": 1336,
"text": "R"
},
{
"code": "# creating empty vector vec using # numeric function.vec <- numeric() vec",
"e": 1413,
"s": 1338,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1413,
"text": "Output:"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": "numeric(0)"
},
{
"code": null,
"e": 1487,
"s": 1432,
"text": "Here we can directly use rep() to create empty vector."
},
{
"code": null,
"e": 1495,
"s": 1487,
"text": "Syntax:"
},
{
"code": null,
"e": 1515,
"s": 1495,
"text": "vector name<- rep()"
},
{
"code": null,
"e": 1563,
"s": 1515,
"text": "where, vector name can be any valid identifier."
},
{
"code": null,
"e": 1572,
"s": 1563,
"text": "Example:"
},
{
"code": null,
"e": 1574,
"s": 1572,
"text": "R"
},
{
"code": "# creating empty vector vec using# numeric function.vec <- rep() vec",
"e": 1644,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Output:"
},
{
"code": null,
"e": 1657,
"s": 1652,
"text": "NULL"
},
{
"code": null,
"e": 1664,
"s": 1657,
"text": "Picked"
},
{
"code": null,
"e": 1682,
"s": 1664,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 1692,
"s": 1682,
"text": "R-Vectors"
},
{
"code": null,
"e": 1703,
"s": 1692,
"text": "R Language"
},
{
"code": null,
"e": 1714,
"s": 1703,
"text": "R Programs"
}
] |
Get the statistical summary and nature of the DataFrame in R
|
07 Apr, 2021
In this article, we will see how to find the statistics of the given data frame. We will use the summary() function to get the statistics for each column:
Syntax: summary(dataframe_name)
The result produced will contain the following details:
Minimum value – returns the minimum value from each column
Maximum value – returns the maximum value from each column
Mean – returns the mean value from each column
Median – returns the median from each column
1st quartile – returns the 1st quartile from each column
3rd quartile – returns the 3rd quartile from each column.
Example 1: In this example data, we had taken student marks, height, weight, and marks, so we are calculating the summary of that two columns.
R
# create vector with namesname = c("sravan", "mohan", "sudheer", "radha", "vani", "mohan") # create vector with subjectssubjects = c(".net", "Python", "java", "dbms", "os", "dbms") # create a vector with marksmarks = c(98, 97, 89, 90, 87, 90) # create vector with heightheight = c(5.97, 6.11, 5.89, 5.45, 5.78, 6.0) # create vector with weightweight = c(67, 65, 78, 65, 81, 76) # pass these vectors to the data framedata = data.frame(name, subjects, marks, height, weight) # displayprint(data)print("STATISTICAL SUMMARY") # use summary function print(summary(data))
Output:
Example 2: In this example, we are getting a statistical summary of individual columns
R
# create vector with namesname = c("sravan","mohan","sudheer", "radha","vani","mohan") # create vector with subjectssubjects = c(".net","Python","java", "dbms","os","dbms") # create a vector with marksmarks=c(98,97,89,90,87,90) # create vector with heightheight=c(5.97,6.11,5.89, 5.45,5.78,6.0) # create vector with weightweight=c(67,65,78,65,81,76) # pass these vectors to the data framedata=data.frame(name,subjects,marks, height,weight) # displayprint(data)print("STATISTICAL SUMMARY of marks") # use summary function on marks columnprint(summary(data$marks))print("STATISTICAL SUMMARY of height") # use summary function on height columnprint(summary(data$height))print("STATISTICAL SUMMARY of weight") # use summary function on weight columnprint(summary(data$weight))
Output:
We can use class() function to get the nature of the dataframe.
It will return:
Either data is NULL or not
The datatype of a particular column in a dataframe
Syntax: class(dataframe$column_name)
Example:
R
# create vector with namesname = c("sravan","mohan","sudheer", "radha","vani","mohan") # create vector with subjectssubjects = c(".net","Python","java", "dbms","os","dbms") # create a vector with marksmarks=c(98,97,89,90,87,90) # create vector with heightheight=c(5.97,6.11,5.89, 5.45,5.78,6.0) # create vector with weightweight=c(67,65,78,65,81,76) # pass these vectors to the data framedata=data.frame(name,subjects,marks, height,weight) # nature of dataframeprint(paste("names column",class(data$names)))print(paste("subjects column",class(data$subjects)))print(paste("marks column",class(data$marks)))print(paste("height column",class(data$height)))print(paste("weight column",class(data$weight)))
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "In this article, we will see how to find the statistics of the given data frame. We will use the summary() function to get the statistics for each column:"
},
{
"code": null,
"e": 215,
"s": 183,
"text": "Syntax: summary(dataframe_name)"
},
{
"code": null,
"e": 271,
"s": 215,
"text": "The result produced will contain the following details:"
},
{
"code": null,
"e": 330,
"s": 271,
"text": "Minimum value – returns the minimum value from each column"
},
{
"code": null,
"e": 389,
"s": 330,
"text": "Maximum value – returns the maximum value from each column"
},
{
"code": null,
"e": 436,
"s": 389,
"text": "Mean – returns the mean value from each column"
},
{
"code": null,
"e": 481,
"s": 436,
"text": "Median – returns the median from each column"
},
{
"code": null,
"e": 538,
"s": 481,
"text": "1st quartile – returns the 1st quartile from each column"
},
{
"code": null,
"e": 596,
"s": 538,
"text": "3rd quartile – returns the 3rd quartile from each column."
},
{
"code": null,
"e": 739,
"s": 596,
"text": "Example 1: In this example data, we had taken student marks, height, weight, and marks, so we are calculating the summary of that two columns."
},
{
"code": null,
"e": 741,
"s": 739,
"text": "R"
},
{
"code": "# create vector with namesname = c(\"sravan\", \"mohan\", \"sudheer\", \"radha\", \"vani\", \"mohan\") # create vector with subjectssubjects = c(\".net\", \"Python\", \"java\", \"dbms\", \"os\", \"dbms\") # create a vector with marksmarks = c(98, 97, 89, 90, 87, 90) # create vector with heightheight = c(5.97, 6.11, 5.89, 5.45, 5.78, 6.0) # create vector with weightweight = c(67, 65, 78, 65, 81, 76) # pass these vectors to the data framedata = data.frame(name, subjects, marks, height, weight) # displayprint(data)print(\"STATISTICAL SUMMARY\") # use summary function print(summary(data))",
"e": 1352,
"s": 741,
"text": null
},
{
"code": null,
"e": 1360,
"s": 1352,
"text": "Output:"
},
{
"code": null,
"e": 1447,
"s": 1360,
"text": "Example 2: In this example, we are getting a statistical summary of individual columns"
},
{
"code": null,
"e": 1449,
"s": 1447,
"text": "R"
},
{
"code": "# create vector with namesname = c(\"sravan\",\"mohan\",\"sudheer\", \"radha\",\"vani\",\"mohan\") # create vector with subjectssubjects = c(\".net\",\"Python\",\"java\", \"dbms\",\"os\",\"dbms\") # create a vector with marksmarks=c(98,97,89,90,87,90) # create vector with heightheight=c(5.97,6.11,5.89, 5.45,5.78,6.0) # create vector with weightweight=c(67,65,78,65,81,76) # pass these vectors to the data framedata=data.frame(name,subjects,marks, height,weight) # displayprint(data)print(\"STATISTICAL SUMMARY of marks\") # use summary function on marks columnprint(summary(data$marks))print(\"STATISTICAL SUMMARY of height\") # use summary function on height columnprint(summary(data$height))print(\"STATISTICAL SUMMARY of weight\") # use summary function on weight columnprint(summary(data$weight))",
"e": 2277,
"s": 1449,
"text": null
},
{
"code": null,
"e": 2285,
"s": 2277,
"text": "Output:"
},
{
"code": null,
"e": 2349,
"s": 2285,
"text": "We can use class() function to get the nature of the dataframe."
},
{
"code": null,
"e": 2365,
"s": 2349,
"text": "It will return:"
},
{
"code": null,
"e": 2392,
"s": 2365,
"text": "Either data is NULL or not"
},
{
"code": null,
"e": 2443,
"s": 2392,
"text": "The datatype of a particular column in a dataframe"
},
{
"code": null,
"e": 2480,
"s": 2443,
"text": "Syntax: class(dataframe$column_name)"
},
{
"code": null,
"e": 2489,
"s": 2480,
"text": "Example:"
},
{
"code": null,
"e": 2491,
"s": 2489,
"text": "R"
},
{
"code": "# create vector with namesname = c(\"sravan\",\"mohan\",\"sudheer\", \"radha\",\"vani\",\"mohan\") # create vector with subjectssubjects = c(\".net\",\"Python\",\"java\", \"dbms\",\"os\",\"dbms\") # create a vector with marksmarks=c(98,97,89,90,87,90) # create vector with heightheight=c(5.97,6.11,5.89, 5.45,5.78,6.0) # create vector with weightweight=c(67,65,78,65,81,76) # pass these vectors to the data framedata=data.frame(name,subjects,marks, height,weight) # nature of dataframeprint(paste(\"names column\",class(data$names)))print(paste(\"subjects column\",class(data$subjects)))print(paste(\"marks column\",class(data$marks)))print(paste(\"height column\",class(data$height)))print(paste(\"weight column\",class(data$weight)))",
"e": 3242,
"s": 2491,
"text": null
},
{
"code": null,
"e": 3250,
"s": 3242,
"text": "Output:"
},
{
"code": null,
"e": 3257,
"s": 3250,
"text": "Picked"
},
{
"code": null,
"e": 3278,
"s": 3257,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3290,
"s": 3278,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3301,
"s": 3290,
"text": "R Language"
},
{
"code": null,
"e": 3312,
"s": 3301,
"text": "R Programs"
},
{
"code": null,
"e": 3410,
"s": 3312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3462,
"s": 3410,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3520,
"s": 3462,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3555,
"s": 3520,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3593,
"s": 3555,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3642,
"s": 3593,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3700,
"s": 3642,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3749,
"s": 3700,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3792,
"s": 3749,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3830,
"s": 3792,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to add Radio Buttons in form using HTML ?
|
22 Jul, 2021
We know that Radio Buttons are used to select only one option out of the several options. It is generally used in HTML form.
Approach: To add a radio buttons in a webpage, the HTML provides a <input> element with type attribute is set to “radio”.
Syntax:
<input type="radio">
Example: Below code illustrates that how to add a radio button in the webpage.
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; } h2 { color: green; } </style></head> <body> <h2> GeeksforGeeks </h2> <h3> How to add a Radio Buttons in form using HTML? </h3> <h4> Select Gender </h4> Male <input type="radio" checked=true name="user_gender"> Female <input type="radio" name="user_gender"> </body> </html>
Output:
gender of user
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
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 Jul, 2021"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "We know that Radio Buttons are used to select only one option out of the several options. It is generally used in HTML form. "
},
{
"code": null,
"e": 278,
"s": 154,
"text": "Approach: To add a radio buttons in a webpage, the HTML provides a <input> element with type attribute is set to “radio”. "
},
{
"code": null,
"e": 286,
"s": 278,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 286,
"text": "<input type=\"radio\"> "
},
{
"code": null,
"e": 389,
"s": 309,
"text": "Example: Below code illustrates that how to add a radio button in the webpage. "
},
{
"code": null,
"e": 394,
"s": 389,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h2 { color: green; } </style></head> <body> <h2> GeeksforGeeks </h2> <h3> How to add a Radio Buttons in form using HTML? </h3> <h4> Select Gender </h4> Male <input type=\"radio\" checked=true name=\"user_gender\"> Female <input type=\"radio\" name=\"user_gender\"> </body> </html> ",
"e": 903,
"s": 394,
"text": null
},
{
"code": null,
"e": 911,
"s": 903,
"text": "Output:"
},
{
"code": null,
"e": 926,
"s": 911,
"text": "gender of user"
},
{
"code": null,
"e": 941,
"s": 926,
"text": "HTML-Questions"
},
{
"code": null,
"e": 951,
"s": 941,
"text": "HTML-Tags"
},
{
"code": null,
"e": 956,
"s": 951,
"text": "HTML"
},
{
"code": null,
"e": 973,
"s": 956,
"text": "Web Technologies"
},
{
"code": null,
"e": 978,
"s": 973,
"text": "HTML"
},
{
"code": null,
"e": 1076,
"s": 978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1100,
"s": 1076,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1139,
"s": 1100,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1178,
"s": 1139,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1198,
"s": 1178,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1227,
"s": 1198,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1260,
"s": 1227,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1321,
"s": 1260,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1364,
"s": 1321,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1436,
"s": 1364,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Pandas Scatter Plot – DataFrame.plot.scatter()
|
25 Feb, 2021
A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame.
Syntax: DataFrame.plot.scatter(x, y, s = none, c = none)
Parameter:
x: column name to be used as horizontal coordinates for each pointy: column name to be used as vertical coordinates for each points: size of dotsc: color of dots
Import necessary libraries.
Prepare a data
Convert prepared data into DataFrame
Draw a scatter plot
Example 1: In this example, we will plot the scatter plot using dataframe, Here we will create the dataframe and plot the scatter plot using different columns.
Python3
# Program to draw scatter plot using Dataframe.plot# Import librariesimport pandas as pd # Prepare datadata={'Name':['Dhanashri', 'Smita', 'Rutuja', 'Sunita', 'Poonam', 'Srushti'], 'Age':[20, 18, 27, 50, 12, 15]} # Load data into DataFramedf = pd.DataFrame(data = data); # Draw a scatter plotdf.plot.scatter(x = 'Name', y = 'Age', s = 100);
Output:
Example 2: Here we will create the dataframe and plot the scatter plot using different columns with style data points.
Python3
# Program to draw scatter plot using Dataframe.plot# Import librariesimport pandas as pd # Prepare datadata={'Name':['Dhanashri', 'Smita', 'Rutuja', 'Sunita', 'Poonam', 'Srushti'], 'Age':[ 20, 18, 27, 50, 12, 15]} # Load data into DataFramedf = pd.DataFrame(data = data); # Draw a scatter plot and here size of dots determined by age of persondf.plot.scatter(x = 'Name', y = 'Age', s = 'Age', c = 'red');
Output:
Picked
Python pandas-plotting
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
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame. "
},
{
"code": null,
"e": 431,
"s": 374,
"text": "Syntax: DataFrame.plot.scatter(x, y, s = none, c = none)"
},
{
"code": null,
"e": 442,
"s": 431,
"text": "Parameter:"
},
{
"code": null,
"e": 604,
"s": 442,
"text": "x: column name to be used as horizontal coordinates for each pointy: column name to be used as vertical coordinates for each points: size of dotsc: color of dots"
},
{
"code": null,
"e": 632,
"s": 604,
"text": "Import necessary libraries."
},
{
"code": null,
"e": 647,
"s": 632,
"text": "Prepare a data"
},
{
"code": null,
"e": 684,
"s": 647,
"text": "Convert prepared data into DataFrame"
},
{
"code": null,
"e": 704,
"s": 684,
"text": "Draw a scatter plot"
},
{
"code": null,
"e": 864,
"s": 704,
"text": "Example 1: In this example, we will plot the scatter plot using dataframe, Here we will create the dataframe and plot the scatter plot using different columns."
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Python3"
},
{
"code": "# Program to draw scatter plot using Dataframe.plot# Import librariesimport pandas as pd # Prepare datadata={'Name':['Dhanashri', 'Smita', 'Rutuja', 'Sunita', 'Poonam', 'Srushti'], 'Age':[20, 18, 27, 50, 12, 15]} # Load data into DataFramedf = pd.DataFrame(data = data); # Draw a scatter plotdf.plot.scatter(x = 'Name', y = 'Age', s = 100);",
"e": 1234,
"s": 872,
"text": null
},
{
"code": null,
"e": 1242,
"s": 1234,
"text": "Output:"
},
{
"code": null,
"e": 1361,
"s": 1242,
"text": "Example 2: Here we will create the dataframe and plot the scatter plot using different columns with style data points."
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Python3"
},
{
"code": "# Program to draw scatter plot using Dataframe.plot# Import librariesimport pandas as pd # Prepare datadata={'Name':['Dhanashri', 'Smita', 'Rutuja', 'Sunita', 'Poonam', 'Srushti'], 'Age':[ 20, 18, 27, 50, 12, 15]} # Load data into DataFramedf = pd.DataFrame(data = data); # Draw a scatter plot and here size of dots determined by age of persondf.plot.scatter(x = 'Name', y = 'Age', s = 'Age', c = 'red');",
"e": 1795,
"s": 1369,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1795,
"text": "Output:"
},
{
"code": null,
"e": 1810,
"s": 1803,
"text": "Picked"
},
{
"code": null,
"e": 1833,
"s": 1810,
"text": "Python pandas-plotting"
},
{
"code": null,
"e": 1847,
"s": 1833,
"text": "Python-pandas"
},
{
"code": null,
"e": 1854,
"s": 1847,
"text": "Python"
},
{
"code": null,
"e": 1952,
"s": 1854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1970,
"s": 1952,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2012,
"s": 1970,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2034,
"s": 2012,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2060,
"s": 2034,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2092,
"s": 2060,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2121,
"s": 2092,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2148,
"s": 2121,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2184,
"s": 2148,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2215,
"s": 2184,
"text": "Python | os.path.join() method"
}
] |
How to Convert Pandas to PySpark DataFrame ?
|
23 May, 2021
In this article, we will learn How to Convert Pandas to PySpark DataFrame. Sometimes we will get csv, xlsx, etc. format data, and we have to store it in PySpark DataFrame and that can be done by loading data in Pandas then converted PySpark DataFrame. For conversion, we pass the Pandas dataframe into the CreateDataFrame() method.
Syntax: spark.createDataframe(data, schema)
Parameter:
data – list of values on which dataframe is created.
schema – It’s the structure of dataset or list of column names.
where spark is the SparkSession object.
Example 1: Create a DataFrame and then Convert using spark.createDataFrame() method
Python3
# import the pandasimport pandas as pd # from pyspark library import # SparkSessionfrom pyspark.sql import SparkSession # Building the SparkSession and name# it :'pandas to spark'spark = SparkSession.builder.appName( "pandas to spark").getOrCreate() # Create the DataFrame with the help # of pd.DataFrame()data = pd.DataFrame({'State': ['Alaska', 'California', 'Florida', 'Washington'], 'city': ["Anchorage", "Los Angeles", "Miami", "Bellevue"]}) # create DataFramedf_spark = spark.createDataFrame(data) df_spark.show()
Output:
Example 2: Create a DataFrame and then Convert using spark.createDataFrame() method
In this method, we are using Apache Arrow to convert Pandas to Pyspark DataFrame.
Python3
import the pandasimport pandas as pd # from pyspark library import # SparkSessionfrom pyspark.sql import SparkSession # Building the SparkSession and name # it :'pandas to spark'spark = SparkSession.builder.appName( "pandas to spark").getOrCreate() # Create the DataFrame with the help # of pd.DataFrame()data = pd.DataFrame({'State': ['Alaska', 'California', 'Florida', 'Washington'], 'city': ["Anchorage", "Los Angeles", "Miami", "Bellevue"]}) # enableing the Apache Arrow for converting# Pandas to pySpark DF(DataFrame)spark.conf.set("spark.sql.execution.arrow.enabled", "true") # Creating the DataFramesprak_arrow = spark.createDataFrame(data) # Show the DataFramesprak_arrow.show()
Output:
Example 3: Load a DataFrame from CSV and then Convert
In this method, we can easily read the CSV file in Pandas Dataframe as well as in Pyspark Dataframe. The dataset used here is heart.csv.
Python3
# import the pandas libraryimport pandas as pd # Read the Dataset in Pandas Dataframedf_pd = pd.read_csv('heart.csv') # Show the dataset here head() # will return top 5 rowsdf_pd.head()
Output:
Python3
# Reading the csv file in # Pyspark DataFramedf_spark2 = spark.read.option( 'header', 'true').csv("heart.csv") # Showing the data in the from of # table and showing only top 5 rowsdf_spark2.show(5)
Output:
We can also convert pyspark Dataframe to pandas Dataframe. For this, we will use DataFrame.toPandas() method.
Syntax: DataFrame.toPandas()
Returns the contents of this DataFrame as Pandas pandas.DataFrame.
Python3
# Convert Pyspark DataFrame to # Pandas DataFrame by toPandas() # Function head() will show only# top 5 rows of the datasetdf_spark2.toPandas().head()
Output:
Picked
Python-Pyspark
Python
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "In this article, we will learn How to Convert Pandas to PySpark DataFrame. Sometimes we will get csv, xlsx, etc. format data, and we have to store it in PySpark DataFrame and that can be done by loading data in Pandas then converted PySpark DataFrame. For conversion, we pass the Pandas dataframe into the CreateDataFrame() method."
},
{
"code": null,
"e": 404,
"s": 360,
"text": "Syntax: spark.createDataframe(data, schema)"
},
{
"code": null,
"e": 415,
"s": 404,
"text": "Parameter:"
},
{
"code": null,
"e": 468,
"s": 415,
"text": "data – list of values on which dataframe is created."
},
{
"code": null,
"e": 532,
"s": 468,
"text": "schema – It’s the structure of dataset or list of column names."
},
{
"code": null,
"e": 572,
"s": 532,
"text": "where spark is the SparkSession object."
},
{
"code": null,
"e": 656,
"s": 572,
"text": "Example 1: Create a DataFrame and then Convert using spark.createDataFrame() method"
},
{
"code": null,
"e": 664,
"s": 656,
"text": "Python3"
},
{
"code": "# import the pandasimport pandas as pd # from pyspark library import # SparkSessionfrom pyspark.sql import SparkSession # Building the SparkSession and name# it :'pandas to spark'spark = SparkSession.builder.appName( \"pandas to spark\").getOrCreate() # Create the DataFrame with the help # of pd.DataFrame()data = pd.DataFrame({'State': ['Alaska', 'California', 'Florida', 'Washington'], 'city': [\"Anchorage\", \"Los Angeles\", \"Miami\", \"Bellevue\"]}) # create DataFramedf_spark = spark.createDataFrame(data) df_spark.show()",
"e": 1294,
"s": 664,
"text": null
},
{
"code": null,
"e": 1302,
"s": 1294,
"text": "Output:"
},
{
"code": null,
"e": 1386,
"s": 1302,
"text": "Example 2: Create a DataFrame and then Convert using spark.createDataFrame() method"
},
{
"code": null,
"e": 1468,
"s": 1386,
"text": "In this method, we are using Apache Arrow to convert Pandas to Pyspark DataFrame."
},
{
"code": null,
"e": 1476,
"s": 1468,
"text": "Python3"
},
{
"code": "import the pandasimport pandas as pd # from pyspark library import # SparkSessionfrom pyspark.sql import SparkSession # Building the SparkSession and name # it :'pandas to spark'spark = SparkSession.builder.appName( \"pandas to spark\").getOrCreate() # Create the DataFrame with the help # of pd.DataFrame()data = pd.DataFrame({'State': ['Alaska', 'California', 'Florida', 'Washington'], 'city': [\"Anchorage\", \"Los Angeles\", \"Miami\", \"Bellevue\"]}) # enableing the Apache Arrow for converting# Pandas to pySpark DF(DataFrame)spark.conf.set(\"spark.sql.execution.arrow.enabled\", \"true\") # Creating the DataFramesprak_arrow = spark.createDataFrame(data) # Show the DataFramesprak_arrow.show()",
"e": 2275,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2283,
"s": 2275,
"text": "Output:"
},
{
"code": null,
"e": 2338,
"s": 2283,
"text": "Example 3: Load a DataFrame from CSV and then Convert "
},
{
"code": null,
"e": 2475,
"s": 2338,
"text": "In this method, we can easily read the CSV file in Pandas Dataframe as well as in Pyspark Dataframe. The dataset used here is heart.csv."
},
{
"code": null,
"e": 2483,
"s": 2475,
"text": "Python3"
},
{
"code": "# import the pandas libraryimport pandas as pd # Read the Dataset in Pandas Dataframedf_pd = pd.read_csv('heart.csv') # Show the dataset here head() # will return top 5 rowsdf_pd.head()",
"e": 2671,
"s": 2483,
"text": null
},
{
"code": null,
"e": 2679,
"s": 2671,
"text": "Output:"
},
{
"code": null,
"e": 2687,
"s": 2679,
"text": "Python3"
},
{
"code": "# Reading the csv file in # Pyspark DataFramedf_spark2 = spark.read.option( 'header', 'true').csv(\"heart.csv\") # Showing the data in the from of # table and showing only top 5 rowsdf_spark2.show(5)",
"e": 2887,
"s": 2687,
"text": null
},
{
"code": null,
"e": 2895,
"s": 2887,
"text": "Output:"
},
{
"code": null,
"e": 3005,
"s": 2895,
"text": "We can also convert pyspark Dataframe to pandas Dataframe. For this, we will use DataFrame.toPandas() method."
},
{
"code": null,
"e": 3034,
"s": 3005,
"text": "Syntax: DataFrame.toPandas()"
},
{
"code": null,
"e": 3101,
"s": 3034,
"text": "Returns the contents of this DataFrame as Pandas pandas.DataFrame."
},
{
"code": null,
"e": 3109,
"s": 3101,
"text": "Python3"
},
{
"code": "# Convert Pyspark DataFrame to # Pandas DataFrame by toPandas() # Function head() will show only# top 5 rows of the datasetdf_spark2.toPandas().head()",
"e": 3260,
"s": 3109,
"text": null
},
{
"code": null,
"e": 3268,
"s": 3260,
"text": "Output:"
},
{
"code": null,
"e": 3275,
"s": 3268,
"text": "Picked"
},
{
"code": null,
"e": 3290,
"s": 3275,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 3297,
"s": 3290,
"text": "Python"
},
{
"code": null,
"e": 3395,
"s": 3297,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3437,
"s": 3395,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3459,
"s": 3437,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3491,
"s": 3459,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3520,
"s": 3491,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3547,
"s": 3520,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3568,
"s": 3547,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3604,
"s": 3568,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3627,
"s": 3604,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3683,
"s": 3627,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Collection add() Method in Java with Examples
|
29 Nov, 2021
The add(E element) of java.util.Collection interface is used to add the element ‘element’ to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false.
Syntax:
Collection.add(E element)
Parameters: This method accepts a mandatory parameter element of type E which is to be added to this collection.
Return Value: A boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false.
Exceptions: This method throws 5 following exceptions listed below as follows:
UnsupportedOperationException: if the add operation is not supported by this collection
ClassCastException: if the class of the specified element prevents it from being added to this collection
NullPointerException: if the specified element is null and this collection does not permit null elements
IllegalArgumentException: if some property of the element prevents it from being added to this collection
IllegalStateException: if the element cannot be added at this time due to insertion restrictions
Now we will be implementing this method over different classes as it is a very important and essential method when it comes downs to java programming so here we will be stressing over each class as follows:
LinkedList class
ArrayDeque
ArrayList class
NullPointerException is Thrown
Let us implement add() method in all 4 above listed cases via clean java examples as follows:
Example 1: LinkedList Class
Java
// Java code to illustrate boolean add() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Output the present list System.out.println("The list is: " + list); // Adding new elements to the end list.add("Last"); list.add("Element"); // printing the new list System.out.println("The new List is: " + list); }}
The list is: [Geeks, for, Geeks]
The new List is: [Geeks, for, Geeks, Last, Element]
Example 2: ArrayDeque Class
Java
// Java code to illustrate add() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); }}
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Example 3: Using ArrayList Class
Java
// Java code to illustrate add() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}
Number = 15
Number = 20
Number = 25
Geeks do keep an bound over special case where NullPointer Exception will be thrown as show in below example as follows:
Example 4:
Java
// Java code to illustrate boolean add()// Where NullPointerException is Thrown // Importing required utility classesimport java.util.*; // Main class// LinkedListDemoclass GFG { // Main driver method public static void main(String args[]) { // Creating an empty ArrayList of string type Collection<String> list = new ArrayList<String>(); // Printing and displaying the Arraylist System.out.println("The ArrayList is: " + list); // Note: Here by now we have not added any element/s // Try block to check for exceptions try { // Appending the null to the list // using add() method list.add(null); } // Catch block to handle exceptions catch (Exception e) { // Display message when exceptions occurs System.out.println("Exception: " + e); } }}
The ArrayList is: []
Output explanation: Here we need to pick it up as we will only receive a List. So it is good practice to document for add() method either its is accepting it whether it needs to support null.
solankimayank
surinderdawra388
anikakapoor
varshagumber28
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 312,
"s": 53,
"text": "The add(E element) of java.util.Collection interface is used to add the element ‘element’ to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false."
},
{
"code": null,
"e": 321,
"s": 312,
"text": "Syntax: "
},
{
"code": null,
"e": 347,
"s": 321,
"text": "Collection.add(E element)"
},
{
"code": null,
"e": 460,
"s": 347,
"text": "Parameters: This method accepts a mandatory parameter element of type E which is to be added to this collection."
},
{
"code": null,
"e": 603,
"s": 460,
"text": "Return Value: A boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false."
},
{
"code": null,
"e": 682,
"s": 603,
"text": "Exceptions: This method throws 5 following exceptions listed below as follows:"
},
{
"code": null,
"e": 770,
"s": 682,
"text": "UnsupportedOperationException: if the add operation is not supported by this collection"
},
{
"code": null,
"e": 876,
"s": 770,
"text": "ClassCastException: if the class of the specified element prevents it from being added to this collection"
},
{
"code": null,
"e": 981,
"s": 876,
"text": "NullPointerException: if the specified element is null and this collection does not permit null elements"
},
{
"code": null,
"e": 1087,
"s": 981,
"text": "IllegalArgumentException: if some property of the element prevents it from being added to this collection"
},
{
"code": null,
"e": 1184,
"s": 1087,
"text": "IllegalStateException: if the element cannot be added at this time due to insertion restrictions"
},
{
"code": null,
"e": 1391,
"s": 1184,
"text": "Now we will be implementing this method over different classes as it is a very important and essential method when it comes downs to java programming so here we will be stressing over each class as follows:"
},
{
"code": null,
"e": 1408,
"s": 1391,
"text": "LinkedList class"
},
{
"code": null,
"e": 1419,
"s": 1408,
"text": "ArrayDeque"
},
{
"code": null,
"e": 1435,
"s": 1419,
"text": "ArrayList class"
},
{
"code": null,
"e": 1466,
"s": 1435,
"text": "NullPointerException is Thrown"
},
{
"code": null,
"e": 1560,
"s": 1466,
"text": "Let us implement add() method in all 4 above listed cases via clean java examples as follows:"
},
{
"code": null,
"e": 1588,
"s": 1560,
"text": "Example 1: LinkedList Class"
},
{
"code": null,
"e": 1593,
"s": 1588,
"text": "Java"
},
{
"code": "// Java code to illustrate boolean add() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Output the present list System.out.println(\"The list is: \" + list); // Adding new elements to the end list.add(\"Last\"); list.add(\"Element\"); // printing the new list System.out.println(\"The new List is: \" + list); }}",
"e": 2250,
"s": 1593,
"text": null
},
{
"code": null,
"e": 2335,
"s": 2250,
"text": "The list is: [Geeks, for, Geeks]\nThe new List is: [Geeks, for, Geeks, Last, Element]"
},
{
"code": null,
"e": 2366,
"s": 2337,
"text": "Example 2: ArrayDeque Class "
},
{
"code": null,
"e": 2371,
"s": 2366,
"text": "Java"
},
{
"code": "// Java code to illustrate add() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); }}",
"e": 2897,
"s": 2371,
"text": null
},
{
"code": null,
"e": 2940,
"s": 2897,
"text": "ArrayDeque: [Welcome, To, Geeks, 4, Geeks]"
},
{
"code": null,
"e": 2976,
"s": 2942,
"text": "Example 3: Using ArrayList Class "
},
{
"code": null,
"e": 2981,
"s": 2976,
"text": "Java"
},
{
"code": "// Java code to illustrate add() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}",
"e": 3550,
"s": 2981,
"text": null
},
{
"code": null,
"e": 3586,
"s": 3550,
"text": "Number = 15\nNumber = 20\nNumber = 25"
},
{
"code": null,
"e": 3709,
"s": 3588,
"text": "Geeks do keep an bound over special case where NullPointer Exception will be thrown as show in below example as follows:"
},
{
"code": null,
"e": 3720,
"s": 3709,
"text": "Example 4:"
},
{
"code": null,
"e": 3725,
"s": 3720,
"text": "Java"
},
{
"code": "// Java code to illustrate boolean add()// Where NullPointerException is Thrown // Importing required utility classesimport java.util.*; // Main class// LinkedListDemoclass GFG { // Main driver method public static void main(String args[]) { // Creating an empty ArrayList of string type Collection<String> list = new ArrayList<String>(); // Printing and displaying the Arraylist System.out.println(\"The ArrayList is: \" + list); // Note: Here by now we have not added any element/s // Try block to check for exceptions try { // Appending the null to the list // using add() method list.add(null); } // Catch block to handle exceptions catch (Exception e) { // Display message when exceptions occurs System.out.println(\"Exception: \" + e); } }}",
"e": 4620,
"s": 3725,
"text": null
},
{
"code": null,
"e": 4641,
"s": 4620,
"text": "The ArrayList is: []"
},
{
"code": null,
"e": 4835,
"s": 4643,
"text": "Output explanation: Here we need to pick it up as we will only receive a List. So it is good practice to document for add() method either its is accepting it whether it needs to support null."
},
{
"code": null,
"e": 4849,
"s": 4835,
"text": "solankimayank"
},
{
"code": null,
"e": 4866,
"s": 4849,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4878,
"s": 4866,
"text": "anikakapoor"
},
{
"code": null,
"e": 4893,
"s": 4878,
"text": "varshagumber28"
},
{
"code": null,
"e": 4913,
"s": 4893,
"text": "Java - util package"
},
{
"code": null,
"e": 4930,
"s": 4913,
"text": "Java-Collections"
},
{
"code": null,
"e": 4945,
"s": 4930,
"text": "Java-Functions"
},
{
"code": null,
"e": 4950,
"s": 4945,
"text": "Java"
},
{
"code": null,
"e": 4955,
"s": 4950,
"text": "Java"
},
{
"code": null,
"e": 4972,
"s": 4955,
"text": "Java-Collections"
},
{
"code": null,
"e": 5070,
"s": 4972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5085,
"s": 5070,
"text": "Stream In Java"
},
{
"code": null,
"e": 5106,
"s": 5085,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5127,
"s": 5106,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5146,
"s": 5127,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5163,
"s": 5146,
"text": "Generics in Java"
},
{
"code": null,
"e": 5193,
"s": 5163,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5219,
"s": 5193,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5235,
"s": 5219,
"text": "Strings in Java"
},
{
"code": null,
"e": 5272,
"s": 5235,
"text": "Differences between JDK, JRE and JVM"
}
] |
Comments in C++
|
Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example −
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
A comment can also start with //, extending to the end of the line. For example −
#include <iostream>
using namespace std;
main() {
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following result −
Hello World
Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of comment within the other kind. For example −
/* Comment out printing of Hello World:
cout << "Hello World"; // prints Hello World
|
[
{
"code": null,
"e": 2645,
"s": 2452,
"text": "Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments."
},
{
"code": null,
"e": 2768,
"s": 2645,
"text": "C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler."
},
{
"code": null,
"e": 2826,
"s": 2768,
"text": "C++ comments start with /* and end with */. For example −"
},
{
"code": null,
"e": 2905,
"s": 2826,
"text": "/* This is a comment */\n\n/* C++ comments can also\n * span multiple lines\n*/\n"
},
{
"code": null,
"e": 2987,
"s": 2905,
"text": "A comment can also start with //, extending to the end of the line. For example −"
},
{
"code": null,
"e": 3105,
"s": 2987,
"text": "#include <iostream>\nusing namespace std;\n\nmain() {\n cout << \"Hello World\"; // prints Hello World\n \n return 0;\n}"
},
{
"code": null,
"e": 3232,
"s": 3105,
"text": "When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following result −"
},
{
"code": null,
"e": 3245,
"s": 3232,
"text": "Hello World\n"
},
{
"code": null,
"e": 3446,
"s": 3245,
"text": "Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can \"nest\" one kind of comment within the other kind. For example −"
}
] |
Draw Colourful Star Pattern in Turtle – Python
|
08 Jun, 2020
In this article we will use Python’s turtle library to draw a spiral of stars, filled with randomly generated colours. We can generate different patterns by varying some parameters.
modules required:
turtle:
turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas.turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics.
Explanation:First we set each of the parameters for the spiral: number of stars, exterior angle of the stars and angle of rotation for the spiral. The colours are chosen randomly by choosing three random integers for rgb values, and so each time we get a different colour combination.In the implementation below, we will draw a pattern of 30 stars, with exterior angle 144 degrees and angle of rotation 18 degrees.
from turtle import * import random speed(speed ='fastest') def draw(n, x, angle): # loop for number of stars for i in range(n): colormode(255) # choosing random integers # between 0 and 255 # to generate random rgb values a = random.randint(0, 255) b = random.randint(0, 255) c = random.randint(0, 255) # setting the outline # and fill colour pencolor(a, b, c) fillcolor(a, b, c) # begins filling the star begin_fill() # loop for drawing each star for j in range(5): forward(5 * n-5 * i) right(x) forward(5 * n-5 * i) right(72 - x) # colour filling complete end_fill() # rotating for # the next star rt(angle) # setting the parametersn = 30 # number of starsx = 144 # exterior angle of each starangle = 18 # angle of rotation for the spiral draw(n, x, angle)
Output:
By changing the exterior angle to 72, we can get a pattern of pentagons as such:
20 pentagons, 18 degree spiral
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 234,
"s": 52,
"text": "In this article we will use Python’s turtle library to draw a spiral of stars, filled with randomly generated colours. We can generate different patterns by varying some parameters."
},
{
"code": null,
"e": 252,
"s": 234,
"text": "modules required:"
},
{
"code": null,
"e": 260,
"s": 252,
"text": "turtle:"
},
{
"code": null,
"e": 496,
"s": 260,
"text": "turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas.turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics."
},
{
"code": null,
"e": 911,
"s": 496,
"text": "Explanation:First we set each of the parameters for the spiral: number of stars, exterior angle of the stars and angle of rotation for the spiral. The colours are chosen randomly by choosing three random integers for rgb values, and so each time we get a different colour combination.In the implementation below, we will draw a pattern of 30 stars, with exterior angle 144 degrees and angle of rotation 18 degrees."
},
{
"code": "from turtle import * import random speed(speed ='fastest') def draw(n, x, angle): # loop for number of stars for i in range(n): colormode(255) # choosing random integers # between 0 and 255 # to generate random rgb values a = random.randint(0, 255) b = random.randint(0, 255) c = random.randint(0, 255) # setting the outline # and fill colour pencolor(a, b, c) fillcolor(a, b, c) # begins filling the star begin_fill() # loop for drawing each star for j in range(5): forward(5 * n-5 * i) right(x) forward(5 * n-5 * i) right(72 - x) # colour filling complete end_fill() # rotating for # the next star rt(angle) # setting the parametersn = 30 # number of starsx = 144 # exterior angle of each starangle = 18 # angle of rotation for the spiral draw(n, x, angle)",
"e": 1974,
"s": 911,
"text": null
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Output:"
},
{
"code": null,
"e": 2063,
"s": 1982,
"text": "By changing the exterior angle to 72, we can get a pattern of pentagons as such:"
},
{
"code": null,
"e": 2094,
"s": 2063,
"text": "20 pentagons, 18 degree spiral"
},
{
"code": null,
"e": 2108,
"s": 2094,
"text": "Python-turtle"
},
{
"code": null,
"e": 2115,
"s": 2108,
"text": "Python"
}
] |
Search in an array of strings where non-empty strings are sorted
|
14 Sep, 2021
Given an array of strings. The array has both empty and non-empty strings. All non-empty strings are in sorted order. Empty strings can be present anywhere between non-empty strings.
Examples:
Input : arr[] = {"for", "", "", "", "geeks",
"ide", "", "practice", "" ,
"", "quiz", "", ""};
str = "quiz"
Output : 10
The string "quiz" is present at index 10 in
given array.
A simple solution is to linearly search given str in array of strings.
A better solution is to do modified Binary Search. Like normal binary search, we compare given str with middle string. If middle string is empty, we find the closest non-empty string x (by linearly searching on both sides). Once we find x, we do standard binary search, i.e., we compare given str with x. If str is same as x, we return index of x. if str is greater, we recur for right half, else we recur for left half.
Below is the implementation of the idea:
C++
Java
Python3
Javascript
// C++ program to find location of a str in// an array of strings which is sorted and// has empty strings between strings.#include <bits/stdc++.h>using namespace std; // Compare two string equals are notint compareStrings(string str1, string str2){ int i = 0; while (str1[i] == str2[i] && str1[i] != '\0') i++; if (str1[i] > str2[i]) return -1; return (str1[i] < str2[i]);} // Main function to find string locationint searchStr(string arr[], string str, int first, int last){ if (first > last) return -1; // Move mid to the middle int mid = (last+first)/2; // If mid is empty , find closest non-empty string if (arr[mid].empty()) { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. int left = mid - 1; int right = mid + 1; while (true) { if (left < first && right > last) return -1; if (right<=last && !arr[right].empty()) { mid = right; break; } if (left>=first && !arr[left].empty()) { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid+1, last); // If str is smaller than mid return searchStr(arr, str, first, mid-1);} // Driver Codeint main(){ // Input arr of Strings. string arr[] = {"for", "", "", "", "geeks", "ide", "", "practice", "" , "", "quiz", "", ""}; // input Search String string str = "quiz"; int n = sizeof(arr)/sizeof(arr[0]); cout << searchStr(arr, str, 0, n-1); return 0;}
// Java program to find location of a str in// an array of strings which is sorted and// has empty strings between strings.import java.util.*; class GFG{ // Compare two string equals are not static int compareStrings(String str1, String str2) { int i = 0; while (i < str1.length() - 1 && str1.charAt(i) == str2.charAt(i)) i++; if (str1.charAt(i) > str2.charAt(i)) return -1; if (str1.charAt(i) < str2.charAt(i)) return 1; else return 0; } // Main function to find string location static int searchStr(String[] arr, String str, int first, int last) { if (first > last) return -1; // Move mid to the middle int mid = (last + first) / 2; // If mid is empty, // find closest non-empty string if (arr[mid].isEmpty()) { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. int left = mid - 1; int right = mid + 1; while (true) { if (left < right && right > last) return -1; if (right <= last && !arr[right].isEmpty()) { mid = right; break; } if (left >= right && !arr[left].isEmpty()) { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid + 1, last); // If str is smaller than mid return searchStr(arr, str, first, mid - 1); } // Driver Code public static void main(String[] args) { // Input arr of Strings. String[] arr = { "for", "", "", "", "geeks", "ide", "", "practice", "", "", "quiz", "", "" }; // input Search String String str = "quiz"; int n = arr.length; System.out.println(searchStr(arr, str, 0, n - 1)); }} // This code is contributed by// sanjeev2552
# Python3 program to find the location of# an str in an array of strings which is sorted# and has empty strings between strings. # Compare two string equals are notdef compareStrings(str1, str2): i = 0 while i < len(str1) - 1 and str1[i] == str2[i]: i += 1 if str1[i] > str2[i]: return -1 return str1[i] < str2[i] # Main function to find string locationdef searchStr(arr, string, first, last): if first > last: return -1 # Move mid to the middle mid = (last + first) // 2 # If mid is empty , find closest non-empty string if len(arr[mid]) == 0: # If mid is empty, search in both sides of mid # and find the closest non-empty string, and # set mid accordingly. left, right = mid - 1, mid + 1 while True: if left < first and right > last: return -1 if right <= last and len(arr[right]) != 0: mid = right break if left >= first and len(arr[left]) != 0: mid = left break right += 1 left -= 1 # If str is found at mid if compareStrings(string, arr[mid]) == 0: return mid # If str is greater than mid if compareStrings(string, arr[mid]) < 0: return searchStr(arr, string, mid+1, last) # If str is smaller than mid return searchStr(arr, string, first, mid-1) # Driver Codeif __name__ == "__main__": # Input arr of Strings. arr = ["for", "", "", "", "geeks", "ide", "", "practice", "" , "", "quiz", "", ""] # input Search String string = "quiz" n = len(arr) print(searchStr(arr, string, 0, n-1)) # This code is contributed by Rituraj Jain
<script> // Javascript program to find location of a str in // an array of strings which is sorted and // has empty strings between strings. // Compare two string equals are not function compareStrings(str1, str2) { let i = 0; while (i < str1.length - 1 && str1[i] == str2[i]) i++; if (str1[i] > str2[i]) return -1; if (str1[i] < str2[i]) return 1; else return 0; } // Main function to find string location function searchStr(arr, str, first, last) { if (first > last) return -1; // Move mid to the middle let mid = parseInt((last + first) / 2, 10); // If mid is empty, // find closest non-empty string if (arr[mid] == "") { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. let left = mid - 1; let right = mid + 1; while (true) { if (left < right && right > last) return -1; if (right <= last && arr[right] != "") { mid = right; break; } if (left >= right && !arr[left] == "") { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid + 1, last); // If str is smaller than mid return searchStr(arr, str, first, mid - 1); } // Input arr of Strings. let arr = [ "for", "", "", "", "geeks", "ide", "", "practice", "", "", "quiz", "", "" ]; // input Search String let str = "quiz"; let n = arr.length; document.write(searchStr(arr, str, 0, n - 1)); // This code is contributed by vaibhavrabadiya3.</script>
Output:
10
Using linear search would take us O(L*N), where L is the string comparison. To optimize the runtime, we use binary search making the time complexity O(L(logN)).
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rituraj_jain
sanjeev2552
azadug
vaibhavrabadiya3
arorakashish0911
Binary Search
Searching
Strings
Searching
Strings
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 237,
"s": 54,
"text": "Given an array of strings. The array has both empty and non-empty strings. All non-empty strings are in sorted order. Empty strings can be present anywhere between non-empty strings."
},
{
"code": null,
"e": 248,
"s": 237,
"text": "Examples: "
},
{
"code": null,
"e": 479,
"s": 248,
"text": "Input : arr[] = {\"for\", \"\", \"\", \"\", \"geeks\", \n \"ide\", \"\", \"practice\", \"\" , \n \"\", \"quiz\", \"\", \"\"};\n str = \"quiz\"\nOutput : 10\nThe string \"quiz\" is present at index 10 in \ngiven array."
},
{
"code": null,
"e": 550,
"s": 479,
"text": "A simple solution is to linearly search given str in array of strings."
},
{
"code": null,
"e": 971,
"s": 550,
"text": "A better solution is to do modified Binary Search. Like normal binary search, we compare given str with middle string. If middle string is empty, we find the closest non-empty string x (by linearly searching on both sides). Once we find x, we do standard binary search, i.e., we compare given str with x. If str is same as x, we return index of x. if str is greater, we recur for right half, else we recur for left half."
},
{
"code": null,
"e": 1012,
"s": 971,
"text": "Below is the implementation of the idea:"
},
{
"code": null,
"e": 1016,
"s": 1012,
"text": "C++"
},
{
"code": null,
"e": 1021,
"s": 1016,
"text": "Java"
},
{
"code": null,
"e": 1029,
"s": 1021,
"text": "Python3"
},
{
"code": null,
"e": 1040,
"s": 1029,
"text": "Javascript"
},
{
"code": "// C++ program to find location of a str in// an array of strings which is sorted and// has empty strings between strings.#include <bits/stdc++.h>using namespace std; // Compare two string equals are notint compareStrings(string str1, string str2){ int i = 0; while (str1[i] == str2[i] && str1[i] != '\\0') i++; if (str1[i] > str2[i]) return -1; return (str1[i] < str2[i]);} // Main function to find string locationint searchStr(string arr[], string str, int first, int last){ if (first > last) return -1; // Move mid to the middle int mid = (last+first)/2; // If mid is empty , find closest non-empty string if (arr[mid].empty()) { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. int left = mid - 1; int right = mid + 1; while (true) { if (left < first && right > last) return -1; if (right<=last && !arr[right].empty()) { mid = right; break; } if (left>=first && !arr[left].empty()) { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid+1, last); // If str is smaller than mid return searchStr(arr, str, first, mid-1);} // Driver Codeint main(){ // Input arr of Strings. string arr[] = {\"for\", \"\", \"\", \"\", \"geeks\", \"ide\", \"\", \"practice\", \"\" , \"\", \"quiz\", \"\", \"\"}; // input Search String string str = \"quiz\"; int n = sizeof(arr)/sizeof(arr[0]); cout << searchStr(arr, str, 0, n-1); return 0;}",
"e": 2976,
"s": 1040,
"text": null
},
{
"code": "// Java program to find location of a str in// an array of strings which is sorted and// has empty strings between strings.import java.util.*; class GFG{ // Compare two string equals are not static int compareStrings(String str1, String str2) { int i = 0; while (i < str1.length() - 1 && str1.charAt(i) == str2.charAt(i)) i++; if (str1.charAt(i) > str2.charAt(i)) return -1; if (str1.charAt(i) < str2.charAt(i)) return 1; else return 0; } // Main function to find string location static int searchStr(String[] arr, String str, int first, int last) { if (first > last) return -1; // Move mid to the middle int mid = (last + first) / 2; // If mid is empty, // find closest non-empty string if (arr[mid].isEmpty()) { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. int left = mid - 1; int right = mid + 1; while (true) { if (left < right && right > last) return -1; if (right <= last && !arr[right].isEmpty()) { mid = right; break; } if (left >= right && !arr[left].isEmpty()) { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid + 1, last); // If str is smaller than mid return searchStr(arr, str, first, mid - 1); } // Driver Code public static void main(String[] args) { // Input arr of Strings. String[] arr = { \"for\", \"\", \"\", \"\", \"geeks\", \"ide\", \"\", \"practice\", \"\", \"\", \"quiz\", \"\", \"\" }; // input Search String String str = \"quiz\"; int n = arr.length; System.out.println(searchStr(arr, str, 0, n - 1)); }} // This code is contributed by// sanjeev2552",
"e": 5410,
"s": 2976,
"text": null
},
{
"code": "# Python3 program to find the location of# an str in an array of strings which is sorted# and has empty strings between strings. # Compare two string equals are notdef compareStrings(str1, str2): i = 0 while i < len(str1) - 1 and str1[i] == str2[i]: i += 1 if str1[i] > str2[i]: return -1 return str1[i] < str2[i] # Main function to find string locationdef searchStr(arr, string, first, last): if first > last: return -1 # Move mid to the middle mid = (last + first) // 2 # If mid is empty , find closest non-empty string if len(arr[mid]) == 0: # If mid is empty, search in both sides of mid # and find the closest non-empty string, and # set mid accordingly. left, right = mid - 1, mid + 1 while True: if left < first and right > last: return -1 if right <= last and len(arr[right]) != 0: mid = right break if left >= first and len(arr[left]) != 0: mid = left break right += 1 left -= 1 # If str is found at mid if compareStrings(string, arr[mid]) == 0: return mid # If str is greater than mid if compareStrings(string, arr[mid]) < 0: return searchStr(arr, string, mid+1, last) # If str is smaller than mid return searchStr(arr, string, first, mid-1) # Driver Codeif __name__ == \"__main__\": # Input arr of Strings. arr = [\"for\", \"\", \"\", \"\", \"geeks\", \"ide\", \"\", \"practice\", \"\" , \"\", \"quiz\", \"\", \"\"] # input Search String string = \"quiz\" n = len(arr) print(searchStr(arr, string, 0, n-1)) # This code is contributed by Rituraj Jain",
"e": 7204,
"s": 5410,
"text": null
},
{
"code": "<script> // Javascript program to find location of a str in // an array of strings which is sorted and // has empty strings between strings. // Compare two string equals are not function compareStrings(str1, str2) { let i = 0; while (i < str1.length - 1 && str1[i] == str2[i]) i++; if (str1[i] > str2[i]) return -1; if (str1[i] < str2[i]) return 1; else return 0; } // Main function to find string location function searchStr(arr, str, first, last) { if (first > last) return -1; // Move mid to the middle let mid = parseInt((last + first) / 2, 10); // If mid is empty, // find closest non-empty string if (arr[mid] == \"\") { // If mid is empty, search in both sides of mid // and find the closest non-empty string, and // set mid accordingly. let left = mid - 1; let right = mid + 1; while (true) { if (left < right && right > last) return -1; if (right <= last && arr[right] != \"\") { mid = right; break; } if (left >= right && !arr[left] == \"\") { mid = left; break; } right++; left--; } } // If str is found at mid if (compareStrings(str, arr[mid]) == 0) return mid; // If str is greater than mid if (compareStrings(str, arr[mid]) < 0) return searchStr(arr, str, mid + 1, last); // If str is smaller than mid return searchStr(arr, str, first, mid - 1); } // Input arr of Strings. let arr = [ \"for\", \"\", \"\", \"\", \"geeks\", \"ide\", \"\", \"practice\", \"\", \"\", \"quiz\", \"\", \"\" ]; // input Search String let str = \"quiz\"; let n = arr.length; document.write(searchStr(arr, str, 0, n - 1)); // This code is contributed by vaibhavrabadiya3.</script>",
"e": 9405,
"s": 7204,
"text": null
},
{
"code": null,
"e": 9414,
"s": 9405,
"text": "Output: "
},
{
"code": null,
"e": 9419,
"s": 9414,
"text": " 10"
},
{
"code": null,
"e": 9581,
"s": 9419,
"text": "Using linear search would take us O(L*N), where L is the string comparison. To optimize the runtime, we use binary search making the time complexity O(L(logN)). "
},
{
"code": null,
"e": 10008,
"s": 9581,
"text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10021,
"s": 10008,
"text": "rituraj_jain"
},
{
"code": null,
"e": 10033,
"s": 10021,
"text": "sanjeev2552"
},
{
"code": null,
"e": 10040,
"s": 10033,
"text": "azadug"
},
{
"code": null,
"e": 10057,
"s": 10040,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 10074,
"s": 10057,
"text": "arorakashish0911"
},
{
"code": null,
"e": 10088,
"s": 10074,
"text": "Binary Search"
},
{
"code": null,
"e": 10098,
"s": 10088,
"text": "Searching"
},
{
"code": null,
"e": 10106,
"s": 10098,
"text": "Strings"
},
{
"code": null,
"e": 10116,
"s": 10106,
"text": "Searching"
},
{
"code": null,
"e": 10124,
"s": 10116,
"text": "Strings"
},
{
"code": null,
"e": 10138,
"s": 10124,
"text": "Binary Search"
},
{
"code": null,
"e": 10236,
"s": 10138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10250,
"s": 10236,
"text": "Binary Search"
},
{
"code": null,
"e": 10318,
"s": 10250,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10332,
"s": 10318,
"text": "Linear Search"
},
{
"code": null,
"e": 10388,
"s": 10332,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 10436,
"s": 10388,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 10482,
"s": 10436,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10507,
"s": 10482,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10567,
"s": 10507,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10582,
"s": 10567,
"text": "C++ Data Types"
}
] |
Scala sum Map values
|
26 Jul, 2019
In Scala, the sum of the map elements can be done by utilizing foldLeft method.
Syntax : m1.foldLeft(0)(_+_._1)
Here, m1 is used for a Map, foldLeft is a method that takes an initial value zero. it will take previous result and add it to the next map key value.
Return Type: It returns the sum of all the elements of the map.
Example #1:
// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs") // Applying sum method val result = m1.foldLeft(0)(_+_._1) // Displays output println(result) }}
6
Here, zero in the foldLeft method is the initial value.Example #2:
// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 1 -> "for", 1 -> "for") // Applying sum method val result = m1.foldLeft(0)(_+_._1) // Displays output println(result) }}
4
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "In Scala, the sum of the map elements can be done by utilizing foldLeft method."
},
{
"code": null,
"e": 140,
"s": 108,
"text": "Syntax : m1.foldLeft(0)(_+_._1)"
},
{
"code": null,
"e": 290,
"s": 140,
"text": "Here, m1 is used for a Map, foldLeft is a method that takes an initial value zero. it will take previous result and add it to the next map key value."
},
{
"code": null,
"e": 354,
"s": 290,
"text": "Return Type: It returns the sum of all the elements of the map."
},
{
"code": null,
"e": 366,
"s": 354,
"text": "Example #1:"
},
{
"code": "// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 1 -> \"for\", 2 -> \"cs\") // Applying sum method val result = m1.foldLeft(0)(_+_._1) // Displays output println(result) }}",
"e": 732,
"s": 366,
"text": null
},
{
"code": null,
"e": 735,
"s": 732,
"text": "6\n"
},
{
"code": null,
"e": 802,
"s": 735,
"text": "Here, zero in the foldLeft method is the initial value.Example #2:"
},
{
"code": "// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 1 -> \"for\", 1 -> \"for\") // Applying sum method val result = m1.foldLeft(0)(_+_._1) // Displays output println(result) }}",
"e": 1169,
"s": 802,
"text": null
},
{
"code": null,
"e": 1172,
"s": 1169,
"text": "4\n"
},
{
"code": null,
"e": 1178,
"s": 1172,
"text": "Scala"
},
{
"code": null,
"e": 1188,
"s": 1178,
"text": "Scala-Map"
},
{
"code": null,
"e": 1201,
"s": 1188,
"text": "Scala-Method"
},
{
"code": null,
"e": 1207,
"s": 1201,
"text": "Scala"
},
{
"code": null,
"e": 1305,
"s": 1207,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1331,
"s": 1305,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1353,
"s": 1331,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 1406,
"s": 1353,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1418,
"s": 1406,
"text": "Scala Lists"
},
{
"code": null,
"e": 1437,
"s": 1418,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1452,
"s": 1437,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1471,
"s": 1452,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1516,
"s": 1471,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 1543,
"s": 1516,
"text": "Lambda Expression in Scala"
}
] |
Count distinct Bitwise OR of all Subarrays
|
14 Jun, 2022
Given an array A of non-negative integers, where . The task is to count number of distinct possible results obtained by taking the bitwise OR of all the elements in all possible Subarrays.Examples:
Input: A = [1, 2]
Output: 3
Explanation: The possible subarrays are [1], [2], [1, 2].
These Bitwise OR of subarrays are 1, 2, 3.
There are 3 distinct values, so the answer is 3.
Input: A = [1, 2, 4]
Output: 6
Explanation: The possible distinct values are 1, 2, 3, 4, 6, and 7.
Approach: The Naive approach is to generate all possible subarrays and take bitwise OR of all elements in the subarray. Store each result in set and return length of the set. Efficient Approach: We can make the above approach better. The Naive approach is to calculate all possible result where, res(i, j) = A[i] | A[i+1] | ... | A[j]. However we can speed this up by taking note of the fact that res(i, j+1) = res(i, j) | A[j+1]. At the kth step, say we have all of the res(i, k) in some set pre. Then we can find the next pre set (for k -> k+1) by using res(i, k+1) = res(i, k) | A[k+1].However, the number of unique values in this set pre is atmost 32, since the list res(k, k), res(k-1, k), res(k-2, k), ... is monotone increasing, and any subsequent values that are different from previous must have more 1’s in it’s binary representation which can have maximum of 32 ones.Below is the implementation of above approach.
Python
# Python implementation of the above approach # function to return count of distinct bitwise ORdef subarrayBitwiseOR(A): # res contains distinct values res = set() pre = {0} for x in A: pre = {x | y for y in pre} | {x} res |= pre return len(res) # Driver programA = [1, 2, 4] # print required answerprint(subarrayBitwiseOR(A)) # This code is written by# Sanjit_Prasad
6
Time Complexity: O(N*log(K)), where N is the length of A, and K is the maximum size of elements in A.
C++ implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to calculate count of// distinct bitwise OR of all// subarrays.int distintBitwiseOR(int arr[], int n){ unordered_set<int> ans, prev; for (int i = 0; i < n; i++) { unordered_set<int> ne; for (auto x : prev) ne.insert(arr[i] | x); ne.insert(arr[i]); for (auto x : ne) ans.insert(x); prev = ne; } return ans.size();} // Driver Codeint main(){ int n = 3; int arr[] = { 1, 2, 4 }; cout << distintBitwiseOR(arr, n); return 0;}
// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG{ // function to calculate count of// distinct bitwise OR of all// subarrays. static int distintBitwiseOR(int arr[], int n) { HashSet<Integer>ans = new HashSet<>(); HashSet<Integer>prev = new HashSet<>(); for(int i = 0; i < n; i++) { HashSet<Integer>ne = new HashSet<>(); ne.add(arr[i]); for(int x :prev) { ne.add(arr[i]|x); } for(int x :ne) { ans.add(x); } prev = ne; } return ans.size(); } // Driver code public static void main (String[] args) { int n = 3; int arr[] = { 1, 2, 4 }; System.out.println(distintBitwiseOR(arr, n)); }} // This code is contributed by iramkhalid24.
# Python implementation of the above approach # function to calculate count of# distinct bitwise OR of all# subarrays.def distintBitwiseOR(arr,n): ans,prev = set(), set() for i in range(n): ne = set() for x in prev: ne.add(arr[i] | x) ne.add(arr[i]) for x in ne: ans.add(x) prev = ne return len(ans) # Driver Coden = 3arr = [ 1, 2, 4 ] print(distintBitwiseOR(arr, n)) # This code is written by Shinjanpatra
// C# implementation of the above approachusing System;using System.Collections.Generic; public class GFG{ // function to calculate count of // distinct bitwise OR of all // subarrays. static int distintBitwiseOR(int[] arr, int n) { HashSet<int> ans = new HashSet<int>(); HashSet<int> prev = new HashSet<int>(); for (int i = 0; i < n; i++) { HashSet<int> ne = new HashSet<int>(); ne.Add(arr[i]); foreach(var x in prev) { ne.Add(arr[i] | x); } foreach(var x in ne) { ans.Add(x); } prev = ne; } return ans.Count; } // Driver code public static void Main(string[] args) { int n = 3; int[] arr = { 1, 2, 4 }; // Function call Console.WriteLine(distintBitwiseOR(arr, n)); }} // This code is contributed by phasing17
<script> // JavaScript implementation of the above approach // function to calculate count of// distinct bitwise OR of all// subarrays.function distintBitwiseOR(arr,n){ let ans = new Set(), prev = new Set(); for (let i = 0; i < n; i++) { let ne = new Set(); for (let x of prev) ne.add(arr[i] | x); ne.add(arr[i]); for (let x of ne) ans.add(x); prev = ne; } return ans.size;} // Driver Code let n = 3;let arr = [ 1, 2, 4 ]; document.write(distintBitwiseOR(arr, n)); // This code is written by Shinjanpatra </script>
6
pawanharwani11
iramkhalid24
shinjanpatra
phasing17
Bitwise-OR
Arrays
Bit Magic
Arrays
Bit Magic
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
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Little and Big Endian Mystery
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 254,
"s": 54,
"text": "Given an array A of non-negative integers, where . The task is to count number of distinct possible results obtained by taking the bitwise OR of all the elements in all possible Subarrays.Examples: "
},
{
"code": null,
"e": 532,
"s": 254,
"text": "Input: A = [1, 2]\nOutput: 3\nExplanation: The possible subarrays are [1], [2], [1, 2].\nThese Bitwise OR of subarrays are 1, 2, 3.\nThere are 3 distinct values, so the answer is 3.\n\nInput: A = [1, 2, 4]\nOutput: 6\nExplanation: The possible distinct values are 1, 2, 3, 4, 6, and 7."
},
{
"code": null,
"e": 1459,
"s": 532,
"text": "Approach: The Naive approach is to generate all possible subarrays and take bitwise OR of all elements in the subarray. Store each result in set and return length of the set. Efficient Approach: We can make the above approach better. The Naive approach is to calculate all possible result where, res(i, j) = A[i] | A[i+1] | ... | A[j]. However we can speed this up by taking note of the fact that res(i, j+1) = res(i, j) | A[j+1]. At the kth step, say we have all of the res(i, k) in some set pre. Then we can find the next pre set (for k -> k+1) by using res(i, k+1) = res(i, k) | A[k+1].However, the number of unique values in this set pre is atmost 32, since the list res(k, k), res(k-1, k), res(k-2, k), ... is monotone increasing, and any subsequent values that are different from previous must have more 1’s in it’s binary representation which can have maximum of 32 ones.Below is the implementation of above approach. "
},
{
"code": null,
"e": 1466,
"s": 1459,
"text": "Python"
},
{
"code": "# Python implementation of the above approach # function to return count of distinct bitwise ORdef subarrayBitwiseOR(A): # res contains distinct values res = set() pre = {0} for x in A: pre = {x | y for y in pre} | {x} res |= pre return len(res) # Driver programA = [1, 2, 4] # print required answerprint(subarrayBitwiseOR(A)) # This code is written by# Sanjit_Prasad",
"e": 1868,
"s": 1466,
"text": null
},
{
"code": null,
"e": 1870,
"s": 1868,
"text": "6"
},
{
"code": null,
"e": 1972,
"s": 1870,
"text": "Time Complexity: O(N*log(K)), where N is the length of A, and K is the maximum size of elements in A."
},
{
"code": null,
"e": 2014,
"s": 1972,
"text": "C++ implementation of the above approach."
},
{
"code": null,
"e": 2018,
"s": 2014,
"text": "C++"
},
{
"code": null,
"e": 2023,
"s": 2018,
"text": "Java"
},
{
"code": null,
"e": 2031,
"s": 2023,
"text": "Python3"
},
{
"code": null,
"e": 2034,
"s": 2031,
"text": "C#"
},
{
"code": null,
"e": 2045,
"s": 2034,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to calculate count of// distinct bitwise OR of all// subarrays.int distintBitwiseOR(int arr[], int n){ unordered_set<int> ans, prev; for (int i = 0; i < n; i++) { unordered_set<int> ne; for (auto x : prev) ne.insert(arr[i] | x); ne.insert(arr[i]); for (auto x : ne) ans.insert(x); prev = ne; } return ans.size();} // Driver Codeint main(){ int n = 3; int arr[] = { 1, 2, 4 }; cout << distintBitwiseOR(arr, n); return 0;}",
"e": 2654,
"s": 2045,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG{ // function to calculate count of// distinct bitwise OR of all// subarrays. static int distintBitwiseOR(int arr[], int n) { HashSet<Integer>ans = new HashSet<>(); HashSet<Integer>prev = new HashSet<>(); for(int i = 0; i < n; i++) { HashSet<Integer>ne = new HashSet<>(); ne.add(arr[i]); for(int x :prev) { ne.add(arr[i]|x); } for(int x :ne) { ans.add(x); } prev = ne; } return ans.size(); } // Driver code public static void main (String[] args) { int n = 3; int arr[] = { 1, 2, 4 }; System.out.println(distintBitwiseOR(arr, n)); }} // This code is contributed by iramkhalid24.",
"e": 3558,
"s": 2654,
"text": null
},
{
"code": "# Python implementation of the above approach # function to calculate count of# distinct bitwise OR of all# subarrays.def distintBitwiseOR(arr,n): ans,prev = set(), set() for i in range(n): ne = set() for x in prev: ne.add(arr[i] | x) ne.add(arr[i]) for x in ne: ans.add(x) prev = ne return len(ans) # Driver Coden = 3arr = [ 1, 2, 4 ] print(distintBitwiseOR(arr, n)) # This code is written by Shinjanpatra",
"e": 4037,
"s": 3558,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;using System.Collections.Generic; public class GFG{ // function to calculate count of // distinct bitwise OR of all // subarrays. static int distintBitwiseOR(int[] arr, int n) { HashSet<int> ans = new HashSet<int>(); HashSet<int> prev = new HashSet<int>(); for (int i = 0; i < n; i++) { HashSet<int> ne = new HashSet<int>(); ne.Add(arr[i]); foreach(var x in prev) { ne.Add(arr[i] | x); } foreach(var x in ne) { ans.Add(x); } prev = ne; } return ans.Count; } // Driver code public static void Main(string[] args) { int n = 3; int[] arr = { 1, 2, 4 }; // Function call Console.WriteLine(distintBitwiseOR(arr, n)); }} // This code is contributed by phasing17",
"e": 4817,
"s": 4037,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // function to calculate count of// distinct bitwise OR of all// subarrays.function distintBitwiseOR(arr,n){ let ans = new Set(), prev = new Set(); for (let i = 0; i < n; i++) { let ne = new Set(); for (let x of prev) ne.add(arr[i] | x); ne.add(arr[i]); for (let x of ne) ans.add(x); prev = ne; } return ans.size;} // Driver Code let n = 3;let arr = [ 1, 2, 4 ]; document.write(distintBitwiseOR(arr, n)); // This code is written by Shinjanpatra </script>",
"e": 5406,
"s": 4817,
"text": null
},
{
"code": null,
"e": 5408,
"s": 5406,
"text": "6"
},
{
"code": null,
"e": 5425,
"s": 5410,
"text": "pawanharwani11"
},
{
"code": null,
"e": 5438,
"s": 5425,
"text": "iramkhalid24"
},
{
"code": null,
"e": 5451,
"s": 5438,
"text": "shinjanpatra"
},
{
"code": null,
"e": 5461,
"s": 5451,
"text": "phasing17"
},
{
"code": null,
"e": 5472,
"s": 5461,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 5479,
"s": 5472,
"text": "Arrays"
},
{
"code": null,
"e": 5489,
"s": 5479,
"text": "Bit Magic"
},
{
"code": null,
"e": 5496,
"s": 5489,
"text": "Arrays"
},
{
"code": null,
"e": 5506,
"s": 5496,
"text": "Bit Magic"
},
{
"code": null,
"e": 5604,
"s": 5506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5672,
"s": 5604,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5716,
"s": 5672,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5764,
"s": 5716,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5796,
"s": 5764,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5819,
"s": 5796,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 5846,
"s": 5819,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 5892,
"s": 5846,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 5960,
"s": 5892,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 5990,
"s": 5960,
"text": "Little and Big Endian Mystery"
}
] |
Angular forms FormControlName Directive - GeeksforGeeks
|
03 Jun, 2021
In this article, we are going to see what is FormControlName in Angular 10 and how to use it.
FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.
Syntax:
<form [FormControlName] ="name">
Exported from:
ReactiveFormsModule
Selectors:
[FormControlName]
Approach:
Create the Angular app to be used
In app.component.ts make an object that contain value for the input.
In app.component.html use FormControlName to get values.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ name: new FormControl(), rollno: new FormControl() }); get name(): any { return this.form.get('name'); } get rollno(): any { return this.form.get('rollno'); } onSubmit(): void { console.log(this.form.value); } }
app.component.html
<br><form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"> <input formControlName="rollno" placeholder="RollNo"> <br> <button type='submit'>Submit</button> <br> <br></form>
Output:
Reference: https://angular.io/api/forms/FormControlName
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 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25135,
"s": 25107,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25229,
"s": 25135,
"text": "In this article, we are going to see what is FormControlName in Angular 10 and how to use it."
},
{
"code": null,
"e": 25335,
"s": 25229,
"text": "FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name."
},
{
"code": null,
"e": 25343,
"s": 25335,
"text": "Syntax:"
},
{
"code": null,
"e": 25376,
"s": 25343,
"text": "<form [FormControlName] =\"name\">"
},
{
"code": null,
"e": 25391,
"s": 25376,
"text": "Exported from:"
},
{
"code": null,
"e": 25411,
"s": 25391,
"text": "ReactiveFormsModule"
},
{
"code": null,
"e": 25424,
"s": 25413,
"text": "Selectors:"
},
{
"code": null,
"e": 25442,
"s": 25424,
"text": "[FormControlName]"
},
{
"code": null,
"e": 25453,
"s": 25442,
"text": "Approach: "
},
{
"code": null,
"e": 25487,
"s": 25453,
"text": "Create the Angular app to be used"
},
{
"code": null,
"e": 25556,
"s": 25487,
"text": "In app.component.ts make an object that contain value for the input."
},
{
"code": null,
"e": 25613,
"s": 25556,
"text": "In app.component.html use FormControlName to get values."
},
{
"code": null,
"e": 25669,
"s": 25613,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 25680,
"s": 25669,
"text": "Example 1:"
},
{
"code": null,
"e": 25697,
"s": 25680,
"text": "app.component.ts"
},
{
"code": "import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ name: new FormControl(), rollno: new FormControl() }); get name(): any { return this.form.get('name'); } get rollno(): any { return this.form.get('rollno'); } onSubmit(): void { console.log(this.form.value); } }",
"e": 26270,
"s": 25697,
"text": null
},
{
"code": null,
"e": 26289,
"s": 26270,
"text": "app.component.html"
},
{
"code": "<br><form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <input formControlName=\"name\" placeholder=\"Name\"> <input formControlName=\"rollno\" placeholder=\"RollNo\"> <br> <button type='submit'>Submit</button> <br> <br></form>",
"e": 26517,
"s": 26289,
"text": null
},
{
"code": null,
"e": 26525,
"s": 26517,
"text": "Output:"
},
{
"code": null,
"e": 26581,
"s": 26525,
"text": "Reference: https://angular.io/api/forms/FormControlName"
},
{
"code": null,
"e": 26591,
"s": 26581,
"text": "Angular10"
},
{
"code": null,
"e": 26612,
"s": 26591,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 26622,
"s": 26612,
"text": "AngularJS"
},
{
"code": null,
"e": 26639,
"s": 26622,
"text": "Web Technologies"
},
{
"code": null,
"e": 26737,
"s": 26639,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26746,
"s": 26737,
"text": "Comments"
},
{
"code": null,
"e": 26759,
"s": 26746,
"text": "Old Comments"
},
{
"code": null,
"e": 26803,
"s": 26759,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 26867,
"s": 26803,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 26920,
"s": 26867,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 26944,
"s": 26920,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 26979,
"s": 26944,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27021,
"s": 26979,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27054,
"s": 27021,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27097,
"s": 27054,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27159,
"s": 27097,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Spring Boot - Enabling Swagger2
|
Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser.
To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
For Gradle users, add the following dependencies in your build.gradle file.
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
Now, add the @EnableSwagger2 annotation in your main Spring Boot application. The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application.
The code for main Spring Boot application is shown below −
package com.tutorialspoint.swaggerdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
Next, create Docket Bean to configure Swagger2 for your Spring Boot application. We need to define the base package to configure REST API(s) for Swagger2.
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.tutorialspoint.swaggerdemo")).build();
}
Now, add this bean in main Spring Boot application class file itself and your main Spring Boot application class will look as shown below −
package com.tutorialspoint.swaggerdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.tutorialspoint.swaggerdemo")).build();
}
}
Now, add the below Spring Boot Starter Web dependency in your build configuration file to write a REST Endpoints as shown below −
Maven users can add the following dependency in your pom.xml file −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradle users can add the following dependency in build.gradle file −
compile('org.springframework.boot:spring-boot-starter-web')
Now, the code to build two simple RESTful web services GET and POST in Rest Controller file is shown here −
package com.tutorialspoint.swaggerdemo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SwaggerAPIController {
@RequestMapping(value = "/products", method = RequestMethod.GET)
public List<String> getProducts() {
List<String> productsList = new ArrayList<>();
productsList.add("Honey");
productsList.add("Almond");
return productsList;
}
@RequestMapping(value = "/products", method = RequestMethod.POST)
public String createProduct() {
return "Product is saved successfully";
}
}
The complete build configuration file is given below −
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<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>com.tutorialspoint</groupId>
<artifactId>swagger-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>swagger-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
} dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
}
You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.
For Maven, you can use the command shown here −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command as shown here −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the command shown here −
java –jar <JARFILE>
Now, the application will start on the Tomcat port 8080 as shown −
Now, hit the URL in your web browser and see the Swagger API functionalities.
http://localhost:8080/swagger-ui.html
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3211,
"s": 3025,
"text": "Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser."
},
{
"code": null,
"e": 3340,
"s": 3211,
"text": "To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file."
},
{
"code": null,
"e": 3616,
"s": 3340,
"text": "<dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger2</artifactId>\n <version>2.7.0</version>\n</dependency>\n<dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger-ui</artifactId>\n <version>2.7.0</version>\n</dependency>"
},
{
"code": null,
"e": 3692,
"s": 3616,
"text": "For Gradle users, add the following dependencies in your build.gradle file."
},
{
"code": null,
"e": 3847,
"s": 3692,
"text": "compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'\ncompile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'\n"
},
{
"code": null,
"e": 4021,
"s": 3847,
"text": "Now, add the @EnableSwagger2 annotation in your main Spring Boot application. The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application."
},
{
"code": null,
"e": 4080,
"s": 4021,
"text": "The code for main Spring Boot application is shown below −"
},
{
"code": null,
"e": 4503,
"s": 4080,
"text": "package com.tutorialspoint.swaggerdemo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport springfox.documentation.swagger2.annotations.EnableSwagger2;\n\n@SpringBootApplication\n@EnableSwagger2\npublic class SwaggerDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(SwaggerDemoApplication.class, args);\n }\n}"
},
{
"code": null,
"e": 4658,
"s": 4503,
"text": "Next, create Docket Bean to configure Swagger2 for your Spring Boot application. We need to define the base package to configure REST API(s) for Swagger2."
},
{
"code": null,
"e": 4859,
"s": 4658,
"text": "@Bean\n public Docket productApi() {\n return new Docket(DocumentationType.SWAGGER_2).select()\n .apis(RequestHandlerSelectors.basePackage(\"com.tutorialspoint.swaggerdemo\")).build();\n }\n"
},
{
"code": null,
"e": 4999,
"s": 4859,
"text": "Now, add this bean in main Spring Boot application class file itself and your main Spring Boot application class will look as shown below −"
},
{
"code": null,
"e": 5855,
"s": 4999,
"text": "package com.tutorialspoint.swaggerdemo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\n\nimport springfox.documentation.builders.RequestHandlerSelectors;\nimport springfox.documentation.spi.DocumentationType;\nimport springfox.documentation.spring.web.plugins.Docket;\nimport springfox.documentation.swagger2.annotations.EnableSwagger2;\n\n@SpringBootApplication\n@EnableSwagger2\npublic class SwaggerDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(SwaggerDemoApplication.class, args);\n }\n @Bean\n public Docket productApi() {\n return new Docket(DocumentationType.SWAGGER_2).select()\n .apis(RequestHandlerSelectors.basePackage(\"com.tutorialspoint.swaggerdemo\")).build();\n }\n}"
},
{
"code": null,
"e": 5985,
"s": 5855,
"text": "Now, add the below Spring Boot Starter Web dependency in your build configuration file to write a REST Endpoints as shown below −"
},
{
"code": null,
"e": 6053,
"s": 5985,
"text": "Maven users can add the following dependency in your pom.xml file −"
},
{
"code": null,
"e": 6180,
"s": 6053,
"text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n"
},
{
"code": null,
"e": 6249,
"s": 6180,
"text": "Gradle users can add the following dependency in build.gradle file −"
},
{
"code": null,
"e": 6310,
"s": 6249,
"text": "compile('org.springframework.boot:spring-boot-starter-web')\n"
},
{
"code": null,
"e": 6418,
"s": 6310,
"text": "Now, the code to build two simple RESTful web services GET and POST in Rest Controller file is shown here −"
},
{
"code": null,
"e": 7168,
"s": 6418,
"text": "package com.tutorialspoint.swaggerdemo;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class SwaggerAPIController {\n @RequestMapping(value = \"/products\", method = RequestMethod.GET)\n public List<String> getProducts() {\n List<String> productsList = new ArrayList<>();\n productsList.add(\"Honey\");\n productsList.add(\"Almond\");\n return productsList;\n }\n @RequestMapping(value = \"/products\", method = RequestMethod.POST)\n public String createProduct() {\n return \"Product is saved successfully\";\n }\n}"
},
{
"code": null,
"e": 7223,
"s": 7168,
"text": "The complete build configuration file is given below −"
},
{
"code": null,
"e": 7239,
"s": 7223,
"text": "Maven – pom.xml"
},
{
"code": null,
"e": 9188,
"s": 7239,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.tutorialspoint</groupId>\n <artifactId>swagger-demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>swagger-demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath /> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n \n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger2</artifactId>\n <version>2.7.0</version>\n </dependency>\n\n <dependency>\n <groupId>io.springfox</groupId>\n <artifactId>springfox-swagger-ui</artifactId>\n <version>2.7.0</version>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 9210,
"s": 9188,
"text": "Gradle – build.gradle"
},
{
"code": null,
"e": 9953,
"s": 9210,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n} dependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'\n compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'\n}"
},
{
"code": null,
"e": 10077,
"s": 9953,
"text": "You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands."
},
{
"code": null,
"e": 10125,
"s": 10077,
"text": "For Maven, you can use the command shown here −"
},
{
"code": null,
"e": 10144,
"s": 10125,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 10221,
"s": 10144,
"text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 10273,
"s": 10221,
"text": "For Gradle, you can use the command as shown here −"
},
{
"code": null,
"e": 10293,
"s": 10273,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 10377,
"s": 10293,
"text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 10433,
"s": 10377,
"text": "Now, run the JAR file by using the command shown here −"
},
{
"code": null,
"e": 10455,
"s": 10433,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 10522,
"s": 10455,
"text": "Now, the application will start on the Tomcat port 8080 as shown −"
},
{
"code": null,
"e": 10600,
"s": 10522,
"text": "Now, hit the URL in your web browser and see the Swagger API functionalities."
},
{
"code": null,
"e": 10638,
"s": 10600,
"text": "http://localhost:8080/swagger-ui.html"
},
{
"code": null,
"e": 10672,
"s": 10638,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10686,
"s": 10672,
"text": " Karthikeya T"
},
{
"code": null,
"e": 10719,
"s": 10686,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10734,
"s": 10719,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 10769,
"s": 10734,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10781,
"s": 10769,
"text": " Senol Atac"
},
{
"code": null,
"e": 10816,
"s": 10781,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10828,
"s": 10816,
"text": " Senol Atac"
},
{
"code": null,
"e": 10863,
"s": 10828,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10875,
"s": 10863,
"text": " Senol Atac"
},
{
"code": null,
"e": 10908,
"s": 10875,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10920,
"s": 10908,
"text": " Senol Atac"
},
{
"code": null,
"e": 10927,
"s": 10920,
"text": " Print"
},
{
"code": null,
"e": 10938,
"s": 10927,
"text": " Add Notes"
}
] |
How to reset all form values using a button in HTML ? - GeeksforGeeks
|
30 Jun, 2021
You can easily reset all form values using the HTML button using <input type=”reset”> attribute. Clicking the reset button restores the form to its original state (the default value) before the user started entering values into the fields, selecting radio buttons, checkboxes, etc. There could be many scenarios.
In this article, we are going to learn about how to clear the input field.
Syntax:
<input type="reset">
Example:
HTML
<!DOCTYPE html><html> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <form> <input type="text" placeholder="Email address" id="email" name="email" /> <br /><br /> <input type="password" placeholder="Password" id="pin" name="password" maxlength="8" /> <br /><br /> <input type="reset" value="Reset" style="background-color: red; color: white" /> <input type="submit" value="Submit" style="background-color: green; color: white" /> </form> </center></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.
HTML-Attributes
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24894,
"s": 24866,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25208,
"s": 24894,
"text": "You can easily reset all form values using the HTML button using <input type=”reset”> attribute. Clicking the reset button restores the form to its original state (the default value) before the user started entering values into the fields, selecting radio buttons, checkboxes, etc. There could be many scenarios. "
},
{
"code": null,
"e": 25283,
"s": 25208,
"text": "In this article, we are going to learn about how to clear the input field."
},
{
"code": null,
"e": 25291,
"s": 25283,
"text": "Syntax:"
},
{
"code": null,
"e": 25312,
"s": 25291,
"text": "<input type=\"reset\">"
},
{
"code": null,
"e": 25321,
"s": 25312,
"text": "Example:"
},
{
"code": null,
"e": 25326,
"s": 25321,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <form> <input type=\"text\" placeholder=\"Email address\" id=\"email\" name=\"email\" /> <br /><br /> <input type=\"password\" placeholder=\"Password\" id=\"pin\" name=\"password\" maxlength=\"8\" /> <br /><br /> <input type=\"reset\" value=\"Reset\" style=\"background-color: red; color: white\" /> <input type=\"submit\" value=\"Submit\" style=\"background-color: green; color: white\" /> </form> </center></body> </html>",
"e": 26076,
"s": 25326,
"text": null
},
{
"code": null,
"e": 26084,
"s": 26076,
"text": "Output:"
},
{
"code": null,
"e": 26221,
"s": 26084,
"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": 26237,
"s": 26221,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26252,
"s": 26237,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26259,
"s": 26252,
"text": "Picked"
},
{
"code": null,
"e": 26264,
"s": 26259,
"text": "HTML"
},
{
"code": null,
"e": 26281,
"s": 26264,
"text": "Web Technologies"
},
{
"code": null,
"e": 26286,
"s": 26281,
"text": "HTML"
},
{
"code": null,
"e": 26384,
"s": 26286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26408,
"s": 26384,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26445,
"s": 26408,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26465,
"s": 26445,
"text": "Angular File Upload"
},
{
"code": null,
"e": 26494,
"s": 26465,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26522,
"s": 26494,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 26564,
"s": 26522,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26597,
"s": 26564,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26640,
"s": 26597,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26685,
"s": 26640,
"text": "Convert a string to an integer in JavaScript"
}
] |
Bootstrap class pull-left
|
Float an element to the left with class pull-left.
You can try to run the following code to implement the pull-left class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "pull-left">
Float to left
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Float an element to the left with class pull-left."
},
{
"code": null,
"e": 1186,
"s": 1113,
"text": "You can try to run the following code to implement the pull-left class −"
},
{
"code": null,
"e": 1196,
"s": 1186,
"text": "Live Demo"
},
{
"code": null,
"e": 1566,
"s": 1196,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"pull-left\">\n Float to left\n </div>\n </body>\n</html>"
}
] |
java.util.zip.ZipInputStream.getNextEntry() Method Example
|
The java.util.zip.ZipInputStream.getNextEntry() method reads the next ZIP file entry and positions the stream at the beginning of the entry data.
Following is the declaration for java.util.zip.ZipInputStream.getNextEntry() method.
public ZipEntry getNextEntry()
throws IOException
the next ZIP file entry, or null if there are no more entries.
ZipException − if a ZIP file error has occurred.
ZipException − if a ZIP file error has occurred.
IOException − if an I/O error has occurred.
IOException − if an I/O error has occurred.
Create a file Hello.txt in D:> test > directory with the following content.
This is an example.
The following example shows the usage of java.util.zip.ZipInputStream.getNextEntry() method.
package com.tutorialspoint;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipInputStreamDemo {
private static String SOURCE_FILE = "D:\\test\\Hello.txt";
private static String TARGET_FILE = "D:\\test\\Hello.zip";
public static void main(String[] args) {
try {
createZipFile();
readZipFile();
} catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
private static void createZipFile() throws IOException{
FileOutputStream fout = new FileOutputStream(TARGET_FILE);
CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
ZipOutputStream zout = new ZipOutputStream(checksum);
FileInputStream fin = new FileInputStream(SOURCE_FILE);
ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
zout.putNextEntry(zipEntry);
int length;
byte[] buffer = new byte[1024];
while((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
zout.close();
}
private static void readZipFile() throws IOException{
ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE));
ZipEntry entry;
while((entry = zin.getNextEntry())!=null){
System.out.printf("File: %s Modified on %TD %n",
entry.getName(), new Date(entry.getTime()));
extractFile(entry, zin);
System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
zin.closeEntry();
}
zin.close();
}
private static void extractFile(final ZipEntry entry, ZipInputStream is)
throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(entry.getName());
while(is.available() != 0){
fos.write(is.read());
}
} catch (IOException ioex) {
fos.close();
}
}
}
Let us compile and run the above program, this will produce the following result −
File: D:\test\Hello.txt Modified on 05/22/17
Zip file D:\test\Hello.txt extracted successfully.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2338,
"s": 2192,
"text": "The java.util.zip.ZipInputStream.getNextEntry() method reads the next ZIP file entry and positions the stream at the beginning of the entry data."
},
{
"code": null,
"e": 2423,
"s": 2338,
"text": "Following is the declaration for java.util.zip.ZipInputStream.getNextEntry() method."
},
{
"code": null,
"e": 2477,
"s": 2423,
"text": "public ZipEntry getNextEntry()\n throws IOException\n"
},
{
"code": null,
"e": 2540,
"s": 2477,
"text": "the next ZIP file entry, or null if there are no more entries."
},
{
"code": null,
"e": 2590,
"s": 2540,
"text": "ZipException − if a ZIP file error has occurred."
},
{
"code": null,
"e": 2640,
"s": 2590,
"text": "ZipException − if a ZIP file error has occurred."
},
{
"code": null,
"e": 2685,
"s": 2640,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 2730,
"s": 2685,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 2807,
"s": 2730,
"text": "Create a file Hello.txt in D:> test > directory with the following content."
},
{
"code": null,
"e": 2828,
"s": 2807,
"text": "This is an example.\n"
},
{
"code": null,
"e": 2921,
"s": 2828,
"text": "The following example shows the usage of java.util.zip.ZipInputStream.getNextEntry() method."
},
{
"code": null,
"e": 5115,
"s": 2921,
"text": "package com.tutorialspoint;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.zip.Adler32;\nimport java.util.zip.CheckedOutputStream;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\n\npublic class ZipInputStreamDemo {\n private static String SOURCE_FILE = \"D:\\\\test\\\\Hello.txt\";\n private static String TARGET_FILE = \"D:\\\\test\\\\Hello.zip\";\n\n public static void main(String[] args) {\n try {\n createZipFile();\n readZipFile();\n } catch(IOException ioe) {\n System.out.println(\"IOException : \" + ioe);\n }\n }\n\n private static void createZipFile() throws IOException{\n FileOutputStream fout = new FileOutputStream(TARGET_FILE);\n CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());\n ZipOutputStream zout = new ZipOutputStream(checksum);\n\n FileInputStream fin = new FileInputStream(SOURCE_FILE);\n ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);\n zout.putNextEntry(zipEntry);\n int length;\n byte[] buffer = new byte[1024];\n while((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n fin.close();\n zout.close();\n }\n\n private static void readZipFile() throws IOException{\n ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); \n\n ZipEntry entry;\n while((entry = zin.getNextEntry())!=null){\n System.out.printf(\"File: %s Modified on %TD %n\", \n entry.getName(), new Date(entry.getTime()));\n extractFile(entry, zin); \n System.out.printf(\"Zip file %s extracted successfully.\", SOURCE_FILE);\n zin.closeEntry();\n }\n zin.close();\n }\n\n private static void extractFile(final ZipEntry entry, ZipInputStream is) \n throws IOException {\n FileOutputStream fos = null; \n try { \n fos = new FileOutputStream(entry.getName()); \n while(is.available() != 0){\n fos.write(is.read()); \n }\n } catch (IOException ioex) { \n fos.close(); \n } \n }\n}"
},
{
"code": null,
"e": 5198,
"s": 5115,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 5296,
"s": 5198,
"text": "File: D:\\test\\Hello.txt Modified on 05/22/17 \nZip file D:\\test\\Hello.txt extracted successfully.\n"
},
{
"code": null,
"e": 5303,
"s": 5296,
"text": " Print"
},
{
"code": null,
"e": 5314,
"s": 5303,
"text": " Add Notes"
}
] |
Clojure - Lists cons
|
Returns a new list wherein an element is added to the beginning of the list.
Following is the syntax.
(cons element lst)
Parameters − ‘element’ is the element which needs to be added to the list. ‘lst’ is the list of items.
Return Value − The list with the appended value.
Following is an example of cons in Clojure.
(ns clojure.examples.example
(:gen-class))
(defn example []
(println (cons 0 (list 1 2,3))))
(example)
The above program produces the following output.
(0 1 2 3)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2451,
"s": 2374,
"text": "Returns a new list wherein an element is added to the beginning of the list."
},
{
"code": null,
"e": 2476,
"s": 2451,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2496,
"s": 2476,
"text": "(cons element lst)\n"
},
{
"code": null,
"e": 2599,
"s": 2496,
"text": "Parameters − ‘element’ is the element which needs to be added to the list. ‘lst’ is the list of items."
},
{
"code": null,
"e": 2648,
"s": 2599,
"text": "Return Value − The list with the appended value."
},
{
"code": null,
"e": 2692,
"s": 2648,
"text": "Following is an example of cons in Clojure."
},
{
"code": null,
"e": 2801,
"s": 2692,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (println (cons 0 (list 1 2,3))))\n(example)"
},
{
"code": null,
"e": 2850,
"s": 2801,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 2861,
"s": 2850,
"text": "(0 1 2 3)\n"
},
{
"code": null,
"e": 2868,
"s": 2861,
"text": " Print"
},
{
"code": null,
"e": 2879,
"s": 2868,
"text": " Add Notes"
}
] |
Multiply Large Numbers represented as Strings - GeeksforGeeks
|
01 Apr, 2021
Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.Examples:
Input : num1 = 4154
num2 = 51454
Output : 213739916
Input : num1 = 654154154151454545415415454
num2 = 63516561563156316545145146514654
Output : 41549622603955309777243716069997997007620439937711509062916
The idea is based on school mathematics.
We start from last digit of second number multiply it with first number. Then we multiply second digit of second number with first number, and so on. We add all these multiplications. While adding, we put i-th multiplication shifted.The approach used in below solution is to keep only one array for result. We traverse all digits first and second numbers in a loop and add the result at appropriate position.
C++
Java
Python3
C#
// C++ program to multiply two numbers represented// as strings.#include<bits/stdc++.h>using namespace std; // Multiplies str1 and str2, and prints result.string multiply(string num1, string num2){ int len1 = num1.size(); int len2 = num2.size(); if (len1 == 0 || len2 == 0) return "0"; // will keep the result number in vector // in reverse order vector<int> result(len1 + len2, 0); // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i=len1-1; i>=0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j=len2-1; j>=0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n1*n2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum/10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.size() - 1; while (i>=0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string string s = ""; while (i >= 0) s += std::to_string(result[i--]); return s;} // Driver codeint main(){ string str1 = "1235421415454545454545454544"; string str2 = "1714546546546545454544548544544545"; if((str1.at(0) == '-' || str2.at(0) == '-') && (str1.at(0) != '-' || str2.at(0) != '-' )) cout<<"-"; if(str1.at(0) == '-') str1 = str1.substr(1); if(str2.at(0) == '-') str2 = str2.substr(1); cout << multiply(str1, str2); return 0;}
// Java program to multiply two numbers// represented as Strings.class GFG{ // Multiplies str1 and str2, and prints result.static String multiply(String num1, String num2){ int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) return "0"; // will keep the result number in vector // in reverse order int result[] = new int[len1 + len2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; // To shift position to left after every // multipliccharAtion of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = len2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2.charAt(j) - '0'; // Multiply with current digit of first number // and add result to previously stored result // charAt current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next itercharAtion carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multipliccharAtion of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both // or one of num1 or num2 were '0' if (i == -1) return "0"; // genercharAte the result String String s = ""; while (i >= 0) s += (result[i--]); return s;} // Driver codepublic static void main(String[] args){ String str1 = "1235421415454545454545454544"; String str2 = "1714546546546545454544548544544545"; if ((str1.charAt(0) == '-' || str2.charAt(0) == '-') && (str1.charAt(0) != '-' || str2.charAt(0) != '-')) System.out.print("-"); if (str1.charAt(0) == '-') str1 = str1.substring(1); if (str2.charAt(0) == '-') str2 = str2.substring(1); System.out.println(multiply(str1, str2));}} // This code is contributed by ankush_953
# Python3 program to multiply two numbers# represented as strings. # Multiplies str1 and str2, and prints result.def multiply(num1, num2): len1 = len(num1) len2 = len(num2) if len1 == 0 or len2 == 0: return "0" # will keep the result number in vector # in reverse order result = [0] * (len1 + len2) # Below two indexes are used to # find positions in result. i_n1 = 0 i_n2 = 0 # Go from right to left in num1 for i in range(len1 - 1, -1, -1): carry = 0 n1 = ord(num1[i]) - 48 # To shift position to left after every # multiplication of a digit in num2 i_n2 = 0 # Go from right to left in num2 for j in range(len2 - 1, -1, -1): # Take current digit of second number n2 = ord(num2[j]) - 48 # Multiply with current digit of first number # and add result to previously stored result # at current position. summ = n1 * n2 + result[i_n1 + i_n2] + carry # Carry for next iteration carry = summ // 10 # Store result result[i_n1 + i_n2] = summ % 10 i_n2 += 1 # store carry in next cell if (carry > 0): result[i_n1 + i_n2] += carry # To shift position to left after every # multiplication of a digit in num1. i_n1 += 1 # print(result) # ignore '0's from the right i = len(result) - 1 while (i >= 0 and result[i] == 0): i -= 1 # If all were '0's - means either both or # one of num1 or num2 were '0' if (i == -1): return "0" # generate the result string s = "" while (i >= 0): s += chr(result[i] + 48) i -= 1 return s # Driver codestr1 = "1235421415454545454545454544"str2 = "1714546546546545454544548544544545" if((str1[0] == '-' or str2[0] == '-') and (str1[0] != '-' or str2[0] != '-')): print("-", end = '') if(str1[0] == '-' and str2[0] != '-'): str1 = str1[1:]elif(str1[0] != '-' and str2[0] == '-'): str2 = str2[1:]elif(str1[0] == '-' and str2[0] == '-'): str1 = str1[1:] str2 = str2[1:]print(multiply(str1, str2)) # This code is contributed by ankush_953
// C# program to multiply two numbers// represented as Strings.using System; class GFG{ // Multiplies str1 and str2, and prints result.static String multiply(String num1, String num2){ int len1 = num1.Length; int len2 = num2.Length; if (len1 == 0 || len2 == 0) return "0"; // will keep the result number in vector // in reverse order int []result = new int[len1 + len2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; int i; // Go from right to left in num1 for (i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multipliccharAtion of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = len2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // charAt current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next itercharAtion carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multipliccharAtion of a digit in num1. i_n1++; } // ignore '0's from the right i = result.Length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both // or one of num1 or num2 were '0' if (i == -1) return "0"; // genercharAte the result String String s = ""; while (i >= 0) s += (result[i--]); return s;} // Driver codepublic static void Main(String[] args){ String str1 = "1235421415454545454545454544"; String str2 = "1714546546546545454544548544544545"; if ((str1[0] == '-' || str2[0] == '-') && (str1[0] != '-' || str2[0] != '-')) Console.Write("-"); if (str1[0] == '-' && str2[0] != '-') { str1 = str1.Substring(1); } else if (str1[0] != '-' && str2[0] == '-') { str2 = str2.Substring(1); } else if (str1[0] == '-' && str2[0] == '-') { str1 = str1.Substring(1); str2 = str2.Substring(1); } Console.WriteLine(multiply(str1, str2));}} // This code is contributed by Rajput-Ji
Output:
2118187521397235888154583183918321221520083884298838480662480
The above code is adapted from the code provided by Gaurav.Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied. Another method:
Java
// Java program to multiply two numbers represented// as strings.import java.util.Scanner; public class StringMultiplication { // Driver code public static void main(String[] args) { String num1 = "1235421415454545454545454544"; String tempnum1 = num1; String num2 = "1714546546546545454544548544544545"; String tempnum2 = num2; // Check condition if one string is negative if (num1.charAt(0) == '-' && num2.charAt(0) != '-') { num1 = num1.substring(1); } else if (num1.charAt(0) != '-' && num2.charAt(0) == '-') { num2 = num2.substring(1); } else if (num1.charAt(0) == '-' && num2.charAt(0) == '-') { num1 = num1.substring(1); num2 = num2.substring(1); } String s1 = new StringBuffer(num1).reverse().toString(); String s2 = new StringBuffer(num2).reverse().toString(); int[] m = new int[s1.length() + s2.length()]; // Go from right to left in num1 for (int i = 0; i < s1.length(); i++) { // Go from right to left in num2 for (int j = 0; j < s2.length(); j++) { m[i + j] = m[i + j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0'); } } String product = new String(); // Multiply with current digit of first number // and add result to previously stored product // at current position. for (int i = 0; i < m.length; i++) { int digit = m[i] % 10; int carry = m[i] / 10; if (i + 1 < m.length) { m[i + 1] = m[i + 1] + carry; } product = digit + product; } // ignore '0's from the right while (product.length() > 1 && product.charAt(0) == '0') { product = product.substring(1); } // Check condition if one string is negative if (tempnum1.charAt(0) == '-' && tempnum2.charAt(0) != '-') { product = new StringBuffer(product) .insert(0, '-') .toString(); } else if (tempnum1.charAt(0) != '-' && tempnum2.charAt(0) == '-') { product = new StringBuffer(product) .insert(0, '-') .toString(); } else if (tempnum1.charAt(0) == '-' && tempnum2.charAt(0) == '-') { product = product; } System.out.println("Product of the two numbers is :" + "\n" + product); }}
Output:
2118187521397235888154583183918321221520083884298838480662480
Related Article : Karatsuba algorithm for fast multiplicationThis article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DheerendraJaiswal
ankush_953
Rajput-Ji
adishah0912
klynsaha
Adobe
Facebook
Flipkart
large-numbers
Microsoft
Samsung
Mathematical
Strings
Flipkart
Microsoft
Samsung
Adobe
Facebook
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Prime Numbers
Program to find sum of elements in a given array
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 25354,
"s": 25326,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 25515,
"s": 25354,
"text": "Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.Examples: "
},
{
"code": null,
"e": 25744,
"s": 25515,
"text": "Input : num1 = 4154 \n num2 = 51454\nOutput : 213739916 \n\nInput : num1 = 654154154151454545415415454 \n num2 = 63516561563156316545145146514654 \nOutput : 41549622603955309777243716069997997007620439937711509062916"
},
{
"code": null,
"e": 25787,
"s": 25744,
"text": "The idea is based on school mathematics. "
},
{
"code": null,
"e": 26197,
"s": 25787,
"text": "We start from last digit of second number multiply it with first number. Then we multiply second digit of second number with first number, and so on. We add all these multiplications. While adding, we put i-th multiplication shifted.The approach used in below solution is to keep only one array for result. We traverse all digits first and second numbers in a loop and add the result at appropriate position. "
},
{
"code": null,
"e": 26201,
"s": 26197,
"text": "C++"
},
{
"code": null,
"e": 26206,
"s": 26201,
"text": "Java"
},
{
"code": null,
"e": 26214,
"s": 26206,
"text": "Python3"
},
{
"code": null,
"e": 26217,
"s": 26214,
"text": "C#"
},
{
"code": "// C++ program to multiply two numbers represented// as strings.#include<bits/stdc++.h>using namespace std; // Multiplies str1 and str2, and prints result.string multiply(string num1, string num2){ int len1 = num1.size(); int len2 = num2.size(); if (len1 == 0 || len2 == 0) return \"0\"; // will keep the result number in vector // in reverse order vector<int> result(len1 + len2, 0); // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i=len1-1; i>=0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j=len2-1; j>=0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n1*n2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum/10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.size() - 1; while (i>=0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return \"0\"; // generate the result string string s = \"\"; while (i >= 0) s += std::to_string(result[i--]); return s;} // Driver codeint main(){ string str1 = \"1235421415454545454545454544\"; string str2 = \"1714546546546545454544548544544545\"; if((str1.at(0) == '-' || str2.at(0) == '-') && (str1.at(0) != '-' || str2.at(0) != '-' )) cout<<\"-\"; if(str1.at(0) == '-') str1 = str1.substr(1); if(str2.at(0) == '-') str2 = str2.substr(1); cout << multiply(str1, str2); return 0;}",
"e": 28514,
"s": 26217,
"text": null
},
{
"code": "// Java program to multiply two numbers// represented as Strings.class GFG{ // Multiplies str1 and str2, and prints result.static String multiply(String num1, String num2){ int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) return \"0\"; // will keep the result number in vector // in reverse order int result[] = new int[len1 + len2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; // To shift position to left after every // multipliccharAtion of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = len2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2.charAt(j) - '0'; // Multiply with current digit of first number // and add result to previously stored result // charAt current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next itercharAtion carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multipliccharAtion of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both // or one of num1 or num2 were '0' if (i == -1) return \"0\"; // genercharAte the result String String s = \"\"; while (i >= 0) s += (result[i--]); return s;} // Driver codepublic static void main(String[] args){ String str1 = \"1235421415454545454545454544\"; String str2 = \"1714546546546545454544548544544545\"; if ((str1.charAt(0) == '-' || str2.charAt(0) == '-') && (str1.charAt(0) != '-' || str2.charAt(0) != '-')) System.out.print(\"-\"); if (str1.charAt(0) == '-') str1 = str1.substring(1); if (str2.charAt(0) == '-') str2 = str2.substring(1); System.out.println(multiply(str1, str2));}} // This code is contributed by ankush_953",
"e": 30946,
"s": 28514,
"text": null
},
{
"code": "# Python3 program to multiply two numbers# represented as strings. # Multiplies str1 and str2, and prints result.def multiply(num1, num2): len1 = len(num1) len2 = len(num2) if len1 == 0 or len2 == 0: return \"0\" # will keep the result number in vector # in reverse order result = [0] * (len1 + len2) # Below two indexes are used to # find positions in result. i_n1 = 0 i_n2 = 0 # Go from right to left in num1 for i in range(len1 - 1, -1, -1): carry = 0 n1 = ord(num1[i]) - 48 # To shift position to left after every # multiplication of a digit in num2 i_n2 = 0 # Go from right to left in num2 for j in range(len2 - 1, -1, -1): # Take current digit of second number n2 = ord(num2[j]) - 48 # Multiply with current digit of first number # and add result to previously stored result # at current position. summ = n1 * n2 + result[i_n1 + i_n2] + carry # Carry for next iteration carry = summ // 10 # Store result result[i_n1 + i_n2] = summ % 10 i_n2 += 1 # store carry in next cell if (carry > 0): result[i_n1 + i_n2] += carry # To shift position to left after every # multiplication of a digit in num1. i_n1 += 1 # print(result) # ignore '0's from the right i = len(result) - 1 while (i >= 0 and result[i] == 0): i -= 1 # If all were '0's - means either both or # one of num1 or num2 were '0' if (i == -1): return \"0\" # generate the result string s = \"\" while (i >= 0): s += chr(result[i] + 48) i -= 1 return s # Driver codestr1 = \"1235421415454545454545454544\"str2 = \"1714546546546545454544548544544545\" if((str1[0] == '-' or str2[0] == '-') and (str1[0] != '-' or str2[0] != '-')): print(\"-\", end = '') if(str1[0] == '-' and str2[0] != '-'): str1 = str1[1:]elif(str1[0] != '-' and str2[0] == '-'): str2 = str2[1:]elif(str1[0] == '-' and str2[0] == '-'): str1 = str1[1:] str2 = str2[1:]print(multiply(str1, str2)) # This code is contributed by ankush_953",
"e": 33201,
"s": 30946,
"text": null
},
{
"code": "// C# program to multiply two numbers// represented as Strings.using System; class GFG{ // Multiplies str1 and str2, and prints result.static String multiply(String num1, String num2){ int len1 = num1.Length; int len2 = num2.Length; if (len1 == 0 || len2 == 0) return \"0\"; // will keep the result number in vector // in reverse order int []result = new int[len1 + len2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; int i; // Go from right to left in num1 for (i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multipliccharAtion of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = len2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // charAt current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next itercharAtion carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multipliccharAtion of a digit in num1. i_n1++; } // ignore '0's from the right i = result.Length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both // or one of num1 or num2 were '0' if (i == -1) return \"0\"; // genercharAte the result String String s = \"\"; while (i >= 0) s += (result[i--]); return s;} // Driver codepublic static void Main(String[] args){ String str1 = \"1235421415454545454545454544\"; String str2 = \"1714546546546545454544548544544545\"; if ((str1[0] == '-' || str2[0] == '-') && (str1[0] != '-' || str2[0] != '-')) Console.Write(\"-\"); if (str1[0] == '-' && str2[0] != '-') { str1 = str1.Substring(1); } else if (str1[0] != '-' && str2[0] == '-') { str2 = str2.Substring(1); } else if (str1[0] == '-' && str2[0] == '-') { str1 = str1.Substring(1); str2 = str2.Substring(1); } Console.WriteLine(multiply(str1, str2));}} // This code is contributed by Rajput-Ji",
"e": 35761,
"s": 33201,
"text": null
},
{
"code": null,
"e": 35770,
"s": 35761,
"text": "Output: "
},
{
"code": null,
"e": 35832,
"s": 35770,
"text": "2118187521397235888154583183918321221520083884298838480662480"
},
{
"code": null,
"e": 36000,
"s": 35832,
"text": "The above code is adapted from the code provided by Gaurav.Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied. Another method: "
},
{
"code": null,
"e": 36005,
"s": 36000,
"text": "Java"
},
{
"code": "// Java program to multiply two numbers represented// as strings.import java.util.Scanner; public class StringMultiplication { // Driver code public static void main(String[] args) { String num1 = \"1235421415454545454545454544\"; String tempnum1 = num1; String num2 = \"1714546546546545454544548544544545\"; String tempnum2 = num2; // Check condition if one string is negative if (num1.charAt(0) == '-' && num2.charAt(0) != '-') { num1 = num1.substring(1); } else if (num1.charAt(0) != '-' && num2.charAt(0) == '-') { num2 = num2.substring(1); } else if (num1.charAt(0) == '-' && num2.charAt(0) == '-') { num1 = num1.substring(1); num2 = num2.substring(1); } String s1 = new StringBuffer(num1).reverse().toString(); String s2 = new StringBuffer(num2).reverse().toString(); int[] m = new int[s1.length() + s2.length()]; // Go from right to left in num1 for (int i = 0; i < s1.length(); i++) { // Go from right to left in num2 for (int j = 0; j < s2.length(); j++) { m[i + j] = m[i + j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0'); } } String product = new String(); // Multiply with current digit of first number // and add result to previously stored product // at current position. for (int i = 0; i < m.length; i++) { int digit = m[i] % 10; int carry = m[i] / 10; if (i + 1 < m.length) { m[i + 1] = m[i + 1] + carry; } product = digit + product; } // ignore '0's from the right while (product.length() > 1 && product.charAt(0) == '0') { product = product.substring(1); } // Check condition if one string is negative if (tempnum1.charAt(0) == '-' && tempnum2.charAt(0) != '-') { product = new StringBuffer(product) .insert(0, '-') .toString(); } else if (tempnum1.charAt(0) != '-' && tempnum2.charAt(0) == '-') { product = new StringBuffer(product) .insert(0, '-') .toString(); } else if (tempnum1.charAt(0) == '-' && tempnum2.charAt(0) == '-') { product = product; } System.out.println(\"Product of the two numbers is :\" + \"\\n\" + product); }}",
"e": 38716,
"s": 36005,
"text": null
},
{
"code": null,
"e": 38725,
"s": 38716,
"text": "Output: "
},
{
"code": null,
"e": 38787,
"s": 38725,
"text": "2118187521397235888154583183918321221520083884298838480662480"
},
{
"code": null,
"e": 39269,
"s": 38787,
"text": "Related Article : Karatsuba algorithm for fast multiplicationThis article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39287,
"s": 39269,
"text": "DheerendraJaiswal"
},
{
"code": null,
"e": 39298,
"s": 39287,
"text": "ankush_953"
},
{
"code": null,
"e": 39308,
"s": 39298,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39320,
"s": 39308,
"text": "adishah0912"
},
{
"code": null,
"e": 39329,
"s": 39320,
"text": "klynsaha"
},
{
"code": null,
"e": 39335,
"s": 39329,
"text": "Adobe"
},
{
"code": null,
"e": 39344,
"s": 39335,
"text": "Facebook"
},
{
"code": null,
"e": 39353,
"s": 39344,
"text": "Flipkart"
},
{
"code": null,
"e": 39367,
"s": 39353,
"text": "large-numbers"
},
{
"code": null,
"e": 39377,
"s": 39367,
"text": "Microsoft"
},
{
"code": null,
"e": 39385,
"s": 39377,
"text": "Samsung"
},
{
"code": null,
"e": 39398,
"s": 39385,
"text": "Mathematical"
},
{
"code": null,
"e": 39406,
"s": 39398,
"text": "Strings"
},
{
"code": null,
"e": 39415,
"s": 39406,
"text": "Flipkart"
},
{
"code": null,
"e": 39425,
"s": 39415,
"text": "Microsoft"
},
{
"code": null,
"e": 39433,
"s": 39425,
"text": "Samsung"
},
{
"code": null,
"e": 39439,
"s": 39433,
"text": "Adobe"
},
{
"code": null,
"e": 39448,
"s": 39439,
"text": "Facebook"
},
{
"code": null,
"e": 39456,
"s": 39448,
"text": "Strings"
},
{
"code": null,
"e": 39469,
"s": 39456,
"text": "Mathematical"
},
{
"code": null,
"e": 39567,
"s": 39469,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39591,
"s": 39567,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 39634,
"s": 39591,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 39676,
"s": 39634,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 39690,
"s": 39676,
"text": "Prime Numbers"
},
{
"code": null,
"e": 39739,
"s": 39690,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 39785,
"s": 39739,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 39810,
"s": 39785,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 39844,
"s": 39810,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 39919,
"s": 39844,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
How to Extract Data from PDF Forms Using Python | by ankur garg | Towards Data Science
|
PDF or Portable Document File format is one of the most common file formats in use today. It is widely used across enterprises, in government offices, healthcare and other industries. As a result, there is a large body of unstructured data that exists in PDF format and to extract and analyse this data to generate meaningful insights is a common task among data scientists.
I work for a financial institution and recently came across a situation where we had to extract data from a large volume of PDF forms. While there is a good body of work available to describe simple text extraction from PDF documents, I struggled to find a comprehensive guide to extract data from PDF forms. My objective to write this article is to develop such a guide.
There are several Python libraries dedicated to working with PDF documents, some more popular than the others. I will be using PyPDF2 for the purpose of this article. PyPDF2 is a Pure-Python library built as a PDF toolkit. Being Pure-Python, it can run on any Python platform without any dependencies or external libraries. You can use pip to install this library by executing the code below.
pip install PyPDF2
Once you have installed PyPDF2, you should be all set to follow along. We will take a quick look at the structure of PDF files as it will help us to better understand the programmatic basis of extracting data from PDF forms. I will briefly discuss the 2 types of PDF forms that are widely used. We will then jump right into the examples to extract data from each of the 2 types of PDF forms.
Instead of looking at PDF document as a monolith, it should be looked at as a collection of objects. All of these objects are arranged in a set pattern. If you open a PDF file in a text editor such as notepad, the content may not make much sense and appear to be junk. However, if you use a tool that provides low level access to PDF objects, you could see and appreciate the underlying structure. For example, please look at Figure 1 below. I used iText RUPS to open a simple PDF document.The image on the left is of a simple PDF document I opened in a reader application(Acrobat Reader). The middle image displays the low level object model of this document as rendered by iText RUPS. The image on the Right shows the data stream that captures the content of the PDF on its first page. As you could see, the object model(middle image) has a set pattern and encapsulates all of the meta data that is needed to render the document independent of the software, hardware, operating system etc. This structure is what makes PDF so versatile and popular.
There are 2 primary types of PDF forms.
XFA (XML Forms Architecture) based FormsAcroforms
XFA (XML Forms Architecture) based Forms
Acroforms
Adobe(the company that developed PDF format) has an application called AEM (Adobe Experience Manager) Forms Designer, which is aimed at enabling customers to create and publish PDF forms. Adobe uses the term PDF form to refer to the interactive and dynamic forms created with AEM Forms Designer. These PDF forms are based on Adobe’s XML Forms Architecture (XFA), which is based on XML. These forms can be dynamic in nature and can reflow PDF content based on user input.
There’s another type of PDF form, called an Acroform. Acroform is Adobe’s older and original interactive form technology introduced in 1996 as a part of PDF 1.2 specification. Acroforms are a combination of a traditional PDF that defines the static layout with Interactive form fields that are bolted on top. First, you design the form layout using Microsoft Word, Adobe InDesign, or Adobe Illustrator, etc. Then you add the form elements — fields, dropdown controls, checkboxes, script logic etc.
Figure 2 below shows a screenshot of the XFA based PDF form that we will be using as an example for this exercise. This is a Currency Transactions Report form used by the banks and other institutions to report certain financial transactions to the regulatory agency. This is a dynamic form where you could add and remove sections based on the amount of information that needs to be reported. I have partially filled this form with some dummy data.
Figure 3 shows the object model of this form. The XML document, shown on the right side of the image is what makes up the XFA, which is stored as the value of the XFA key inside the AcroForm dictionary(look at the object model on the left side of the image). The Acroform dictionary is a child element of the Catalog dictionary, which in turn is housed inside the Root of this PDF file. All we need to do is use PyPDF2 to access the XML document from the object structure of this file. Once we have access to the XML, it is a simple exercise of parsing out the XML document to access values for various form elements, which could then be stored into a Python list, Numpy array, Pandas dataframe etc. for the purpose of analysis.
Below is the code to extract the XML that makes up this form.
import PyPDF2 as pypdfdef findInDict(needle, haystack): for key in haystack.keys(): try: value=haystack[key] except: continue if key==needle: return value if isinstance(value,dict): x=findInDict(needle,value) if x is not None: return xpdfobject=open('CTRX_filled.pdf','rb')pdf=pypdf.PdfFileReader(pdfobject)xfa=findInDict('/XFA',pdf.resolvedObjects)xml=xfa[7].getObject().getData()
In the first line, I am simply importing the PyPDF2 library and providing it an alias — pypdf. The second line is the beginning of function definition to find elements of a dictionary by providing the dictionary key. You would recall from our discussion above, that our XML is embedded inside a dictionary referenced by the key ‘/XFA’. This function helps me to navigate the complicated object model of the PDF file, which is basically a set of dictionaries embedded inside multiple sets of dictionaries. In the line following the function definition, I am reading in the PDF form and creating a PdfFileReader object. The resolvedObjects method of this class unravels the PDF object model as a set of Python dictionaries. I then invoke the findInDict function to extract the elements of the ‘/XFA’ dictionary, which is an array as shown in figure 4 below.
The seventh element of this array is the actual XML content that makes up the form. It is an IndirectObject. An IndirectObject is an alias that points to an actual object. This reference helps to reduce the size of the file when same object appears at multiple places. The getObject() method used in the last line of the code retrieves the actual object. If the object is a text object, using str() function should give you the actual text. Otherwise, the getData() method needs to be used to render the data from the object. Below is a snapshot of a portion of the XML retrieved in the last line of the code above. You could see some of the dummy address data I entered into the sample form. You could easily parse out this data from the XML and use it for further analysis.
This one will be relatively easy as we have already discussed most of the concepts related with the PDF object model in the sections above. Below is a sample income tax form that I will be using as an example. I have put some dummy data in it.
Figure 7 below shows the object model of this form.
The values of individual form fields are referenced by the key ‘/V’, which is embedded inside ‘/Fields’, which in turn is embedded inside ‘/AcroForm’. ‘/AcroFrom’ is a child of the root Catalog dictionary of this PDF file. We could use the approach we used in the case of XFA form and use the ‘findInDict’ function to retrieve the ‘/Fields’ dictionary and then retrieve values of the individual fields. Fortunately, PyPDF2 provides a more direct way to do this. The PdfFileReader class provides a getFormTextFields() method that returns a dictionary of all form values. Below is the short code. Figure 8 shows the output. The dictionary object could be easily converted into a list or a Pandas dataframe for further procecssing.
import PyPDF2 as pypdfpdfobject=open('incometaxform_filled.pdf','rb')pdf=pypdf.PdfFileReader(pdfobject)pdf.getFormTextFields()
Extracting data from PDF forms is easy once you understand the underlying object model and PyPDF2 is a powerful library that enables you to access it. Have fun with your data!
|
[
{
"code": null,
"e": 546,
"s": 171,
"text": "PDF or Portable Document File format is one of the most common file formats in use today. It is widely used across enterprises, in government offices, healthcare and other industries. As a result, there is a large body of unstructured data that exists in PDF format and to extract and analyse this data to generate meaningful insights is a common task among data scientists."
},
{
"code": null,
"e": 918,
"s": 546,
"text": "I work for a financial institution and recently came across a situation where we had to extract data from a large volume of PDF forms. While there is a good body of work available to describe simple text extraction from PDF documents, I struggled to find a comprehensive guide to extract data from PDF forms. My objective to write this article is to develop such a guide."
},
{
"code": null,
"e": 1311,
"s": 918,
"text": "There are several Python libraries dedicated to working with PDF documents, some more popular than the others. I will be using PyPDF2 for the purpose of this article. PyPDF2 is a Pure-Python library built as a PDF toolkit. Being Pure-Python, it can run on any Python platform without any dependencies or external libraries. You can use pip to install this library by executing the code below."
},
{
"code": null,
"e": 1330,
"s": 1311,
"text": "pip install PyPDF2"
},
{
"code": null,
"e": 1722,
"s": 1330,
"text": "Once you have installed PyPDF2, you should be all set to follow along. We will take a quick look at the structure of PDF files as it will help us to better understand the programmatic basis of extracting data from PDF forms. I will briefly discuss the 2 types of PDF forms that are widely used. We will then jump right into the examples to extract data from each of the 2 types of PDF forms."
},
{
"code": null,
"e": 2773,
"s": 1722,
"text": "Instead of looking at PDF document as a monolith, it should be looked at as a collection of objects. All of these objects are arranged in a set pattern. If you open a PDF file in a text editor such as notepad, the content may not make much sense and appear to be junk. However, if you use a tool that provides low level access to PDF objects, you could see and appreciate the underlying structure. For example, please look at Figure 1 below. I used iText RUPS to open a simple PDF document.The image on the left is of a simple PDF document I opened in a reader application(Acrobat Reader). The middle image displays the low level object model of this document as rendered by iText RUPS. The image on the Right shows the data stream that captures the content of the PDF on its first page. As you could see, the object model(middle image) has a set pattern and encapsulates all of the meta data that is needed to render the document independent of the software, hardware, operating system etc. This structure is what makes PDF so versatile and popular."
},
{
"code": null,
"e": 2813,
"s": 2773,
"text": "There are 2 primary types of PDF forms."
},
{
"code": null,
"e": 2863,
"s": 2813,
"text": "XFA (XML Forms Architecture) based FormsAcroforms"
},
{
"code": null,
"e": 2904,
"s": 2863,
"text": "XFA (XML Forms Architecture) based Forms"
},
{
"code": null,
"e": 2914,
"s": 2904,
"text": "Acroforms"
},
{
"code": null,
"e": 3385,
"s": 2914,
"text": "Adobe(the company that developed PDF format) has an application called AEM (Adobe Experience Manager) Forms Designer, which is aimed at enabling customers to create and publish PDF forms. Adobe uses the term PDF form to refer to the interactive and dynamic forms created with AEM Forms Designer. These PDF forms are based on Adobe’s XML Forms Architecture (XFA), which is based on XML. These forms can be dynamic in nature and can reflow PDF content based on user input."
},
{
"code": null,
"e": 3883,
"s": 3385,
"text": "There’s another type of PDF form, called an Acroform. Acroform is Adobe’s older and original interactive form technology introduced in 1996 as a part of PDF 1.2 specification. Acroforms are a combination of a traditional PDF that defines the static layout with Interactive form fields that are bolted on top. First, you design the form layout using Microsoft Word, Adobe InDesign, or Adobe Illustrator, etc. Then you add the form elements — fields, dropdown controls, checkboxes, script logic etc."
},
{
"code": null,
"e": 4331,
"s": 3883,
"text": "Figure 2 below shows a screenshot of the XFA based PDF form that we will be using as an example for this exercise. This is a Currency Transactions Report form used by the banks and other institutions to report certain financial transactions to the regulatory agency. This is a dynamic form where you could add and remove sections based on the amount of information that needs to be reported. I have partially filled this form with some dummy data."
},
{
"code": null,
"e": 5060,
"s": 4331,
"text": "Figure 3 shows the object model of this form. The XML document, shown on the right side of the image is what makes up the XFA, which is stored as the value of the XFA key inside the AcroForm dictionary(look at the object model on the left side of the image). The Acroform dictionary is a child element of the Catalog dictionary, which in turn is housed inside the Root of this PDF file. All we need to do is use PyPDF2 to access the XML document from the object structure of this file. Once we have access to the XML, it is a simple exercise of parsing out the XML document to access values for various form elements, which could then be stored into a Python list, Numpy array, Pandas dataframe etc. for the purpose of analysis."
},
{
"code": null,
"e": 5122,
"s": 5060,
"text": "Below is the code to extract the XML that makes up this form."
},
{
"code": null,
"e": 5629,
"s": 5122,
"text": "import PyPDF2 as pypdfdef findInDict(needle, haystack): for key in haystack.keys(): try: value=haystack[key] except: continue if key==needle: return value if isinstance(value,dict): x=findInDict(needle,value) if x is not None: return xpdfobject=open('CTRX_filled.pdf','rb')pdf=pypdf.PdfFileReader(pdfobject)xfa=findInDict('/XFA',pdf.resolvedObjects)xml=xfa[7].getObject().getData()"
},
{
"code": null,
"e": 6485,
"s": 5629,
"text": "In the first line, I am simply importing the PyPDF2 library and providing it an alias — pypdf. The second line is the beginning of function definition to find elements of a dictionary by providing the dictionary key. You would recall from our discussion above, that our XML is embedded inside a dictionary referenced by the key ‘/XFA’. This function helps me to navigate the complicated object model of the PDF file, which is basically a set of dictionaries embedded inside multiple sets of dictionaries. In the line following the function definition, I am reading in the PDF form and creating a PdfFileReader object. The resolvedObjects method of this class unravels the PDF object model as a set of Python dictionaries. I then invoke the findInDict function to extract the elements of the ‘/XFA’ dictionary, which is an array as shown in figure 4 below."
},
{
"code": null,
"e": 7261,
"s": 6485,
"text": "The seventh element of this array is the actual XML content that makes up the form. It is an IndirectObject. An IndirectObject is an alias that points to an actual object. This reference helps to reduce the size of the file when same object appears at multiple places. The getObject() method used in the last line of the code retrieves the actual object. If the object is a text object, using str() function should give you the actual text. Otherwise, the getData() method needs to be used to render the data from the object. Below is a snapshot of a portion of the XML retrieved in the last line of the code above. You could see some of the dummy address data I entered into the sample form. You could easily parse out this data from the XML and use it for further analysis."
},
{
"code": null,
"e": 7505,
"s": 7261,
"text": "This one will be relatively easy as we have already discussed most of the concepts related with the PDF object model in the sections above. Below is a sample income tax form that I will be using as an example. I have put some dummy data in it."
},
{
"code": null,
"e": 7557,
"s": 7505,
"text": "Figure 7 below shows the object model of this form."
},
{
"code": null,
"e": 8286,
"s": 7557,
"text": "The values of individual form fields are referenced by the key ‘/V’, which is embedded inside ‘/Fields’, which in turn is embedded inside ‘/AcroForm’. ‘/AcroFrom’ is a child of the root Catalog dictionary of this PDF file. We could use the approach we used in the case of XFA form and use the ‘findInDict’ function to retrieve the ‘/Fields’ dictionary and then retrieve values of the individual fields. Fortunately, PyPDF2 provides a more direct way to do this. The PdfFileReader class provides a getFormTextFields() method that returns a dictionary of all form values. Below is the short code. Figure 8 shows the output. The dictionary object could be easily converted into a list or a Pandas dataframe for further procecssing."
},
{
"code": null,
"e": 8413,
"s": 8286,
"text": "import PyPDF2 as pypdfpdfobject=open('incometaxform_filled.pdf','rb')pdf=pypdf.PdfFileReader(pdfobject)pdf.getFormTextFields()"
}
] |
FIND_IN_SET() Function in MySQL - GeeksforGeeks
|
02 Sep, 2020
FIND_IN_SET() function used to find the position of a string within a list of strings. If the string is repeated multiple time, the output will be the first position of that string.
Point to be noted :
If string is not found in string_list, the result is 0
If string or string_list is NULL, the result is NULL
If string_list is an empty string (“”), the result is 0
Syntax :
FIND_IN_SET("string", "string_list")
Note : Parameter string is mandatory to search for string_list; string_list is list of string values.
Example-1:Search for “a” within the list of strings :
SELECT FIND_IN_SET("a", "g, e, e, k, s, f, o, r, g, e, e, k, s");
Result –
Example-2:Search for “q” within the list of strings (string list is NULL) :
SELECT FIND_IN_SET("a", null);
Result –
Example-3:Search for “q” within the list of strings :
SELECT FIND_IN_SET("g", "g, e, e, k, s, f, o, r, g, e, e, k, s");
Result –
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 24450,
"s": 24268,
"text": "FIND_IN_SET() function used to find the position of a string within a list of strings. If the string is repeated multiple time, the output will be the first position of that string."
},
{
"code": null,
"e": 24470,
"s": 24450,
"text": "Point to be noted :"
},
{
"code": null,
"e": 24525,
"s": 24470,
"text": "If string is not found in string_list, the result is 0"
},
{
"code": null,
"e": 24578,
"s": 24525,
"text": "If string or string_list is NULL, the result is NULL"
},
{
"code": null,
"e": 24634,
"s": 24578,
"text": "If string_list is an empty string (“”), the result is 0"
},
{
"code": null,
"e": 24643,
"s": 24634,
"text": "Syntax :"
},
{
"code": null,
"e": 24680,
"s": 24643,
"text": "FIND_IN_SET(\"string\", \"string_list\")"
},
{
"code": null,
"e": 24782,
"s": 24680,
"text": "Note : Parameter string is mandatory to search for string_list; string_list is list of string values."
},
{
"code": null,
"e": 24836,
"s": 24782,
"text": "Example-1:Search for “a” within the list of strings :"
},
{
"code": null,
"e": 24903,
"s": 24836,
"text": "SELECT FIND_IN_SET(\"a\", \"g, e, e, k, s, f, o, r, g, e, e, k, s\"); "
},
{
"code": null,
"e": 24912,
"s": 24903,
"text": "Result –"
},
{
"code": null,
"e": 24988,
"s": 24912,
"text": "Example-2:Search for “q” within the list of strings (string list is NULL) :"
},
{
"code": null,
"e": 25020,
"s": 24988,
"text": "SELECT FIND_IN_SET(\"a\", null); "
},
{
"code": null,
"e": 25029,
"s": 25020,
"text": "Result –"
},
{
"code": null,
"e": 25083,
"s": 25029,
"text": "Example-3:Search for “q” within the list of strings :"
},
{
"code": null,
"e": 25150,
"s": 25083,
"text": "SELECT FIND_IN_SET(\"g\", \"g, e, e, k, s, f, o, r, g, e, e, k, s\"); "
},
{
"code": null,
"e": 25159,
"s": 25150,
"text": "Result –"
},
{
"code": null,
"e": 25168,
"s": 25159,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25174,
"s": 25168,
"text": "mysql"
},
{
"code": null,
"e": 25178,
"s": 25174,
"text": "SQL"
},
{
"code": null,
"e": 25182,
"s": 25178,
"text": "SQL"
},
{
"code": null,
"e": 25280,
"s": 25182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25289,
"s": 25280,
"text": "Comments"
},
{
"code": null,
"e": 25302,
"s": 25289,
"text": "Old Comments"
},
{
"code": null,
"e": 25368,
"s": 25302,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25421,
"s": 25368,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 25453,
"s": 25421,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25531,
"s": 25453,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25548,
"s": 25531,
"text": "SQL using Python"
},
{
"code": null,
"e": 25563,
"s": 25548,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 25599,
"s": 25563,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 25620,
"s": 25599,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 25673,
"s": 25620,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
JavaFX - Layout Panes VBox
|
If we use VBox as the layout in our application, all the nodes are set in a single vertical column.
The class named VBox of the package javafx.scene.layout represents the VBox pane. This class contains five properties, which are −
alignment − This property represents the alignment of the nodes inside the bounds of the VBox. You can set value to this property by using the setter method setAlignment().
alignment − This property represents the alignment of the nodes inside the bounds of the VBox. You can set value to this property by using the setter method setAlignment().
fillHeight − This property is of Boolean type and on setting this to be true; the resizable nodes in the VBox are resized to the height of the VBox. You can set value to this property using the setter method setFillHeight().
fillHeight − This property is of Boolean type and on setting this to be true; the resizable nodes in the VBox are resized to the height of the VBox. You can set value to this property using the setter method setFillHeight().
spacing − This property is of double type and it represents the space between the children of the VBox. You can set value to this property using the setter method setSpacing().
spacing − This property is of double type and it represents the space between the children of the VBox. You can set value to this property using the setter method setSpacing().
In addition to these, this class also provides the following methods −
setVgrow() − Sets the vertical grow priority for the child when contained by a VBox. This method accepts a node and a priority value.
setVgrow() − Sets the vertical grow priority for the child when contained by a VBox. This method accepts a node and a priority value.
setMargin() − Using this method, you can set margins to the VBox. This method accepts a node and an object of the Insets class (A set of inside offsets for the 4 sides of a rectangular area)
setMargin() − Using this method, you can set margins to the VBox. This method accepts a node and an object of the Insets class (A set of inside offsets for the 4 sides of a rectangular area)
The following program is an example of the VBox layout. In this, we are inserting a text field and two buttons, play and stop. This is done with a spacing of 10 and each having margins with dimensions – (10, 10, 10, 10).
Save this code in a file with the name VBoxExample.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
public class VBoxExample extends Application {
@Override
public void start(Stage stage) {
//creating a text field
TextField textField = new TextField();
//Creating the play button
Button playButton = new Button("Play");
//Creating the stop button
Button stopButton = new Button("stop");
//Instantiating the VBox class
VBox vBox = new VBox();
//Setting the space between the nodes of a VBox pane
vBox.setSpacing(10);
//Setting the margin to the nodes
vBox.setMargin(textField, new Insets(20, 20, 20, 20));
vBox.setMargin(playButton, new Insets(20, 20, 20, 20));
vBox.setMargin(stopButton, new Insets(20, 20, 20, 20));
//retrieving the observable list of the VBox
ObservableList list = vBox.getChildren();
//Adding all the nodes to the observable list
list.addAll(textField, playButton, stopButton);
//Creating a scene object
Scene scene = new Scene(vBox);
//Setting title to the Stage
stage.setTitle("Vbox Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac VBoxExample.java
java VBoxExample.java
On executing, the above program generates a JavaFX window as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2000,
"s": 1900,
"text": "If we use VBox as the layout in our application, all the nodes are set in a single vertical column."
},
{
"code": null,
"e": 2131,
"s": 2000,
"text": "The class named VBox of the package javafx.scene.layout represents the VBox pane. This class contains five properties, which are −"
},
{
"code": null,
"e": 2304,
"s": 2131,
"text": "alignment − This property represents the alignment of the nodes inside the bounds of the VBox. You can set value to this property by using the setter method setAlignment()."
},
{
"code": null,
"e": 2477,
"s": 2304,
"text": "alignment − This property represents the alignment of the nodes inside the bounds of the VBox. You can set value to this property by using the setter method setAlignment()."
},
{
"code": null,
"e": 2702,
"s": 2477,
"text": "fillHeight − This property is of Boolean type and on setting this to be true; the resizable nodes in the VBox are resized to the height of the VBox. You can set value to this property using the setter method setFillHeight()."
},
{
"code": null,
"e": 2927,
"s": 2702,
"text": "fillHeight − This property is of Boolean type and on setting this to be true; the resizable nodes in the VBox are resized to the height of the VBox. You can set value to this property using the setter method setFillHeight()."
},
{
"code": null,
"e": 3104,
"s": 2927,
"text": "spacing − This property is of double type and it represents the space between the children of the VBox. You can set value to this property using the setter method setSpacing()."
},
{
"code": null,
"e": 3281,
"s": 3104,
"text": "spacing − This property is of double type and it represents the space between the children of the VBox. You can set value to this property using the setter method setSpacing()."
},
{
"code": null,
"e": 3352,
"s": 3281,
"text": "In addition to these, this class also provides the following methods −"
},
{
"code": null,
"e": 3486,
"s": 3352,
"text": "setVgrow() − Sets the vertical grow priority for the child when contained by a VBox. This method accepts a node and a priority value."
},
{
"code": null,
"e": 3620,
"s": 3486,
"text": "setVgrow() − Sets the vertical grow priority for the child when contained by a VBox. This method accepts a node and a priority value."
},
{
"code": null,
"e": 3811,
"s": 3620,
"text": "setMargin() − Using this method, you can set margins to the VBox. This method accepts a node and an object of the Insets class (A set of inside offsets for the 4 sides of a rectangular area)"
},
{
"code": null,
"e": 4002,
"s": 3811,
"text": "setMargin() − Using this method, you can set margins to the VBox. This method accepts a node and an object of the Insets class (A set of inside offsets for the 4 sides of a rectangular area)"
},
{
"code": null,
"e": 4223,
"s": 4002,
"text": "The following program is an example of the VBox layout. In this, we are inserting a text field and two buttons, play and stop. This is done with a spacing of 10 and each having margins with dimensions – (10, 10, 10, 10)."
},
{
"code": null,
"e": 4280,
"s": 4223,
"text": "Save this code in a file with the name VBoxExample.java."
},
{
"code": null,
"e": 5968,
"s": 4280,
"text": "import javafx.application.Application; \nimport javafx.collections.ObservableList; \nimport javafx.geometry.Insets; \nimport javafx.scene.Scene; \nimport javafx.scene.control.Button; \nimport javafx.scene.control.TextField; \nimport javafx.stage.Stage; \nimport javafx.scene.layout.VBox; \n \npublic class VBoxExample extends Application { \n @Override \n public void start(Stage stage) { \n //creating a text field \n TextField textField = new TextField(); \n \n //Creating the play button \n Button playButton = new Button(\"Play\");\n\t \n //Creating the stop button \n Button stopButton = new Button(\"stop\"); \n \n //Instantiating the VBox class \n VBox vBox = new VBox(); \n \n //Setting the space between the nodes of a VBox pane \n vBox.setSpacing(10); \n \n //Setting the margin to the nodes \n vBox.setMargin(textField, new Insets(20, 20, 20, 20)); \n vBox.setMargin(playButton, new Insets(20, 20, 20, 20)); \n vBox.setMargin(stopButton, new Insets(20, 20, 20, 20)); \n \n //retrieving the observable list of the VBox \n ObservableList list = vBox.getChildren(); \n \n //Adding all the nodes to the observable list \n list.addAll(textField, playButton, stopButton); \n \n //Creating a scene object \n Scene scene = new Scene(vBox); \n \n //Setting title to the Stage \n stage.setTitle(\"Vbox Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 6062,
"s": 5968,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6109,
"s": 6062,
"text": "javac VBoxExample.java \njava VBoxExample.java\n"
},
{
"code": null,
"e": 6183,
"s": 6109,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 6218,
"s": 6183,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6229,
"s": 6218,
"text": " Syed Raza"
},
{
"code": null,
"e": 6265,
"s": 6229,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6301,
"s": 6265,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6334,
"s": 6301,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6370,
"s": 6334,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6377,
"s": 6370,
"text": " Print"
},
{
"code": null,
"e": 6388,
"s": 6377,
"text": " Add Notes"
}
] |
Check whether given key already exists in a dictionary in Python
|
The dictionary containers in pipeline old both key and values as pairs. Sometimes we may need to find if a given key is already present in the dictionary. In this article we will see the various ways to check for the presence of a key in a dictionary.
This is a very straightforward way in which we just check for the presence of the key in the dictionary using in operator. If the the keys part of dictionary we print the result as present else absent.
Live Demo
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",Adict)
check_key = "Fri"
if check_key in Adict:
print(check_key,"is Present.")
else:
print(check_key, " is not Present.")
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Fri is not Present.
The dict.keys() method gives us all the keys that are present in a given dictionary. We can use the in operator how to find out if the given key belongs to the given dictionary.
Live Demo
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",Adict)
check_key = "Wed"
if check_key in Adict.keys():
print(check_key,"is Present.")
else:
print(check_key, " is not Present.")
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Wed is Present.
|
[
{
"code": null,
"e": 1314,
"s": 1062,
"text": "The dictionary containers in pipeline old both key and values as pairs. Sometimes we may need to find if a given key is already present in the dictionary. In this article we will see the various ways to check for the presence of a key in a dictionary."
},
{
"code": null,
"e": 1516,
"s": 1314,
"text": "This is a very straightforward way in which we just check for the presence of the key in the dictionary using in operator. If the the keys part of dictionary we print the result as present else absent."
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": " Live Demo"
},
{
"code": null,
"e": 1729,
"s": 1527,
"text": "Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}\nprint(\"The given dictionary : \",Adict)\ncheck_key = \"Fri\"\nif check_key in Adict:\n print(check_key,\"is Present.\")\nelse:\n print(check_key, \" is not Present.\")"
},
{
"code": null,
"e": 1784,
"s": 1729,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1868,
"s": 1784,
"text": "The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}\nFri is not Present."
},
{
"code": null,
"e": 2046,
"s": 1868,
"text": "The dict.keys() method gives us all the keys that are present in a given dictionary. We can use the in operator how to find out if the given key belongs to the given dictionary."
},
{
"code": null,
"e": 2057,
"s": 2046,
"text": " Live Demo"
},
{
"code": null,
"e": 2266,
"s": 2057,
"text": "Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}\nprint(\"The given dictionary : \",Adict)\ncheck_key = \"Wed\"\nif check_key in Adict.keys():\n print(check_key,\"is Present.\")\nelse:\n print(check_key, \" is not Present.\")"
},
{
"code": null,
"e": 2321,
"s": 2266,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2401,
"s": 2321,
"text": "The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}\nWed is Present."
}
] |
Data Visualisation with Chartify - GeeksforGeeks
|
10 Jul, 2020
Chartify is an open-source data visualization library from Spotify that makes it easy for data analysts to create charts and graphs. Chartify is built on top of Bokeh, which is a very popular data visualization library. This article gives a brief introduction to this technology.
Install the latest version of Chartify and Pandas. To install these modules type the below command in the terminal.
pip install chartify
pip install pandas
Pandas is required for data cleaning and manipulation in this context. So let’s import these on to our Python code. It is recommended to use the Jupyter notebook or Google Colab for any kind of data visualization or analysis.
Python3
import chartifyimport pandas as pd
Chartify makes it very easy for anyone to start up. The following code helps set up a simple chart and displays it in the notebook.
Python3
ch = chartify.Chart()ch.show()
Output:
However, this is just an empty chart with no data in it. Let’s try to fill this chart with data to see this visualization tool come alive. Chartify comes with its own dataset examples that you can use to learn from. Thus we are going to load the example data and display it.
Python3
data = chartify.examples.example_data()data.head()
data.head()
If we analyze this dataset, we can come to the conclusion that it is time-series data. Time(or date), by convention, is displayed on the X-axis. Thus, let’s set the type of the X-axis to DateTime.
Python3
ch = chartify.Chart(x_axis_type='datetime')
Now there are various kinds of plots you can draw with this tool. However, in this article we are going to use only two, that is, scatter plot and histogram.
First, let’s build a scatter plot. The easiest way to do this is by using the scatter method. The arguments that should be passed are the data_frame which has the data to be plotted, x_column which specifies X-axis and y_column which specifies Y-axis. All other arguments are optional(that is, a default value is assigned to them when not specified). The color_column argument colors the plot of the basis of the column specified. Let’s say in the above dataset we set color_column to be the column “fruit”. Chartify assigns different colors to different fruit names in the column. A list of values within the color_column argument is used for specific sorting of the colors. alpha is the transparency(alpha value) of a plot. Here 1.0 is completely opaque, which 0.0 is completely transparent. marker refers to the mark on the plot for values. The markers can be a circle, asterisk, diamond, triangle, and various other shapes.
Syntax: scatter(data_frame, x_column, y_column, size_column=None, color_column=None, color_order=None, alpha=1.0, marker=’circle’)
Now let’s set the title, subtitle, and other attributes for our chart.
Python3
ch.set_title("Quantity Fruit vs Date")ch.set_subtitle("Quantity of fruits grown all around the world") ch.axes.set_xaxis_label("Date")ch.axes.set_yaxis_label("Quantity")ch.set_source_label("Source:Chartify Examples")
Now let’s make a scatter plot using the following and display it onto the notebook. data or the example dataset we got from Chartify will be our data_frame. The X-axis will be date and Y-axis will be quantity. The color_column will be fruit.
Python3
ch.plot.scatter(data_frame=data, x_column='date', y_column='quantity', color_column='fruit')ch.show()
Output:
Scatter Plot
Thus, we have built a simple scatter plot. Now let’s make a histogram using the same dataset. Let’s plot a histogram that visualizes the density of data with respect to quantity.
Python3
ch = chartify.Chart(y_axis_type='density')
To plot the histogram we are going to use the histogram method. Just like the scatter plot, even the histogram takes in a data_frame argument. color_column and color_order work in the same way as it did in the scatter plot. The method argument takes in a method and calculates the density of the graph on that basis. The count is the default method.
Syntax: histogram(data_frame, values_column, color_column=None, color_order=None, method=’count’, bins=’auto’)
Now let’s set the attributes of our chart.
Python3
ch.set_title("Quantity vs Count")ch.axes.set_xaxis_label("Quantity")ch.axes.set_yaxis_label("Count")ch.set_source_label("Source:Chartify Examples")
Now let’s plot the histogram using the method mentioned earlier.
Python3
ch.plot.histogram(data_frame=data, values_column='quantity')ch.show()
Output:
Histogram
Thus, in this article, we have plotted a histogram and a scatter plot using Spotify’s Chartify. This is just a beginner article and the same knowledge can be extended further to build more complex visualizations.
Data Visualization
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25836,
"s": 25555,
"text": "Chartify is an open-source data visualization library from Spotify that makes it easy for data analysts to create charts and graphs. Chartify is built on top of Bokeh, which is a very popular data visualization library. This article gives a brief introduction to this technology. "
},
{
"code": null,
"e": 25952,
"s": 25836,
"text": "Install the latest version of Chartify and Pandas. To install these modules type the below command in the terminal."
},
{
"code": null,
"e": 25993,
"s": 25952,
"text": "pip install chartify\npip install pandas\n"
},
{
"code": null,
"e": 26219,
"s": 25993,
"text": "Pandas is required for data cleaning and manipulation in this context. So let’s import these on to our Python code. It is recommended to use the Jupyter notebook or Google Colab for any kind of data visualization or analysis."
},
{
"code": null,
"e": 26227,
"s": 26219,
"text": "Python3"
},
{
"code": "import chartifyimport pandas as pd",
"e": 26262,
"s": 26227,
"text": null
},
{
"code": null,
"e": 26394,
"s": 26262,
"text": "Chartify makes it very easy for anyone to start up. The following code helps set up a simple chart and displays it in the notebook."
},
{
"code": null,
"e": 26402,
"s": 26394,
"text": "Python3"
},
{
"code": "ch = chartify.Chart()ch.show()",
"e": 26433,
"s": 26402,
"text": null
},
{
"code": null,
"e": 26441,
"s": 26433,
"text": "Output:"
},
{
"code": null,
"e": 26716,
"s": 26441,
"text": "However, this is just an empty chart with no data in it. Let’s try to fill this chart with data to see this visualization tool come alive. Chartify comes with its own dataset examples that you can use to learn from. Thus we are going to load the example data and display it."
},
{
"code": null,
"e": 26724,
"s": 26716,
"text": "Python3"
},
{
"code": "data = chartify.examples.example_data()data.head()",
"e": 26775,
"s": 26724,
"text": null
},
{
"code": null,
"e": 26787,
"s": 26775,
"text": "data.head()"
},
{
"code": null,
"e": 26984,
"s": 26787,
"text": "If we analyze this dataset, we can come to the conclusion that it is time-series data. Time(or date), by convention, is displayed on the X-axis. Thus, let’s set the type of the X-axis to DateTime."
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Python3"
},
{
"code": "ch = chartify.Chart(x_axis_type='datetime')",
"e": 27036,
"s": 26992,
"text": null
},
{
"code": null,
"e": 27194,
"s": 27036,
"text": "Now there are various kinds of plots you can draw with this tool. However, in this article we are going to use only two, that is, scatter plot and histogram."
},
{
"code": null,
"e": 28122,
"s": 27194,
"text": "First, let’s build a scatter plot. The easiest way to do this is by using the scatter method. The arguments that should be passed are the data_frame which has the data to be plotted, x_column which specifies X-axis and y_column which specifies Y-axis. All other arguments are optional(that is, a default value is assigned to them when not specified). The color_column argument colors the plot of the basis of the column specified. Let’s say in the above dataset we set color_column to be the column “fruit”. Chartify assigns different colors to different fruit names in the column. A list of values within the color_column argument is used for specific sorting of the colors. alpha is the transparency(alpha value) of a plot. Here 1.0 is completely opaque, which 0.0 is completely transparent. marker refers to the mark on the plot for values. The markers can be a circle, asterisk, diamond, triangle, and various other shapes."
},
{
"code": null,
"e": 28253,
"s": 28122,
"text": "Syntax: scatter(data_frame, x_column, y_column, size_column=None, color_column=None, color_order=None, alpha=1.0, marker=’circle’)"
},
{
"code": null,
"e": 28324,
"s": 28253,
"text": "Now let’s set the title, subtitle, and other attributes for our chart."
},
{
"code": null,
"e": 28332,
"s": 28324,
"text": "Python3"
},
{
"code": "ch.set_title(\"Quantity Fruit vs Date\")ch.set_subtitle(\"Quantity of fruits grown all around the world\") ch.axes.set_xaxis_label(\"Date\")ch.axes.set_yaxis_label(\"Quantity\")ch.set_source_label(\"Source:Chartify Examples\")",
"e": 28550,
"s": 28332,
"text": null
},
{
"code": null,
"e": 28792,
"s": 28550,
"text": "Now let’s make a scatter plot using the following and display it onto the notebook. data or the example dataset we got from Chartify will be our data_frame. The X-axis will be date and Y-axis will be quantity. The color_column will be fruit."
},
{
"code": null,
"e": 28800,
"s": 28792,
"text": "Python3"
},
{
"code": "ch.plot.scatter(data_frame=data, x_column='date', y_column='quantity', color_column='fruit')ch.show()",
"e": 28933,
"s": 28800,
"text": null
},
{
"code": null,
"e": 28941,
"s": 28933,
"text": "Output:"
},
{
"code": null,
"e": 28954,
"s": 28941,
"text": "Scatter Plot"
},
{
"code": null,
"e": 29133,
"s": 28954,
"text": "Thus, we have built a simple scatter plot. Now let’s make a histogram using the same dataset. Let’s plot a histogram that visualizes the density of data with respect to quantity."
},
{
"code": null,
"e": 29141,
"s": 29133,
"text": "Python3"
},
{
"code": "ch = chartify.Chart(y_axis_type='density')",
"e": 29184,
"s": 29141,
"text": null
},
{
"code": null,
"e": 29535,
"s": 29184,
"text": "To plot the histogram we are going to use the histogram method. Just like the scatter plot, even the histogram takes in a data_frame argument. color_column and color_order work in the same way as it did in the scatter plot. The method argument takes in a method and calculates the density of the graph on that basis. The count is the default method. "
},
{
"code": null,
"e": 29646,
"s": 29535,
"text": "Syntax: histogram(data_frame, values_column, color_column=None, color_order=None, method=’count’, bins=’auto’)"
},
{
"code": null,
"e": 29689,
"s": 29646,
"text": "Now let’s set the attributes of our chart."
},
{
"code": null,
"e": 29697,
"s": 29689,
"text": "Python3"
},
{
"code": "ch.set_title(\"Quantity vs Count\")ch.axes.set_xaxis_label(\"Quantity\")ch.axes.set_yaxis_label(\"Count\")ch.set_source_label(\"Source:Chartify Examples\")",
"e": 29845,
"s": 29697,
"text": null
},
{
"code": null,
"e": 29910,
"s": 29845,
"text": "Now let’s plot the histogram using the method mentioned earlier."
},
{
"code": null,
"e": 29918,
"s": 29910,
"text": "Python3"
},
{
"code": "ch.plot.histogram(data_frame=data, values_column='quantity')ch.show()",
"e": 29988,
"s": 29918,
"text": null
},
{
"code": null,
"e": 29996,
"s": 29988,
"text": "Output:"
},
{
"code": null,
"e": 30006,
"s": 29996,
"text": "Histogram"
},
{
"code": null,
"e": 30219,
"s": 30006,
"text": "Thus, in this article, we have plotted a histogram and a scatter plot using Spotify’s Chartify. This is just a beginner article and the same knowledge can be extended further to build more complex visualizations."
},
{
"code": null,
"e": 30238,
"s": 30219,
"text": "Data Visualization"
},
{
"code": null,
"e": 30253,
"s": 30238,
"text": "python-modules"
},
{
"code": null,
"e": 30260,
"s": 30253,
"text": "Python"
},
{
"code": null,
"e": 30358,
"s": 30260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30390,
"s": 30358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30432,
"s": 30390,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30474,
"s": 30432,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30530,
"s": 30474,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30557,
"s": 30530,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30588,
"s": 30557,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30627,
"s": 30588,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30656,
"s": 30627,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30678,
"s": 30656,
"text": "Defaultdict in Python"
}
] |
HTML | DOM Input Checkbox disabled Property - GeeksforGeeks
|
06 Mar, 2019
The Input Checkbox disabled property in HTML DOM is used to set or return whether the Input Checkbox field must be disabled or not. A disabled checkbox is unclickable and unusable. It is a boolean attribute and used to reflect the HTML Disabled attribute.
Syntax:
It returns the Input Checkbox disabled property.checkboxObject.disabled
checkboxObject.disabled
It is used to set the Input Checkbox disabled property.checkboxObject.disabled = true|falseProperty Values: It contains two property values which are listed below:true: It defines that the checkbox is disabled.False: It has the default value. It defines that the checkbox is not disabled.Return Value: It returns a boolean value which represents the checkbox is disabled or not.Example 1: This example sets the Input Checkbox disabled property.<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id="myGeeks"> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" disabled>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form><br> <button onclick="myGeeks()"> Submit </button> <!-- Script to disable checkbox --> <script> function myGeeks() { var g = document.getElementById("GFG").disabled = false; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button:Example 2: This example returns the Input Checkbox disabled property.<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id="myGeeks"> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" disabled>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form><br> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:25px;"></p> <!-- Script to return Input Checkbox disabled Property --> <script> function myGeeks() { var g = document.getElementById("GFG").disabled; document.getElementById("sudo").innerHTML = g; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button:Supported Browsers: The browser supported by DOM input Checkbox disabled property are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
checkboxObject.disabled = true|false
Property Values: It contains two property values which are listed below:
true: It defines that the checkbox is disabled.
False: It has the default value. It defines that the checkbox is not disabled.
Return Value: It returns a boolean value which represents the checkbox is disabled or not.
Example 1: This example sets the Input Checkbox disabled property.
<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id="myGeeks"> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" disabled>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form><br> <button onclick="myGeeks()"> Submit </button> <!-- Script to disable checkbox --> <script> function myGeeks() { var g = document.getElementById("GFG").disabled = false; } </script> </body> </html>
Output:Before clicking on the Button:After clicking on the Button:
Example 2: This example returns the Input Checkbox disabled property.
<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id="myGeeks"> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" disabled>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form><br> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:25px;"></p> <!-- Script to return Input Checkbox disabled Property --> <script> function myGeeks() { var g = document.getElementById("GFG").disabled; document.getElementById("sudo").innerHTML = g; } </script> </body> </html>
Output:Before clicking on the Button:After clicking on the Button:
Supported Browsers: The browser supported by DOM input Checkbox disabled property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
Web Technologies
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 ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26412,
"s": 26384,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 26668,
"s": 26412,
"text": "The Input Checkbox disabled property in HTML DOM is used to set or return whether the Input Checkbox field must be disabled or not. A disabled checkbox is unclickable and unusable. It is a boolean attribute and used to reflect the HTML Disabled attribute."
},
{
"code": null,
"e": 26676,
"s": 26668,
"text": "Syntax:"
},
{
"code": null,
"e": 26748,
"s": 26676,
"text": "It returns the Input Checkbox disabled property.checkboxObject.disabled"
},
{
"code": null,
"e": 26772,
"s": 26748,
"text": "checkboxObject.disabled"
},
{
"code": null,
"e": 29984,
"s": 26772,
"text": "It is used to set the Input Checkbox disabled property.checkboxObject.disabled = true|falseProperty Values: It contains two property values which are listed below:true: It defines that the checkbox is disabled.False: It has the default value. It defines that the checkbox is not disabled.Return Value: It returns a boolean value which represents the checkbox is disabled or not.Example 1: This example sets the Input Checkbox disabled property.<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id=\"myGeeks\"> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" disabled>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form><br> <button onclick=\"myGeeks()\"> Submit </button> <!-- Script to disable checkbox --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").disabled = false; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button:Example 2: This example returns the Input Checkbox disabled property.<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id=\"myGeeks\"> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" disabled>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form><br> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:25px;\"></p> <!-- Script to return Input Checkbox disabled Property --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").disabled; document.getElementById(\"sudo\").innerHTML = g; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button:Supported Browsers: The browser supported by DOM input Checkbox disabled property are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 30021,
"s": 29984,
"text": "checkboxObject.disabled = true|false"
},
{
"code": null,
"e": 30094,
"s": 30021,
"text": "Property Values: It contains two property values which are listed below:"
},
{
"code": null,
"e": 30142,
"s": 30094,
"text": "true: It defines that the checkbox is disabled."
},
{
"code": null,
"e": 30221,
"s": 30142,
"text": "False: It has the default value. It defines that the checkbox is not disabled."
},
{
"code": null,
"e": 30312,
"s": 30221,
"text": "Return Value: It returns a boolean value which represents the checkbox is disabled or not."
},
{
"code": null,
"e": 30379,
"s": 30312,
"text": "Example 1: This example sets the Input Checkbox disabled property."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id=\"myGeeks\"> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" disabled>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form><br> <button onclick=\"myGeeks()\"> Submit </button> <!-- Script to disable checkbox --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").disabled = false; } </script> </body> </html> ",
"e": 31439,
"s": 30379,
"text": null
},
{
"code": null,
"e": 31506,
"s": 31439,
"text": "Output:Before clicking on the Button:After clicking on the Button:"
},
{
"code": null,
"e": 31576,
"s": 31506,
"text": "Example 2: This example returns the Input Checkbox disabled property."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox disabled Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox disabled Property</h2> <form id=\"myGeeks\"> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" disabled>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form><br> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:25px;\"></p> <!-- Script to return Input Checkbox disabled Property --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").disabled; document.getElementById(\"sudo\").innerHTML = g; } </script> </body> </html> ",
"e": 32766,
"s": 31576,
"text": null
},
{
"code": null,
"e": 32833,
"s": 32766,
"text": "Output:Before clicking on the Button:After clicking on the Button:"
},
{
"code": null,
"e": 32933,
"s": 32833,
"text": "Supported Browsers: The browser supported by DOM input Checkbox disabled property are listed below:"
},
{
"code": null,
"e": 32947,
"s": 32933,
"text": "Google Chrome"
},
{
"code": null,
"e": 32965,
"s": 32947,
"text": "Internet Explorer"
},
{
"code": null,
"e": 32973,
"s": 32965,
"text": "Firefox"
},
{
"code": null,
"e": 32979,
"s": 32973,
"text": "Opera"
},
{
"code": null,
"e": 32986,
"s": 32979,
"text": "Safari"
},
{
"code": null,
"e": 33123,
"s": 32986,
"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": 33132,
"s": 33123,
"text": "HTML-DOM"
},
{
"code": null,
"e": 33137,
"s": 33132,
"text": "HTML"
},
{
"code": null,
"e": 33154,
"s": 33137,
"text": "Web Technologies"
},
{
"code": null,
"e": 33159,
"s": 33154,
"text": "HTML"
},
{
"code": null,
"e": 33257,
"s": 33159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33305,
"s": 33257,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 33329,
"s": 33305,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 33370,
"s": 33329,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 33420,
"s": 33370,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 33470,
"s": 33420,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 33510,
"s": 33470,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33543,
"s": 33510,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33588,
"s": 33543,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33631,
"s": 33588,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Node.js fs.unwatchFile() Method - GeeksforGeeks
|
08 Oct, 2021
The fs.unwatchFile() method is used to stop watching for changes on the given file. An optional listener parameter can be specified to remove only the specified listener from the file. Otherwise, all the listeners associated with the file are removed. If the file is not being watched when this function is used, then it does not perform any operation and throw any error.
Syntax:
fs.unwatchFile(filename[, listener])
Parameters: This method accepts two parameters as mentioned above and described below:
filename: It is a String, Buffer or URL that denotes the file that has to be stopped from watching.
listener: It is a function that specifies the listener previously attached using the fs.watchFile() function. If specified, only this particular listener is removed. It is an optional parameter.
Below examples illustrate the fs.unwatchFile() method in Node.js.
Example 1:
// Node.js program to demonstrate the // fs.unwatchFile() method // Import the filesystem moduleconst fs = require('fs'); // Start watching the filefs.watchFile("example_file.txt", (curr, prev) => { console.log("\nThe file was edited"); console.log("Previous Modified Time:", prev.mtime); console.log("Current Modified Time:", curr.mtime);}); // Make Changes to the file before // it has been stopped watchingsetTimeout( () => fs.writeFileSync("example_file.txt", "File Contents are Edited"), 1000); // Stop watching the filesetTimeout(() => { fs.unwatchFile("example_file.txt"); console.log("\n> File has been stopped watching");}, 6000); // Make Changes to the file after// it has been stopped watchingsetTimeout( () => fs.writeFileSync("example_file.txt", "File Contents are Edited Again"), 7000);
Output:
The file was edited
Previous Modified Time: 2020-05-30T08:43:28.216Z
Current Modified Time: 2020-05-30T08:43:37.208Z
File has been stopped watching
Example 2:
// Node.js program to demonstrate // the fs.unwatchFile() method // Import the filesystem moduleconst fs = require('fs'); // Defining 2 listeners for watching the filelet listener1 = (curr, prev) => { console.log("Listener 1: File Modified");};let listener2 = (curr, prev) => { console.log("Listener 2: File Modified");}; // Using both the listeners on one filefs.watchFile("example_file.txt", listener1);fs.watchFile("example_file.txt", listener2); // Modify the file contentssetTimeout( () => fs.writeFileSync("example_file.txt", "File Contents are Edited"), 1000); // Stop using the first listenersetTimeout(() => { fs.unwatchFile("example_file.txt", listener1); console.log("\n> Listener 1 has been stopped!\n");}, 6000); // Modify the file contents againsetTimeout( () => fs.writeFileSync("example_file.txt", "File Contents are Edited Again"), 8000);
Output:
Listener 1: File Modified
Listener 2: File Modified
Listener 1 has been stopped!
Listener 2: File Modified
Reference: https://nodejs.org/api/fs.html#fs_fs_unwatchfile_filename_listener
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
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?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24922,
"s": 24894,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25295,
"s": 24922,
"text": "The fs.unwatchFile() method is used to stop watching for changes on the given file. An optional listener parameter can be specified to remove only the specified listener from the file. Otherwise, all the listeners associated with the file are removed. If the file is not being watched when this function is used, then it does not perform any operation and throw any error."
},
{
"code": null,
"e": 25303,
"s": 25295,
"text": "Syntax:"
},
{
"code": null,
"e": 25340,
"s": 25303,
"text": "fs.unwatchFile(filename[, listener])"
},
{
"code": null,
"e": 25427,
"s": 25340,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25527,
"s": 25427,
"text": "filename: It is a String, Buffer or URL that denotes the file that has to be stopped from watching."
},
{
"code": null,
"e": 25722,
"s": 25527,
"text": "listener: It is a function that specifies the listener previously attached using the fs.watchFile() function. If specified, only this particular listener is removed. It is an optional parameter."
},
{
"code": null,
"e": 25788,
"s": 25722,
"text": "Below examples illustrate the fs.unwatchFile() method in Node.js."
},
{
"code": null,
"e": 25799,
"s": 25788,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // fs.unwatchFile() method // Import the filesystem moduleconst fs = require('fs'); // Start watching the filefs.watchFile(\"example_file.txt\", (curr, prev) => { console.log(\"\\nThe file was edited\"); console.log(\"Previous Modified Time:\", prev.mtime); console.log(\"Current Modified Time:\", curr.mtime);}); // Make Changes to the file before // it has been stopped watchingsetTimeout( () => fs.writeFileSync(\"example_file.txt\", \"File Contents are Edited\"), 1000); // Stop watching the filesetTimeout(() => { fs.unwatchFile(\"example_file.txt\"); console.log(\"\\n> File has been stopped watching\");}, 6000); // Make Changes to the file after// it has been stopped watchingsetTimeout( () => fs.writeFileSync(\"example_file.txt\", \"File Contents are Edited Again\"), 7000);",
"e": 26633,
"s": 25799,
"text": null
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Output:"
},
{
"code": null,
"e": 26791,
"s": 26641,
"text": "The file was edited\nPrevious Modified Time: 2020-05-30T08:43:28.216Z\nCurrent Modified Time: 2020-05-30T08:43:37.208Z\n\nFile has been stopped watching\n"
},
{
"code": null,
"e": 26802,
"s": 26791,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate // the fs.unwatchFile() method // Import the filesystem moduleconst fs = require('fs'); // Defining 2 listeners for watching the filelet listener1 = (curr, prev) => { console.log(\"Listener 1: File Modified\");};let listener2 = (curr, prev) => { console.log(\"Listener 2: File Modified\");}; // Using both the listeners on one filefs.watchFile(\"example_file.txt\", listener1);fs.watchFile(\"example_file.txt\", listener2); // Modify the file contentssetTimeout( () => fs.writeFileSync(\"example_file.txt\", \"File Contents are Edited\"), 1000); // Stop using the first listenersetTimeout(() => { fs.unwatchFile(\"example_file.txt\", listener1); console.log(\"\\n> Listener 1 has been stopped!\\n\");}, 6000); // Modify the file contents againsetTimeout( () => fs.writeFileSync(\"example_file.txt\", \"File Contents are Edited Again\"), 8000);",
"e": 27690,
"s": 26802,
"text": null
},
{
"code": null,
"e": 27698,
"s": 27690,
"text": "Output:"
},
{
"code": null,
"e": 27808,
"s": 27698,
"text": "Listener 1: File Modified\nListener 2: File Modified\n\nListener 1 has been stopped!\n\nListener 2: File Modified\n"
},
{
"code": null,
"e": 27886,
"s": 27808,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_unwatchfile_filename_listener"
},
{
"code": null,
"e": 27904,
"s": 27886,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 27911,
"s": 27904,
"text": "Picked"
},
{
"code": null,
"e": 27919,
"s": 27911,
"text": "Node.js"
},
{
"code": null,
"e": 27936,
"s": 27919,
"text": "Web Technologies"
},
{
"code": null,
"e": 28034,
"s": 27936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28043,
"s": 28034,
"text": "Comments"
},
{
"code": null,
"e": 28056,
"s": 28043,
"text": "Old Comments"
},
{
"code": null,
"e": 28093,
"s": 28056,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28125,
"s": 28093,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 28156,
"s": 28125,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 28183,
"s": 28156,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28230,
"s": 28183,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 28272,
"s": 28230,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28334,
"s": 28272,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28377,
"s": 28334,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28427,
"s": 28377,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Angular PrimeNG ColorPicker Component - GeeksforGeeks
|
19 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the colorPicker component in Angular PrimeNG.
colorPicker component: It is used to make a component in which users can select colours.
Properties:
style: It is used to set the inline style of the element. It is of string data type & the default value is null.
styleClass: It is used to set the style class of the element. It is of string data type & the default value is null.
inline: It is used to specify whether to display as an overlay or not. It is of boolean data type & the default value is false.
format: It is used to set the format to use in value binding, supported formats are hex, RGB & HSB. It is of string data type & the default value is hex.
appendTo: It is used to set the target element to attach the overlay. It is of string data type & the default value is null.
tabindex: It is used to set the index of the element in tabbing order. It is of number data type & the default value is null.
disabled: It is used to specify that the component should be disabled. It is of the boolean data type & the default value is false.
inputId: It is an ID identifier of the underlying input element. It is of string data type & the default value is null.
baseZIndex: It is used to set the base zIndex value to use in layering. It is of number data type, the default value is 0.
autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true.
showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0,0,0.2,1).
hideTransitionOptions: It is used to set the Transition options of the hide animation. It is of string data type, the default value is .1s linear.
Events:
onChange: It is a callback that is fired when a color is selected.
onShow: It is a callback that is fired when the popup is shown.
onHide: It is a callback that is fired when the popup is hidden.
Styling:
p-colorpicker: It is a styling Container element.
p-colorpicker-overlay: It is a styling Container element in overlay mode.
p-colorpicker-preview: It is Preview input in overlay mode.
p-colorpicker-panel: It is a styling Panel element of the colorpicker.
p-colorpicker-content: It is a Wrapper that contains color and hue sections.
p-colorpicker-color-selector: It is a Color selector.
p-colorpicker-color: It is a styling Color element.
p-colorpicker-color-handle: It is the handle of the color element.
p-colorpicker-hue: It is the Hue slider.
p-colorpicker-hue-handle: It is the Handle of the hue slider.
Creating Angular application & module Installation:
Step 1: Create an Angular application using the following command.ng new appname
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
npm install primeng --save
npm install primeicons --save
Project Structure: After completing the above processes, it will look like the following.
There are 2 properties to use the color picker, the first property is using inline & the second property is using overlay.
Example 1: In this example, we will use an inline property to select the color & this is the basic example that shows how to use the colorPicker component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG colorPicker component</h5><p-colorPicker [(ngModel)]="selectColor" [inline]="true"> </p-colorPicker>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { HttpClientModule } from "@angular/common/http";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component"; import { ColorPickerModule } from "primeng/colorpicker"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ColorPickerModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { selectColor: string;}
Output:
Example 2: In this example, we will know how to use the overlay property to select the color in the colorPicker component.
app.component.html:
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG colorPicker component</h5><p-colorPicker [inline]="false" [(ngModel)]="gfg"></p-colorPicker>
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpClientModule } from '@angular/common/http';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { ColorPickerModule } from 'primeng/colorpicker'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ColorPickerModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { gfg: string = "#05f211";}
Output:
Reference: https://primefaces.org/primeng/showcase/#/colorpicker
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 26641,
"s": 26354,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the colorPicker component in Angular PrimeNG."
},
{
"code": null,
"e": 26730,
"s": 26641,
"text": "colorPicker component: It is used to make a component in which users can select colours."
},
{
"code": null,
"e": 26742,
"s": 26730,
"text": "Properties:"
},
{
"code": null,
"e": 26855,
"s": 26742,
"text": "style: It is used to set the inline style of the element. It is of string data type & the default value is null."
},
{
"code": null,
"e": 26972,
"s": 26855,
"text": "styleClass: It is used to set the style class of the element. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27100,
"s": 26972,
"text": "inline: It is used to specify whether to display as an overlay or not. It is of boolean data type & the default value is false."
},
{
"code": null,
"e": 27254,
"s": 27100,
"text": "format: It is used to set the format to use in value binding, supported formats are hex, RGB & HSB. It is of string data type & the default value is hex."
},
{
"code": null,
"e": 27379,
"s": 27254,
"text": "appendTo: It is used to set the target element to attach the overlay. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27505,
"s": 27379,
"text": "tabindex: It is used to set the index of the element in tabbing order. It is of number data type & the default value is null."
},
{
"code": null,
"e": 27637,
"s": 27505,
"text": "disabled: It is used to specify that the component should be disabled. It is of the boolean data type & the default value is false."
},
{
"code": null,
"e": 27757,
"s": 27637,
"text": "inputId: It is an ID identifier of the underlying input element. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27880,
"s": 27757,
"text": "baseZIndex: It is used to set the base zIndex value to use in layering. It is of number data type, the default value is 0."
},
{
"code": null,
"e": 28019,
"s": 27880,
"text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of the boolean data type, the default value is true."
},
{
"code": null,
"e": 28184,
"s": 28019,
"text": "showTransitionOptions: It is used to set the Transition options of the show animation. It is of string data type, the default value is .12s cubic-bezier(0,0,0.2,1)."
},
{
"code": null,
"e": 28331,
"s": 28184,
"text": "hideTransitionOptions: It is used to set the Transition options of the hide animation. It is of string data type, the default value is .1s linear."
},
{
"code": null,
"e": 28339,
"s": 28331,
"text": "Events:"
},
{
"code": null,
"e": 28406,
"s": 28339,
"text": "onChange: It is a callback that is fired when a color is selected."
},
{
"code": null,
"e": 28470,
"s": 28406,
"text": "onShow: It is a callback that is fired when the popup is shown."
},
{
"code": null,
"e": 28535,
"s": 28470,
"text": "onHide: It is a callback that is fired when the popup is hidden."
},
{
"code": null,
"e": 28546,
"s": 28537,
"text": "Styling:"
},
{
"code": null,
"e": 28596,
"s": 28546,
"text": "p-colorpicker: It is a styling Container element."
},
{
"code": null,
"e": 28670,
"s": 28596,
"text": "p-colorpicker-overlay: It is a styling Container element in overlay mode."
},
{
"code": null,
"e": 28730,
"s": 28670,
"text": "p-colorpicker-preview: It is Preview input in overlay mode."
},
{
"code": null,
"e": 28801,
"s": 28730,
"text": "p-colorpicker-panel: It is a styling Panel element of the colorpicker."
},
{
"code": null,
"e": 28878,
"s": 28801,
"text": "p-colorpicker-content: It is a Wrapper that contains color and hue sections."
},
{
"code": null,
"e": 28932,
"s": 28878,
"text": "p-colorpicker-color-selector: It is a Color selector."
},
{
"code": null,
"e": 28984,
"s": 28932,
"text": "p-colorpicker-color: It is a styling Color element."
},
{
"code": null,
"e": 29051,
"s": 28984,
"text": "p-colorpicker-color-handle: It is the handle of the color element."
},
{
"code": null,
"e": 29092,
"s": 29051,
"text": "p-colorpicker-hue: It is the Hue slider."
},
{
"code": null,
"e": 29154,
"s": 29092,
"text": "p-colorpicker-hue-handle: It is the Handle of the hue slider."
},
{
"code": null,
"e": 29206,
"s": 29154,
"text": "Creating Angular application & module Installation:"
},
{
"code": null,
"e": 29287,
"s": 29206,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 29302,
"s": 29287,
"text": "ng new appname"
},
{
"code": null,
"e": 29409,
"s": 29302,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 29420,
"s": 29409,
"text": "cd appname"
},
{
"code": null,
"e": 29525,
"s": 29420,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29582,
"s": 29525,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29672,
"s": 29582,
"text": "Project Structure: After completing the above processes, it will look like the following."
},
{
"code": null,
"e": 29795,
"s": 29672,
"text": "There are 2 properties to use the color picker, the first property is using inline & the second property is using overlay."
},
{
"code": null,
"e": 29952,
"s": 29795,
"text": "Example 1: In this example, we will use an inline property to select the color & this is the basic example that shows how to use the colorPicker component. "
},
{
"code": null,
"e": 29971,
"s": 29952,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG colorPicker component</h5><p-colorPicker [(ngModel)]=\"selectColor\" [inline]=\"true\"> </p-colorPicker>",
"e": 30106,
"s": 29971,
"text": null
},
{
"code": null,
"e": 30122,
"s": 30108,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { HttpClientModule } from \"@angular/common/http\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\"; import { ColorPickerModule } from \"primeng/colorpicker\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ColorPickerModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 30712,
"s": 30122,
"text": null
},
{
"code": null,
"e": 30729,
"s": 30712,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { selectColor: string;}",
"e": 30897,
"s": 30729,
"text": null
},
{
"code": null,
"e": 30905,
"s": 30897,
"text": "Output:"
},
{
"code": null,
"e": 31029,
"s": 30905,
"text": "Example 2: In this example, we will know how to use the overlay property to select the color in the colorPicker component. "
},
{
"code": null,
"e": 31049,
"s": 31029,
"text": "app.component.html:"
},
{
"code": null,
"e": 31068,
"s": 31049,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG colorPicker component</h5><p-colorPicker [inline]=\"false\" [(ngModel)]=\"gfg\"></p-colorPicker>",
"e": 31195,
"s": 31068,
"text": null
},
{
"code": null,
"e": 31209,
"s": 31195,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpClientModule } from '@angular/common/http';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { ColorPickerModule } from 'primeng/colorpicker'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ColorPickerModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 31797,
"s": 31209,
"text": null
},
{
"code": null,
"e": 31814,
"s": 31797,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { gfg: string = \"#05f211\";}",
"e": 31986,
"s": 31814,
"text": null
},
{
"code": null,
"e": 31994,
"s": 31986,
"text": "Output:"
},
{
"code": null,
"e": 32059,
"s": 31994,
"text": "Reference: https://primefaces.org/primeng/showcase/#/colorpicker"
},
{
"code": null,
"e": 32075,
"s": 32059,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 32085,
"s": 32075,
"text": "AngularJS"
},
{
"code": null,
"e": 32102,
"s": 32085,
"text": "Web Technologies"
},
{
"code": null,
"e": 32200,
"s": 32102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32235,
"s": 32200,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32270,
"s": 32235,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32294,
"s": 32270,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 32329,
"s": 32294,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 32382,
"s": 32329,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 32422,
"s": 32382,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32455,
"s": 32422,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32500,
"s": 32455,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32543,
"s": 32500,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to handle newlines in JSON ? - GeeksforGeeks
|
11 Jan, 2021
JSON is a language-independent data format. It is a JavaScript Object Notation. Basically, it is a text-based format used to represent structured data. Data is being sent in this format from the server to the client.
In this article, we will see how to approach or handle newlines in JSON.
Syntax:
'\\n'
About ‘\\n’: The above syntax is used whenever we want to sent data in multiple lines in a JSON format. Generally, it is difficult to send data in new lines from server to web. But by using this we can achieve the following requirement.
Approach:
First, we need to declare a variable as “json1” and then we need to assign the JSON to it.
In JSON object make sure that you are having a sentence where you need to print in different lines.
Now in-order to print the statements in different lines we need to use ‘\\n’ (backward slash).
As we now know the technique to print in newlines, now just add ‘\\n’ wherever you want.
Now, as it is a JSON we need to parse it in order to print it. So use JSON.parse() method and parse the JSON.
After completing the above steps write a console.log() statement to print the output.
Once you are done with it, execute the file to get the output.
Code implementation:
Example 1:
Javascript
var json = '{ "companyInfo" : "GeeksForGeeks\\n\\nOne stop solution for CS subjects"}'; let finalJson=JSON.parse(json); console.log(finalJson.companyInfo)
Output:
GeeksForGeeks
One stop solution for CS subjects
Example 2:
Javascript
var student = '{ "details" : "P.V.Ramesh\\nC.S.E.\\nI.I.T. Hyderabad"}'; let finalJson = JSON.parse(student); console.log(finalJson.details)
Output:
P.V.Ramesh
C.S.E.
I.I.T. Hyderabad
JavaScript-Misc
JSON
Picked
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25677,
"s": 25649,
"text": "\n11 Jan, 2021"
},
{
"code": null,
"e": 25894,
"s": 25677,
"text": "JSON is a language-independent data format. It is a JavaScript Object Notation. Basically, it is a text-based format used to represent structured data. Data is being sent in this format from the server to the client."
},
{
"code": null,
"e": 25967,
"s": 25894,
"text": "In this article, we will see how to approach or handle newlines in JSON."
},
{
"code": null,
"e": 25976,
"s": 25967,
"text": "Syntax: "
},
{
"code": null,
"e": 25982,
"s": 25976,
"text": "'\\\\n'"
},
{
"code": null,
"e": 26219,
"s": 25982,
"text": "About ‘\\\\n’: The above syntax is used whenever we want to sent data in multiple lines in a JSON format. Generally, it is difficult to send data in new lines from server to web. But by using this we can achieve the following requirement."
},
{
"code": null,
"e": 26229,
"s": 26219,
"text": "Approach:"
},
{
"code": null,
"e": 26320,
"s": 26229,
"text": "First, we need to declare a variable as “json1” and then we need to assign the JSON to it."
},
{
"code": null,
"e": 26420,
"s": 26320,
"text": "In JSON object make sure that you are having a sentence where you need to print in different lines."
},
{
"code": null,
"e": 26515,
"s": 26420,
"text": "Now in-order to print the statements in different lines we need to use ‘\\\\n’ (backward slash)."
},
{
"code": null,
"e": 26604,
"s": 26515,
"text": "As we now know the technique to print in newlines, now just add ‘\\\\n’ wherever you want."
},
{
"code": null,
"e": 26714,
"s": 26604,
"text": "Now, as it is a JSON we need to parse it in order to print it. So use JSON.parse() method and parse the JSON."
},
{
"code": null,
"e": 26800,
"s": 26714,
"text": "After completing the above steps write a console.log() statement to print the output."
},
{
"code": null,
"e": 26863,
"s": 26800,
"text": "Once you are done with it, execute the file to get the output."
},
{
"code": null,
"e": 26884,
"s": 26863,
"text": "Code implementation:"
},
{
"code": null,
"e": 26895,
"s": 26884,
"text": "Example 1:"
},
{
"code": null,
"e": 26906,
"s": 26895,
"text": "Javascript"
},
{
"code": "var json = '{ \"companyInfo\" : \"GeeksForGeeks\\\\n\\\\nOne stop solution for CS subjects\"}'; let finalJson=JSON.parse(json); console.log(finalJson.companyInfo)",
"e": 27094,
"s": 26906,
"text": null
},
{
"code": null,
"e": 27102,
"s": 27094,
"text": "Output:"
},
{
"code": null,
"e": 27152,
"s": 27102,
"text": "GeeksForGeeks\n\n\nOne stop solution for CS subjects"
},
{
"code": null,
"e": 27163,
"s": 27152,
"text": "Example 2:"
},
{
"code": null,
"e": 27174,
"s": 27163,
"text": "Javascript"
},
{
"code": "var student = '{ \"details\" : \"P.V.Ramesh\\\\nC.S.E.\\\\nI.I.T. Hyderabad\"}'; let finalJson = JSON.parse(student); console.log(finalJson.details)",
"e": 27336,
"s": 27174,
"text": null
},
{
"code": null,
"e": 27344,
"s": 27336,
"text": "Output:"
},
{
"code": null,
"e": 27379,
"s": 27344,
"text": "P.V.Ramesh\nC.S.E.\nI.I.T. Hyderabad"
},
{
"code": null,
"e": 27395,
"s": 27379,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27400,
"s": 27395,
"text": "JSON"
},
{
"code": null,
"e": 27407,
"s": 27400,
"text": "Picked"
},
{
"code": null,
"e": 27418,
"s": 27407,
"text": "JavaScript"
},
{
"code": null,
"e": 27435,
"s": 27418,
"text": "Web Technologies"
},
{
"code": null,
"e": 27533,
"s": 27435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27573,
"s": 27533,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27618,
"s": 27573,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27679,
"s": 27618,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27751,
"s": 27679,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27803,
"s": 27751,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27843,
"s": 27803,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27876,
"s": 27843,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27921,
"s": 27876,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27964,
"s": 27921,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Ruby/Tk - Scrollbar Widget
|
A Scrollbar helps the user to see all parts of another widget, whose content is typically much larger than what can be shown in the available screen space.
A scrollbar displays two arrows, one at each end of the scrollbar, and a slider in the middle portion of the scrollbar. The position and size of the slider indicate which portion of the document is visible in the associated window.
Here is a simple syntax to create this widget −
TkScrollbar.new {
.....Standard Options....
.....Widget-specific Options....
}
activebackground
highlightbackground
orient
takefocus
background
highlightcolor
relief
troughcolor
borderwidth
highlightthickness
repeatdelay
cursor
jump
repeatinterval
These options have been described in the previous chapter.
activerelief => String
Specifies the relief to use when displaying the element that is active, if any. Elements other than the active element are always displayed with a raised relief.
command => String
Specifies a callback to invoke to change the view in the widget associated with the scrollbar. When a user requests a view change by manipulating the scrollbar, the callback is invoked.
elementborderwidth => Integer
Specifies the width of borders drawn around the internal elements of the scrollbar.
width => Integer
Specifies the desired narrow dimension of the scrollbar window, not including 3-D border, if any. For vertical scrollbars this will be the width and for horizontal scrollbars this will be the height.
A scrollbar displays five elements, which are referred in the methods for the scrollbar −
arrow1 − The top or left arrow in the scrollbar.
arrow1 − The top or left arrow in the scrollbar.
trough1 − The region between the slider and arrow1.
trough1 − The region between the slider and arrow1.
slider − The rectangle that indicates what is visible in the associated widget.
slider − The rectangle that indicates what is visible in the associated widget.
trough2 − The region between the slider and arrow2.
trough2 − The region between the slider and arrow2.
arrow2 − The bottom or right arrow in the scrollbar.
arrow2 − The bottom or right arrow in the scrollbar.
The following useful methods to manipulate the content of a scrollbar −
activate(?element?) − Marks the element indicated by element as active, which causes it to be displayed as specified by the activebackground and activerelief options. The only element values understood by this command are arrow1, slider, or arrow2.
activate(?element?) − Marks the element indicated by element as active, which causes it to be displayed as specified by the activebackground and activerelief options. The only element values understood by this command are arrow1, slider, or arrow2.
delta(deltaX, deltaY) − Returns a real number indicating the fractional change in the scrollbar setting that corresponds to a given change in slider position.
delta(deltaX, deltaY) − Returns a real number indicating the fractional change in the scrollbar setting that corresponds to a given change in slider position.
fraction(x, y) − Returns a real number between 0 and 1 indicating where the point given by x and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so on.
fraction(x, y) − Returns a real number between 0 and 1 indicating where the point given by x and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so on.
get − Returns the scrollbar settings in the form of a list whose elements are the arguments to the most recent set method.
get − Returns the scrollbar settings in the form of a list whose elements are the arguments to the most recent set method.
identify(x, y) − Returns the name of the element under the point given by x and y (such as arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y must be pixel coordinates relative to the scrollbar widget.
identify(x, y) − Returns the name of the element under the point given by x and y (such as arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y must be pixel coordinates relative to the scrollbar widget.
set(first, last) − This command is invoked by the scrollbar's associated widget to tell the scrollbar about the current view in the widget. The command takes two arguments, each of which is a real fraction between 0 and 1. The fractions describe the range of the document that is visible in the associated widget.
set(first, last) − This command is invoked by the scrollbar's associated widget to tell the scrollbar about the current view in the widget. The command takes two arguments, each of which is a real fraction between 0 and 1. The fractions describe the range of the document that is visible in the associated widget.
Ruby/Tk automatically creates class bindings for scrollbars that gives them the following default behavior. If the behavior is different for vertical and horizontal scrollbars, the horizontal behavior is described in parentheses −
Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one unit so that the document appears to move down (right) one unit. If the button is held down, the action auto-repeats.
Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one unit so that the document appears to move down (right) one unit. If the button is held down, the action auto-repeats.
Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one screenful so that the document appears to move down (right) one screenful. If the button is held down, the action auto-repeats.
Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one screenful so that the document appears to move down (right) one screenful. If the button is held down, the action auto-repeats.
Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the jump option is true, then the view doesn't drag along with the slider; it changes only when the mouse button is released.
Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the jump option is true, then the view doesn't drag along with the slider; it changes only when the mouse button is released.
Pressing button 1 over trough2 causes the view in the associated widget to shift down (right) by one screenful so that the document appears to move up (left) one screenful. If the button is held down, the action auto-repeats.
Pressing button 1 over trough2 causes the view in the associated widget to shift down (right) by one screenful so that the document appears to move up (left) one screenful. If the button is held down, the action auto-repeats.
Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by one unit so that the document appears to move up (left) one unit. If the button is held down, the action auto-repeats.
Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by one unit so that the document appears to move up (left) one unit. If the button is held down, the action auto-repeats.
If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse position; dragging the mouse with button 2 down causes the view to drag with the mouse. If button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1.
If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse position; dragging the mouse with button 2 down causes the view to drag with the mouse. If button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1.
If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1 the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2 the view changes to the very bottom (right) of the document; if the mouse is anywhere else then the button press has no effect.
If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1 the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2 the view changes to the very bottom (right) of the document; if the mouse is anywhere else then the button press has no effect.
In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect.
In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect.
In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect.
In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect.
In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect.
In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect.
In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect.
In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect.
The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2, respectively.
The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2, respectively.
The Home key adjusts the view to the top (left edge) of the document.
The Home key adjusts the view to the top (left edge) of the document.
The End key adjusts the view to the bottom (right edge) of the document.
The End key adjusts the view to the bottom (right edge) of the document.
require "tk"
list = scroll = nil
list = TkListbox.new {
yscroll proc{|idx|
scroll.set *idx
}
width 20
height 16
setgrid 1
pack('side' => 'left', 'fill' => 'y', 'expand' => 1)
}
scroll = TkScrollbar.new {
command proc{|idx|
list.yview *idx
}
pack('side' => 'left', 'fill' => 'y', 'expand' => 1)
}
for f in Dir.glob("*")
list.insert 'end', f
end
Tk.mainloop
This will produce the following result −
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2450,
"s": 2294,
"text": "A Scrollbar helps the user to see all parts of another widget, whose content is typically much larger than what can be shown in the available screen space."
},
{
"code": null,
"e": 2682,
"s": 2450,
"text": "A scrollbar displays two arrows, one at each end of the scrollbar, and a slider in the middle portion of the scrollbar. The position and size of the slider indicate which portion of the document is visible in the associated window."
},
{
"code": null,
"e": 2730,
"s": 2682,
"text": "Here is a simple syntax to create this widget −"
},
{
"code": null,
"e": 2816,
"s": 2730,
"text": "TkScrollbar.new {\n .....Standard Options....\n .....Widget-specific Options....\n}\n"
},
{
"code": null,
"e": 2833,
"s": 2816,
"text": "activebackground"
},
{
"code": null,
"e": 2853,
"s": 2833,
"text": "highlightbackground"
},
{
"code": null,
"e": 2860,
"s": 2853,
"text": "orient"
},
{
"code": null,
"e": 2870,
"s": 2860,
"text": "takefocus"
},
{
"code": null,
"e": 2881,
"s": 2870,
"text": "background"
},
{
"code": null,
"e": 2896,
"s": 2881,
"text": "highlightcolor"
},
{
"code": null,
"e": 2903,
"s": 2896,
"text": "relief"
},
{
"code": null,
"e": 2915,
"s": 2903,
"text": "troughcolor"
},
{
"code": null,
"e": 2927,
"s": 2915,
"text": "borderwidth"
},
{
"code": null,
"e": 2946,
"s": 2927,
"text": "highlightthickness"
},
{
"code": null,
"e": 2958,
"s": 2946,
"text": "repeatdelay"
},
{
"code": null,
"e": 2965,
"s": 2958,
"text": "cursor"
},
{
"code": null,
"e": 2970,
"s": 2965,
"text": "jump"
},
{
"code": null,
"e": 2985,
"s": 2970,
"text": "repeatinterval"
},
{
"code": null,
"e": 3044,
"s": 2985,
"text": "These options have been described in the previous chapter."
},
{
"code": null,
"e": 3068,
"s": 3044,
"text": "activerelief => String"
},
{
"code": null,
"e": 3230,
"s": 3068,
"text": "Specifies the relief to use when displaying the element that is active, if any. Elements other than the active element are always displayed with a raised relief."
},
{
"code": null,
"e": 3249,
"s": 3230,
"text": "command => String"
},
{
"code": null,
"e": 3435,
"s": 3249,
"text": "Specifies a callback to invoke to change the view in the widget associated with the scrollbar. When a user requests a view change by manipulating the scrollbar, the callback is invoked."
},
{
"code": null,
"e": 3466,
"s": 3435,
"text": "elementborderwidth => Integer"
},
{
"code": null,
"e": 3550,
"s": 3466,
"text": "Specifies the width of borders drawn around the internal elements of the scrollbar."
},
{
"code": null,
"e": 3568,
"s": 3550,
"text": "width => Integer"
},
{
"code": null,
"e": 3768,
"s": 3568,
"text": "Specifies the desired narrow dimension of the scrollbar window, not including 3-D border, if any. For vertical scrollbars this will be the width and for horizontal scrollbars this will be the height."
},
{
"code": null,
"e": 3858,
"s": 3768,
"text": "A scrollbar displays five elements, which are referred in the methods for the scrollbar −"
},
{
"code": null,
"e": 3907,
"s": 3858,
"text": "arrow1 − The top or left arrow in the scrollbar."
},
{
"code": null,
"e": 3956,
"s": 3907,
"text": "arrow1 − The top or left arrow in the scrollbar."
},
{
"code": null,
"e": 4008,
"s": 3956,
"text": "trough1 − The region between the slider and arrow1."
},
{
"code": null,
"e": 4060,
"s": 4008,
"text": "trough1 − The region between the slider and arrow1."
},
{
"code": null,
"e": 4140,
"s": 4060,
"text": "slider − The rectangle that indicates what is visible in the associated widget."
},
{
"code": null,
"e": 4220,
"s": 4140,
"text": "slider − The rectangle that indicates what is visible in the associated widget."
},
{
"code": null,
"e": 4272,
"s": 4220,
"text": "trough2 − The region between the slider and arrow2."
},
{
"code": null,
"e": 4324,
"s": 4272,
"text": "trough2 − The region between the slider and arrow2."
},
{
"code": null,
"e": 4377,
"s": 4324,
"text": "arrow2 − The bottom or right arrow in the scrollbar."
},
{
"code": null,
"e": 4430,
"s": 4377,
"text": "arrow2 − The bottom or right arrow in the scrollbar."
},
{
"code": null,
"e": 4502,
"s": 4430,
"text": "The following useful methods to manipulate the content of a scrollbar −"
},
{
"code": null,
"e": 4751,
"s": 4502,
"text": "activate(?element?) − Marks the element indicated by element as active, which causes it to be displayed as specified by the activebackground and activerelief options. The only element values understood by this command are arrow1, slider, or arrow2."
},
{
"code": null,
"e": 5000,
"s": 4751,
"text": "activate(?element?) − Marks the element indicated by element as active, which causes it to be displayed as specified by the activebackground and activerelief options. The only element values understood by this command are arrow1, slider, or arrow2."
},
{
"code": null,
"e": 5159,
"s": 5000,
"text": "delta(deltaX, deltaY) − Returns a real number indicating the fractional change in the scrollbar setting that corresponds to a given change in slider position."
},
{
"code": null,
"e": 5318,
"s": 5159,
"text": "delta(deltaX, deltaY) − Returns a real number indicating the fractional change in the scrollbar setting that corresponds to a given change in slider position."
},
{
"code": null,
"e": 5607,
"s": 5318,
"text": "fraction(x, y) − Returns a real number between 0 and 1 indicating where the point given by x and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so on."
},
{
"code": null,
"e": 5896,
"s": 5607,
"text": "fraction(x, y) − Returns a real number between 0 and 1 indicating where the point given by x and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so on."
},
{
"code": null,
"e": 6019,
"s": 5896,
"text": "get − Returns the scrollbar settings in the form of a list whose elements are the arguments to the most recent set method."
},
{
"code": null,
"e": 6142,
"s": 6019,
"text": "get − Returns the scrollbar settings in the form of a list whose elements are the arguments to the most recent set method."
},
{
"code": null,
"e": 6388,
"s": 6142,
"text": "identify(x, y) − Returns the name of the element under the point given by x and y (such as arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y must be pixel coordinates relative to the scrollbar widget."
},
{
"code": null,
"e": 6634,
"s": 6388,
"text": "identify(x, y) − Returns the name of the element under the point given by x and y (such as arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y must be pixel coordinates relative to the scrollbar widget."
},
{
"code": null,
"e": 6948,
"s": 6634,
"text": "set(first, last) − This command is invoked by the scrollbar's associated widget to tell the scrollbar about the current view in the widget. The command takes two arguments, each of which is a real fraction between 0 and 1. The fractions describe the range of the document that is visible in the associated widget."
},
{
"code": null,
"e": 7262,
"s": 6948,
"text": "set(first, last) − This command is invoked by the scrollbar's associated widget to tell the scrollbar about the current view in the widget. The command takes two arguments, each of which is a real fraction between 0 and 1. The fractions describe the range of the document that is visible in the associated widget."
},
{
"code": null,
"e": 7493,
"s": 7262,
"text": "Ruby/Tk automatically creates class bindings for scrollbars that gives them the following default behavior. If the behavior is different for vertical and horizontal scrollbars, the horizontal behavior is described in parentheses −"
},
{
"code": null,
"e": 7708,
"s": 7493,
"text": "Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one unit so that the document appears to move down (right) one unit. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 7923,
"s": 7708,
"text": "Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one unit so that the document appears to move down (right) one unit. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 8149,
"s": 7923,
"text": "Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one screenful so that the document appears to move down (right) one screenful. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 8375,
"s": 8149,
"text": "Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one screenful so that the document appears to move down (right) one screenful. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 8592,
"s": 8375,
"text": "Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the jump option is true, then the view doesn't drag along with the slider; it changes only when the mouse button is released."
},
{
"code": null,
"e": 8809,
"s": 8592,
"text": "Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the jump option is true, then the view doesn't drag along with the slider; it changes only when the mouse button is released."
},
{
"code": null,
"e": 9035,
"s": 8809,
"text": "Pressing button 1 over trough2 causes the view in the associated widget to shift down (right) by one screenful so that the document appears to move up (left) one screenful. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 9261,
"s": 9035,
"text": "Pressing button 1 over trough2 causes the view in the associated widget to shift down (right) by one screenful so that the document appears to move up (left) one screenful. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 9476,
"s": 9261,
"text": "Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by one unit so that the document appears to move up (left) one unit. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 9691,
"s": 9476,
"text": "Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by one unit so that the document appears to move up (left) one unit. If the button is held down, the action auto-repeats."
},
{
"code": null,
"e": 9974,
"s": 9691,
"text": "If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse position; dragging the mouse with button 2 down causes the view to drag with the mouse. If button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1."
},
{
"code": null,
"e": 10257,
"s": 9974,
"text": "If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse position; dragging the mouse with button 2 down causes the view to drag with the mouse. If button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1."
},
{
"code": null,
"e": 10575,
"s": 10257,
"text": "If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1 the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2 the view changes to the very bottom (right) of the document; if the mouse is anywhere else then the button press has no effect."
},
{
"code": null,
"e": 10893,
"s": 10575,
"text": "If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1 the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2 the view changes to the very bottom (right) of the document; if the mouse is anywhere else then the button press has no effect."
},
{
"code": null,
"e": 11066,
"s": 10893,
"text": "In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect."
},
{
"code": null,
"e": 11239,
"s": 11066,
"text": "In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect."
},
{
"code": null,
"e": 11421,
"s": 11239,
"text": "In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect."
},
{
"code": null,
"e": 11603,
"s": 11421,
"text": "In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect."
},
{
"code": null,
"e": 11776,
"s": 11603,
"text": "In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect."
},
{
"code": null,
"e": 11949,
"s": 11776,
"text": "In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect."
},
{
"code": null,
"e": 12131,
"s": 11949,
"text": "In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect."
},
{
"code": null,
"e": 12313,
"s": 12131,
"text": "In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect."
},
{
"code": null,
"e": 12416,
"s": 12313,
"text": "The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2, respectively."
},
{
"code": null,
"e": 12519,
"s": 12416,
"text": "The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2, respectively."
},
{
"code": null,
"e": 12589,
"s": 12519,
"text": "The Home key adjusts the view to the top (left edge) of the document."
},
{
"code": null,
"e": 12659,
"s": 12589,
"text": "The Home key adjusts the view to the top (left edge) of the document."
},
{
"code": null,
"e": 12732,
"s": 12659,
"text": "The End key adjusts the view to the bottom (right edge) of the document."
},
{
"code": null,
"e": 12805,
"s": 12732,
"text": "The End key adjusts the view to the bottom (right edge) of the document."
},
{
"code": null,
"e": 13206,
"s": 12805,
"text": "require \"tk\"\n\nlist = scroll = nil\n\nlist = TkListbox.new {\n yscroll proc{|idx|\n scroll.set *idx\n }\n width 20\n height 16\n setgrid 1\n pack('side' => 'left', 'fill' => 'y', 'expand' => 1)\n}\nscroll = TkScrollbar.new {\n command proc{|idx|\n list.yview *idx\n }\n pack('side' => 'left', 'fill' => 'y', 'expand' => 1)\n}\n\nfor f in Dir.glob(\"*\")\n list.insert 'end', f\nend\n\nTk.mainloop"
},
{
"code": null,
"e": 13247,
"s": 13206,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 13282,
"s": 13247,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 13310,
"s": 13282,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13345,
"s": 13310,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13365,
"s": 13345,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 13400,
"s": 13365,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 13410,
"s": 13400,
"text": " YouAccel"
},
{
"code": null,
"e": 13444,
"s": 13410,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 13462,
"s": 13444,
"text": " Programming Line"
},
{
"code": null,
"e": 13495,
"s": 13462,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13518,
"s": 13495,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 13553,
"s": 13518,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13576,
"s": 13553,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 13583,
"s": 13576,
"text": " Print"
},
{
"code": null,
"e": 13594,
"s": 13583,
"text": " Add Notes"
}
] |
How to check the permissions of a directory using Python?
|
You can use os.access(path, mode) to check the directory permission with modes for reading, writing and execution permissions. For being able to write you'll also need to check for execution permission. For example,
>>> import os
>>> os.access('my_folder', os.R_OK) # Check for read access
True
>>> os.access('my_folder', os.W_OK) # Check for write access
True
>>> os.access('my_folder', os.X_OK) # Check for execution access
True
>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory
True
You can also follow a common Python idiom: It's easier to ask for forgiveness than for permission. Following that idiom, you should try writing to the directory in question, and catch the error if you don't have the permission to do so.
|
[
{
"code": null,
"e": 1278,
"s": 1062,
"text": "You can use os.access(path, mode) to check the directory permission with modes for reading, writing and execution permissions. For being able to write you'll also need to check for execution permission. For example,"
},
{
"code": null,
"e": 1590,
"s": 1278,
"text": ">>> import os\n>>> os.access('my_folder', os.R_OK) # Check for read access\nTrue\n>>> os.access('my_folder', os.W_OK) # Check for write access\nTrue\n>>> os.access('my_folder', os.X_OK) # Check for execution access\nTrue\n>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory\nTrue"
},
{
"code": null,
"e": 1827,
"s": 1590,
"text": "You can also follow a common Python idiom: It's easier to ask for forgiveness than for permission. Following that idiom, you should try writing to the directory in question, and catch the error if you don't have the permission to do so."
}
] |
GATE | Gate IT 2008 | Question 61 - GeeksforGeeks
|
15 Oct, 2019
Consider the following three schedules of transactions T1, T2 and T3. [Notation: In the following NYO represents the action Y (R for read, W for write) performed by transaction N on object O.]
(S1) 2RA 2WA 3RC 2WB 3WA 3WC 1RA 1RB 1WA 1WB
(S2) 3RC 2RA 2WA 2WB 3WA 1RA 1RB 1WA 1WB 3WC
(S3) 2RA 3RC 3WA 2WA 2WB 3WC 1RA 1RB 1WA 1WB
Which of the following statements is TRUE?
(A) S1, S2 and S3 are all conflict equivalent to each other(B) No two of S1, S2 and S3 are conflict equivalent to each other(C) S2 is conflict equivalent to S3, but not to S1(D) S1 is conflict equivalent to S2, but not to S3Answer: (D)Explanation:
All the conflicting pairs like (3WA, 1WA) are in the same order in both S1 and S2.Quiz of this Question
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25805,
"s": 25777,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 25999,
"s": 25805,
"text": "Consider the following three schedules of transactions T1, T2 and T3. [Notation: In the following NYO represents the action Y (R for read, W for write) performed by transaction N on object O.]"
},
{
"code": null,
"e": 26224,
"s": 25999,
"text": "(S1) 2RA 2WA 3RC 2WB 3WA 3WC 1RA 1RB 1WA 1WB\n(S2) 3RC 2RA 2WA 2WB 3WA 1RA 1RB 1WA 1WB 3WC\n(S3) 2RA 3RC 3WA 2WA 2WB 3WC 1RA 1RB 1WA 1WB"
},
{
"code": null,
"e": 26267,
"s": 26224,
"text": "Which of the following statements is TRUE?"
},
{
"code": null,
"e": 26516,
"s": 26267,
"text": "(A) S1, S2 and S3 are all conflict equivalent to each other(B) No two of S1, S2 and S3 are conflict equivalent to each other(C) S2 is conflict equivalent to S3, but not to S1(D) S1 is conflict equivalent to S2, but not to S3Answer: (D)Explanation: "
},
{
"code": null,
"e": 26620,
"s": 26516,
"text": "All the conflicting pairs like (3WA, 1WA) are in the same order in both S1 and S2.Quiz of this Question"
},
{
"code": null,
"e": 26633,
"s": 26620,
"text": "Gate IT 2008"
},
{
"code": null,
"e": 26651,
"s": 26633,
"text": "GATE-Gate IT 2008"
},
{
"code": null,
"e": 26656,
"s": 26651,
"text": "GATE"
},
{
"code": null,
"e": 26754,
"s": 26656,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26788,
"s": 26754,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26822,
"s": 26788,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26855,
"s": 26822,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26891,
"s": 26855,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26925,
"s": 26891,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26961,
"s": 26925,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26995,
"s": 26961,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27029,
"s": 26995,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27063,
"s": 27029,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Anti-aliased Line | Xiaolin Wu's algorithm - GeeksforGeeks
|
07 Jan, 2022
Anti-Aliased Line DrawingBelow is the image showing line drawn with Bresenham’s line algorithm (left) and Xiaolin Wu’s line algorithm (right) which smooths the line. Which one looks better to you ?Anti Aliasing conceptSuppose we want to draw a line from point(1 , 1) to point(8 , 4) with rectangular edges. The ideal line would be the one shown in figure A . Since I want to display it on screen I cannot use that. Line needs to go through a process called Rasterization which would determine color of individual pixels. Several algorithms can be used like Bresenham’s Line Algorithm , Digital Differential Analyzer , Xiaolin Wu’s line algorithm , Gupta-Sproull algorithm . Later two perform anti-aliasing or line smoothing.The result produced by first two algorithm is show in figure B.
There are few problems in Line( figure B ).1. Pixel (4,2) has less coverage than Pixel (3,2), yet they’re both drawn fully black.2. Pixel (2,2) has almost as much coverage as (4,2), and yet it’s drawn fully white.To overcome these drawbacks and produce a much smoother looking line we use Xiaolin Wu’s line algorithm
Xiaolin Wu’s line algorithmConsider the figure shown below which is drawn using Bresenham’s Line Generation Algorithm . Take a segment and its initial coordinate x. By the X in the loop is added 1 towards the end of the segment. At each step, the error is calculated – the distance between the actual y-coordinate at that location and the nearest grid cell. If the error does not exceed half the height of the cell, it is filled. That’s the whole algorithm.We will modify this algorithm so that it can produce an anti-aliased line .Xiaolin Wu’s line algorithm is characterized by the fact that at each step of the calculation is carried out for the two closest to the line of pixels, and they are colored with different intensity, depending on the distance. Current intersection middle pixel intensity gives 100% if the pixel is within 0.9 pixel, the intensity will be 10%. In other words, one hundred percent of the intensity is divided between the pixels which limit vector line on both sides.In the picture the red and green color shows the distance to the two adjacent pixels. To calculate the error, you can use floating point and take the error value of the fractional part.
NOTE:The following implementation uses SDL library to draw pixels on screen . If you are on debian system like ubuntu just run following command to install SDL library.
sudo apt-get install libsdl2-dev
To build use
gcc filename.c -lSDL2
Note:If the projection of the segment on the x-axis is less than the projection on the y-axis, or the beginning and end of the segment are swapped, then the algorithm will not work. To avoid this, you need to check the direction of the vector and its slope, and then swap the coordinates of the line , ultimately to reduce everything to some one or at least two cases.Following algorithm assumes that only integer co-ordinates will be given as inputs since pixel value cannot be floating point.
// C program to implement Xiaolin Wu's line drawing// algorithm.// We must install SDL library using above steps// to run this program#include<SDL2/SDL.h> // SDL stuffSDL_Window* pWindow = 0;SDL_Renderer* pRenderer = 0; // swaps two numbersvoid swap(int* a , int*b){ int temp = *a; *a = *b; *b = temp;} // returns absolute value of numberfloat absolute(float x ){ if (x < 0) return -x; else return x;} //returns integer part of a floating point numberint iPartOfNumber(float x){ return (int)x;} //rounds off a numberint roundNumber(float x){ return iPartOfNumber(x + 0.5) ;} //returns fractional part of a numberfloat fPartOfNumber(float x){ if (x>0) return x - iPartOfNumber(x); else return x - (iPartOfNumber(x)+1); } //returns 1 - fractional part of numberfloat rfPartOfNumber(float x){ return 1 - fPartOfNumber(x);} // draws a pixel on screen of given brightness// 0<=brightness<=1. We can use your own library// to draw on screenvoid drawPixel( int x , int y , float brightness){ int c = 255*brightness; SDL_SetRenderDrawColor(pRenderer, c, c, c, 255); SDL_RenderDrawPoint(pRenderer, x, y);} void drawAALine(int x0 , int y0 , int x1 , int y1){ int steep = absolute(y1 - y0) > absolute(x1 - x0) ; // swap the co-ordinates if slope > 1 or we // draw backwards if (steep) { swap(&x0 , &y0); swap(&x1 , &y1); } if (x0 > x1) { swap(&x0 ,&x1); swap(&y0 ,&y1); } //compute the slope float dx = x1-x0; float dy = y1-y0; float gradient = dy/dx; if (dx == 0.0) gradient = 1; int xpxl1 = x0; int xpxl2 = x1; float intersectY = y0; // main loop if (steep) { int x; for (x = xpxl1 ; x <=xpxl2 ; x++) { // pixel coverage is determined by fractional // part of y co-ordinate drawPixel(iPartOfNumber(intersectY), x, rfPartOfNumber(intersectY)); drawPixel(iPartOfNumber(intersectY)-1, x, fPartOfNumber(intersectY)); intersectY += gradient; } } else { int x; for (x = xpxl1 ; x <=xpxl2 ; x++) { // pixel coverage is determined by fractional // part of y co-ordinate drawPixel(x, iPartOfNumber(intersectY), rfPartOfNumber(intersectY)); drawPixel(x, iPartOfNumber(intersectY)-1, fPartOfNumber(intersectY)); intersectY += gradient; } } } // Driver codeint main(int argc, char* args[]){ SDL_Event event; // initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) { // if succeeded create our window pWindow = SDL_CreateWindow("Anti-Aliased Line ", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); // if the window creation succeeded create our renderer if (pWindow != 0) pRenderer = SDL_CreateRenderer(pWindow, -1, 0); } else return 1; // sdl could not initialize while (1) { if (SDL_PollEvent(&event) && event.type == SDL_QUIT) break; // Sets background color to white SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255); SDL_RenderClear(pRenderer); // draws a black AALine drawAALine(80 , 200 , 550, 150); // show the window SDL_RenderPresent(pRenderer); } // clean up SDL SDL_Quit(); return 0;}
Output:
References:https://courses.engr.illinois.edu/ece390/archive/archive-f2000/mp/mp4/anti.htmlhttps://unionassets.com/blog/algorithm-brezenhema-and-wu-s-line-299https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithmThis article is contributed by Lokesh Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arorakashish0911
computer-graphics
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to Start Learning DSA?
Understanding Time Complexity with Simple Examples
How to write a Pseudo Code?
Introduction to Algorithms
Playfair Cipher with Examples
Recursive Practice Problems with Solutions
Difference between NP hard and NP complete problem
Quick Sort vs Merge Sort
|
[
{
"code": null,
"e": 25825,
"s": 25797,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26613,
"s": 25825,
"text": "Anti-Aliased Line DrawingBelow is the image showing line drawn with Bresenham’s line algorithm (left) and Xiaolin Wu’s line algorithm (right) which smooths the line. Which one looks better to you ?Anti Aliasing conceptSuppose we want to draw a line from point(1 , 1) to point(8 , 4) with rectangular edges. The ideal line would be the one shown in figure A . Since I want to display it on screen I cannot use that. Line needs to go through a process called Rasterization which would determine color of individual pixels. Several algorithms can be used like Bresenham’s Line Algorithm , Digital Differential Analyzer , Xiaolin Wu’s line algorithm , Gupta-Sproull algorithm . Later two perform anti-aliasing or line smoothing.The result produced by first two algorithm is show in figure B."
},
{
"code": null,
"e": 26930,
"s": 26613,
"text": "There are few problems in Line( figure B ).1. Pixel (4,2) has less coverage than Pixel (3,2), yet they’re both drawn fully black.2. Pixel (2,2) has almost as much coverage as (4,2), and yet it’s drawn fully white.To overcome these drawbacks and produce a much smoother looking line we use Xiaolin Wu’s line algorithm"
},
{
"code": null,
"e": 28111,
"s": 26930,
"text": "Xiaolin Wu’s line algorithmConsider the figure shown below which is drawn using Bresenham’s Line Generation Algorithm . Take a segment and its initial coordinate x. By the X in the loop is added 1 towards the end of the segment. At each step, the error is calculated – the distance between the actual y-coordinate at that location and the nearest grid cell. If the error does not exceed half the height of the cell, it is filled. That’s the whole algorithm.We will modify this algorithm so that it can produce an anti-aliased line .Xiaolin Wu’s line algorithm is characterized by the fact that at each step of the calculation is carried out for the two closest to the line of pixels, and they are colored with different intensity, depending on the distance. Current intersection middle pixel intensity gives 100% if the pixel is within 0.9 pixel, the intensity will be 10%. In other words, one hundred percent of the intensity is divided between the pixels which limit vector line on both sides.In the picture the red and green color shows the distance to the two adjacent pixels. To calculate the error, you can use floating point and take the error value of the fractional part."
},
{
"code": null,
"e": 28280,
"s": 28111,
"text": "NOTE:The following implementation uses SDL library to draw pixels on screen . If you are on debian system like ubuntu just run following command to install SDL library."
},
{
"code": null,
"e": 28314,
"s": 28280,
"text": "sudo apt-get install libsdl2-dev\n"
},
{
"code": null,
"e": 28327,
"s": 28314,
"text": "To build use"
},
{
"code": null,
"e": 28350,
"s": 28327,
"text": "gcc filename.c -lSDL2\n"
},
{
"code": null,
"e": 28845,
"s": 28350,
"text": "Note:If the projection of the segment on the x-axis is less than the projection on the y-axis, or the beginning and end of the segment are swapped, then the algorithm will not work. To avoid this, you need to check the direction of the vector and its slope, and then swap the coordinates of the line , ultimately to reduce everything to some one or at least two cases.Following algorithm assumes that only integer co-ordinates will be given as inputs since pixel value cannot be floating point."
},
{
"code": "// C program to implement Xiaolin Wu's line drawing// algorithm.// We must install SDL library using above steps// to run this program#include<SDL2/SDL.h> // SDL stuffSDL_Window* pWindow = 0;SDL_Renderer* pRenderer = 0; // swaps two numbersvoid swap(int* a , int*b){ int temp = *a; *a = *b; *b = temp;} // returns absolute value of numberfloat absolute(float x ){ if (x < 0) return -x; else return x;} //returns integer part of a floating point numberint iPartOfNumber(float x){ return (int)x;} //rounds off a numberint roundNumber(float x){ return iPartOfNumber(x + 0.5) ;} //returns fractional part of a numberfloat fPartOfNumber(float x){ if (x>0) return x - iPartOfNumber(x); else return x - (iPartOfNumber(x)+1); } //returns 1 - fractional part of numberfloat rfPartOfNumber(float x){ return 1 - fPartOfNumber(x);} // draws a pixel on screen of given brightness// 0<=brightness<=1. We can use your own library// to draw on screenvoid drawPixel( int x , int y , float brightness){ int c = 255*brightness; SDL_SetRenderDrawColor(pRenderer, c, c, c, 255); SDL_RenderDrawPoint(pRenderer, x, y);} void drawAALine(int x0 , int y0 , int x1 , int y1){ int steep = absolute(y1 - y0) > absolute(x1 - x0) ; // swap the co-ordinates if slope > 1 or we // draw backwards if (steep) { swap(&x0 , &y0); swap(&x1 , &y1); } if (x0 > x1) { swap(&x0 ,&x1); swap(&y0 ,&y1); } //compute the slope float dx = x1-x0; float dy = y1-y0; float gradient = dy/dx; if (dx == 0.0) gradient = 1; int xpxl1 = x0; int xpxl2 = x1; float intersectY = y0; // main loop if (steep) { int x; for (x = xpxl1 ; x <=xpxl2 ; x++) { // pixel coverage is determined by fractional // part of y co-ordinate drawPixel(iPartOfNumber(intersectY), x, rfPartOfNumber(intersectY)); drawPixel(iPartOfNumber(intersectY)-1, x, fPartOfNumber(intersectY)); intersectY += gradient; } } else { int x; for (x = xpxl1 ; x <=xpxl2 ; x++) { // pixel coverage is determined by fractional // part of y co-ordinate drawPixel(x, iPartOfNumber(intersectY), rfPartOfNumber(intersectY)); drawPixel(x, iPartOfNumber(intersectY)-1, fPartOfNumber(intersectY)); intersectY += gradient; } } } // Driver codeint main(int argc, char* args[]){ SDL_Event event; // initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) { // if succeeded create our window pWindow = SDL_CreateWindow(\"Anti-Aliased Line \", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); // if the window creation succeeded create our renderer if (pWindow != 0) pRenderer = SDL_CreateRenderer(pWindow, -1, 0); } else return 1; // sdl could not initialize while (1) { if (SDL_PollEvent(&event) && event.type == SDL_QUIT) break; // Sets background color to white SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255); SDL_RenderClear(pRenderer); // draws a black AALine drawAALine(80 , 200 , 550, 150); // show the window SDL_RenderPresent(pRenderer); } // clean up SDL SDL_Quit(); return 0;}",
"e": 32472,
"s": 28845,
"text": null
},
{
"code": null,
"e": 32480,
"s": 32472,
"text": "Output:"
},
{
"code": null,
"e": 32995,
"s": 32482,
"text": "References:https://courses.engr.illinois.edu/ece390/archive/archive-f2000/mp/mp4/anti.htmlhttps://unionassets.com/blog/algorithm-brezenhema-and-wu-s-line-299https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithmThis article is contributed by Lokesh Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33120,
"s": 32995,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33137,
"s": 33120,
"text": "arorakashish0911"
},
{
"code": null,
"e": 33155,
"s": 33137,
"text": "computer-graphics"
},
{
"code": null,
"e": 33166,
"s": 33155,
"text": "Algorithms"
},
{
"code": null,
"e": 33177,
"s": 33166,
"text": "Algorithms"
},
{
"code": null,
"e": 33275,
"s": 33177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33324,
"s": 33275,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33349,
"s": 33324,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33376,
"s": 33349,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 33427,
"s": 33376,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 33455,
"s": 33427,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 33482,
"s": 33455,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 33512,
"s": 33482,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 33555,
"s": 33512,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 33606,
"s": 33555,
"text": "Difference between NP hard and NP complete problem"
}
] |
Python program to find all possible pairs with given sum - GeeksforGeeks
|
07 Jun, 2019
Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K.
Examples:
Input : lst =[1, 5, 3, 7, 9]
K = 12
Output : [(5, 7), (3, 9)]
Input : lst = [2, 1, 5, 7, -1, 4]
K = 6
Output : [(2, 4), (1, 5), (7, -1)]
Method #1 : Pythonic Naive
This is a naive approach to the above problem. First, we take an empty list ‘res’ and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in ‘num’, find remaining difference for sum K, and check if the difference exists in the given list or not.
# Python3 program to find all pairs in # a list of integers with given sum def findPairs(lst, K): res = [] while lst: num = lst.pop() diff = K - num if diff in lst: res.append((diff, num)) res.reverse() return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]
Method #2 : Using collections.Counter
This approach follows the same method as discussed above using collections.Counter.
# Python3 program to find all pairs in # a list of integers with given sum from collections import Counter def findPairs(lst, K): res = [] count = Counter(lst) for x in lst: y = K - x if (x != y and count[y]) or (x == y and count[y] > 1): res.append((x, y)) count.subtract((x, y)) return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]
Method #3 : itertools.combinations (Naive method)
This is a naive approach to use itertools.combinations. We use a for loop to traverse through each combination and find out the desired one.
# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): res = [] for var in combinations(lst, 2): if var[0] + var[1] == K: res.append((var[0], var[1])) return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]
Method #4 : itertools.combinations (Efficient method)
# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): return [pair for pair in combinations(lst, 2) if sum(pair) == K] # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]
Python list-programs
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24575,
"s": 24547,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 24698,
"s": 24575,
"text": "Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K."
},
{
"code": null,
"e": 24708,
"s": 24698,
"text": "Examples:"
},
{
"code": null,
"e": 24863,
"s": 24708,
"text": "Input : lst =[1, 5, 3, 7, 9]\n K = 12\nOutput : [(5, 7), (3, 9)]\n\nInput : lst = [2, 1, 5, 7, -1, 4]\n K = 6\nOutput : [(2, 4), (1, 5), (7, -1)]\n"
},
{
"code": null,
"e": 24891,
"s": 24863,
"text": " Method #1 : Pythonic Naive"
},
{
"code": null,
"e": 25200,
"s": 24891,
"text": "This is a naive approach to the above problem. First, we take an empty list ‘res’ and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in ‘num’, find remaining difference for sum K, and check if the difference exists in the given list or not."
},
{
"code": "# Python3 program to find all pairs in # a list of integers with given sum def findPairs(lst, K): res = [] while lst: num = lst.pop() diff = K - num if diff in lst: res.append((diff, num)) res.reverse() return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))",
"e": 25541,
"s": 25200,
"text": null
},
{
"code": null,
"e": 25559,
"s": 25541,
"text": "[(5, 7), (3, 9)]\n"
},
{
"code": null,
"e": 25598,
"s": 25559,
"text": " Method #2 : Using collections.Counter"
},
{
"code": null,
"e": 25682,
"s": 25598,
"text": "This approach follows the same method as discussed above using collections.Counter."
},
{
"code": "# Python3 program to find all pairs in # a list of integers with given sum from collections import Counter def findPairs(lst, K): res = [] count = Counter(lst) for x in lst: y = K - x if (x != y and count[y]) or (x == y and count[y] > 1): res.append((x, y)) count.subtract((x, y)) return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))",
"e": 26111,
"s": 25682,
"text": null
},
{
"code": null,
"e": 26129,
"s": 26111,
"text": "[(5, 7), (3, 9)]\n"
},
{
"code": null,
"e": 26180,
"s": 26129,
"text": " Method #3 : itertools.combinations (Naive method)"
},
{
"code": null,
"e": 26321,
"s": 26180,
"text": "This is a naive approach to use itertools.combinations. We use a for loop to traverse through each combination and find out the desired one."
},
{
"code": "# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): res = [] for var in combinations(lst, 2): if var[0] + var[1] == K: res.append((var[0], var[1])) return res # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))",
"e": 26674,
"s": 26321,
"text": null
},
{
"code": null,
"e": 26692,
"s": 26674,
"text": "[(5, 7), (3, 9)]\n"
},
{
"code": null,
"e": 26747,
"s": 26692,
"text": " Method #4 : itertools.combinations (Efficient method)"
},
{
"code": "# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): return [pair for pair in combinations(lst, 2) if sum(pair) == K] # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))",
"e": 27025,
"s": 26747,
"text": null
},
{
"code": null,
"e": 27043,
"s": 27025,
"text": "[(5, 7), (3, 9)]\n"
},
{
"code": null,
"e": 27064,
"s": 27043,
"text": "Python list-programs"
},
{
"code": null,
"e": 27071,
"s": 27064,
"text": "Python"
},
{
"code": null,
"e": 27087,
"s": 27071,
"text": "Python Programs"
},
{
"code": null,
"e": 27185,
"s": 27087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27194,
"s": 27185,
"text": "Comments"
},
{
"code": null,
"e": 27207,
"s": 27194,
"text": "Old Comments"
},
{
"code": null,
"e": 27225,
"s": 27207,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27260,
"s": 27225,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27282,
"s": 27260,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27314,
"s": 27282,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27344,
"s": 27314,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27387,
"s": 27344,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27409,
"s": 27387,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27448,
"s": 27409,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27494,
"s": 27448,
"text": "Python | Split string into list of characters"
}
] |
How to convert an object to byte array in java?
|
To convert an object to byte array
Make the required object serializable by implementing the Serializable interface.
Create a ByteArrayOutputStream object.
Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step.
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class.
Flush the contents to the stream using the flush() method.
Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Sample implements Serializable {
public void display() {
System.out.println("This is a sample class");
}
}
public class ObjectToByteArray {
public static void main(String args[]) throws Exception {
Sample obj = new Sample();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
byte [] data = bos.toByteArray();
}
}
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "To convert an object to byte array"
},
{
"code": null,
"e": 1179,
"s": 1097,
"text": "Make the required object serializable by implementing the Serializable interface."
},
{
"code": null,
"e": 1218,
"s": 1179,
"text": "Create a ByteArrayOutputStream object."
},
{
"code": null,
"e": 1328,
"s": 1218,
"text": "Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step."
},
{
"code": null,
"e": 1446,
"s": 1328,
"text": "Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class."
},
{
"code": null,
"e": 1505,
"s": 1446,
"text": "Flush the contents to the stream using the flush() method."
},
{
"code": null,
"e": 1612,
"s": 1505,
"text": "Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method."
},
{
"code": null,
"e": 2184,
"s": 1612,
"text": "import java.io.ByteArrayOutputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\nclass Sample implements Serializable {\n public void display() {\n System.out.println(\"This is a sample class\");\n }\n}\npublic class ObjectToByteArray {\n public static void main(String args[]) throws Exception {\n Sample obj = new Sample();\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(bos);\n oos.writeObject(obj);\n oos.flush();\n byte [] data = bos.toByteArray();\n }\n}"
}
] |
Java.util.ArrayList.add() Method in Java - GeeksforGeeks
|
21 Jun, 2020
Below are the add() methods of ArrayList in Java:
boolean add(Object o) : This method appends the specified element to the end of this list.Parameters:
object o: The element to be appended to this list.
Exception: NA// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}Output:Number = 15
Number = 20
Number = 25
void add(int index, Object element) : This method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).Parameters:
index : The index at which the specified element is to be inserted.
element : The element to be inserted.
Exception:
Throws IndexOutOfBoundsException if the specified
index is out of range (index size()).// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}Output:Number = 10
Number = 22
Number = 30
Number = 35
Number = 40
boolean add(Object o) : This method appends the specified element to the end of this list.Parameters:
object o: The element to be appended to this list.
Exception: NA// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}Output:Number = 15
Number = 20
Number = 25
Parameters:
object o: The element to be appended to this list.
Exception: NA
// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}
Output:
Number = 15
Number = 20
Number = 25
void add(int index, Object element) : This method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).Parameters:
index : The index at which the specified element is to be inserted.
element : The element to be inserted.
Exception:
Throws IndexOutOfBoundsException if the specified
index is out of range (index size()).// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}Output:Number = 10
Number = 22
Number = 30
Number = 35
Number = 40
Parameters:
index : The index at which the specified element is to be inserted.
element : The element to be inserted.
Exception:
Throws IndexOutOfBoundsException if the specified
index is out of range (index size()).
// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } }}
Output:
Number = 10
Number = 22
Number = 30
Number = 35
Number = 40
This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Collections in Java
Set in Java
|
[
{
"code": null,
"e": 24125,
"s": 24097,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 24175,
"s": 24125,
"text": "Below are the add() methods of ArrayList in Java:"
},
{
"code": null,
"e": 26206,
"s": 24175,
"text": "boolean add(Object o) : This method appends the specified element to the end of this list.Parameters: \nobject o: The element to be appended to this list.\nException: NA// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}Output:Number = 15\nNumber = 20\nNumber = 25\nvoid add(int index, Object element) : This method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).Parameters:\nindex : The index at which the specified element is to be inserted.\nelement : The element to be inserted.\n\nException:\nThrows IndexOutOfBoundsException if the specified\nindex is out of range (index size()).// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}Output:Number = 10\nNumber = 22\nNumber = 30\nNumber = 35\nNumber = 40\n"
},
{
"code": null,
"e": 26995,
"s": 26206,
"text": "boolean add(Object o) : This method appends the specified element to the end of this list.Parameters: \nobject o: The element to be appended to this list.\nException: NA// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}Output:Number = 15\nNumber = 20\nNumber = 25\n"
},
{
"code": null,
"e": 27076,
"s": 26995,
"text": "Parameters: \nobject o: The element to be appended to this list.\nException: NA"
},
{
"code": "// Java code to illustrate add(Object o)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}",
"e": 27652,
"s": 27076,
"text": null
},
{
"code": null,
"e": 27660,
"s": 27652,
"text": "Output:"
},
{
"code": null,
"e": 27697,
"s": 27660,
"text": "Number = 15\nNumber = 20\nNumber = 25\n"
},
{
"code": null,
"e": 28940,
"s": 27697,
"text": "void add(int index, Object element) : This method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).Parameters:\nindex : The index at which the specified element is to be inserted.\nelement : The element to be inserted.\n\nException:\nThrows IndexOutOfBoundsException if the specified\nindex is out of range (index size()).// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}Output:Number = 10\nNumber = 22\nNumber = 30\nNumber = 35\nNumber = 40\n"
},
{
"code": null,
"e": 29159,
"s": 28940,
"text": "Parameters:\nindex : The index at which the specified element is to be inserted.\nelement : The element to be inserted.\n\nException:\nThrows IndexOutOfBoundsException if the specified\nindex is out of range (index size())."
},
{
"code": "// Java code to illustrate// void add(int index, Object element)import java.io.*;import java.util.ArrayList; public class ArrayListDemo {public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(10); arrlist.add(22); arrlist.add(30); arrlist.add(40); // adding element 35 at fourth position arrlist.add(3, 35); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println(\"Number = \" + number); } }}",
"e": 29865,
"s": 29159,
"text": null
},
{
"code": null,
"e": 29873,
"s": 29865,
"text": "Output:"
},
{
"code": null,
"e": 29934,
"s": 29873,
"text": "Number = 10\nNumber = 22\nNumber = 30\nNumber = 35\nNumber = 40\n"
},
{
"code": null,
"e": 30237,
"s": 29934,
"text": "This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30362,
"s": 30237,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30382,
"s": 30362,
"text": "Java - util package"
},
{
"code": null,
"e": 30397,
"s": 30382,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 30414,
"s": 30397,
"text": "Java-Collections"
},
{
"code": null,
"e": 30429,
"s": 30414,
"text": "Java-Functions"
},
{
"code": null,
"e": 30434,
"s": 30429,
"text": "Java"
},
{
"code": null,
"e": 30439,
"s": 30434,
"text": "Java"
},
{
"code": null,
"e": 30456,
"s": 30439,
"text": "Java-Collections"
},
{
"code": null,
"e": 30554,
"s": 30456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30563,
"s": 30554,
"text": "Comments"
},
{
"code": null,
"e": 30576,
"s": 30563,
"text": "Old Comments"
},
{
"code": null,
"e": 30627,
"s": 30576,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30657,
"s": 30627,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30688,
"s": 30657,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30707,
"s": 30688,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30739,
"s": 30707,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30771,
"s": 30739,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30791,
"s": 30771,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30815,
"s": 30791,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 30835,
"s": 30815,
"text": "Collections in Java"
}
] |
OR Gate using Perceptron Network - GeeksforGeeks
|
12 Jun, 2019
Perceptron networks come under single-layer feed-forward networks and are also called simple perceptrons. The perceptron network consists of three units, namely, sensory unit (input unit), associator unit (hidden unit), response unit (output unit). The sensory units are connected to associator units with fixed weights having values 1, 0 or -1, which are assigned at random.The problem is to implement or gate using a perceptron network using c++ code.
#include<iostream>using namespace std;int main(){ //Array for Binary Input int arr[4][2] = { {0,0}, {0,1}, {1,0}, {1,1} }; //Target array for Binary Input int t[4] = {0,1,1,1}; // Considering learning rate=1 int alp = 1; // yi = input // yo = output int w1 = 0, w2 = 0, b = 0, count = 0, i, yi, yo; int dw1,dw2,db; while(1) { cout<<"x1"<<" "<<"x2"<<" "<<"b"<<" "<<"yi"<<" "<< "yo"<<" "<<"t"<<" "<<"dw1"<<" "<<"dw2"<<" "<<"db"<< " "<<"w1"<<" "<<"w2"<<" "<<"b"<<endl; for(i = 0; i < 4; i++) { // Calaulating Input yi = arr[i][0] * w1 + arr[i][1] * w2 + b; if(yi >= 0) { yo = 1; } else { yo = 0; } if(t[i] == yo) { count++; dw1 = 0; dw2 = 0; db = 0; } // Calaulating Change in Weight else { dw1 = alp*(t[i] - yo) * arr[i][0]; dw2 = alp*(t[i] - yo) * arr[i][1]; db = alp*(t[i] - yo); } w1 = w1 + dw1; w2 = w2 + dw2; b = b + db; cout<<arr[i][0]<<" "<<arr[i][1]<<" "<<1<<" "<<yi<<" "<<yo <<" "<<t[i]<<" "<<dw1<<" "<<dw2<<" "<<db<<" "<<w1<<" "<<w2 <<" "<<b<<endl; } cout<<endl; if(count == 4) { return 0; } else { count = 0; } }}
Output :
x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1 0 0 0 -1 0 0 -1
0 1 1 -1 0 1 0 1 1 0 1 0
1 0 1 0 1 1 0 0 0 0 1 0
1 1 1 1 1 1 0 0 0 0 1 0
x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1 0 0 0 -1 0 1 -1
0 1 1 0 1 1 0 0 0 0 1 -1
1 0 1 -1 0 1 1 0 1 1 1 0
1 1 1 2 1 1 0 0 0 1 1 0
x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1 0 0 0 -1 1 1 -1
0 1 1 0 1 1 0 0 0 1 1 -1
1 0 1 0 1 1 0 0 0 1 1 -1
1 1 1 1 1 1 0 0 0 1 1 -1
x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 -1 0 0 0 0 0 1 1 -1
0 1 1 0 1 1 0 0 0 1 1 -1
1 0 1 0 1 1 0 0 0 1 1 -1
1 1 1 1 1 1 0 0 0 1 1 -1
C++
Machine Learning
Machine Learning
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Naive Bayes Classifiers
Linear Regression (Python Implementation)
Removing stop words with NLTK in Python
Agents in Artificial Intelligence
ML | Linear Regression
|
[
{
"code": null,
"e": 25161,
"s": 25133,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 25615,
"s": 25161,
"text": "Perceptron networks come under single-layer feed-forward networks and are also called simple perceptrons. The perceptron network consists of three units, namely, sensory unit (input unit), associator unit (hidden unit), response unit (output unit). The sensory units are connected to associator units with fixed weights having values 1, 0 or -1, which are assigned at random.The problem is to implement or gate using a perceptron network using c++ code."
},
{
"code": "#include<iostream>using namespace std;int main(){ //Array for Binary Input int arr[4][2] = { {0,0}, {0,1}, {1,0}, {1,1} }; //Target array for Binary Input int t[4] = {0,1,1,1}; // Considering learning rate=1 int alp = 1; // yi = input // yo = output int w1 = 0, w2 = 0, b = 0, count = 0, i, yi, yo; int dw1,dw2,db; while(1) { cout<<\"x1\"<<\" \"<<\"x2\"<<\" \"<<\"b\"<<\" \"<<\"yi\"<<\" \"<< \"yo\"<<\" \"<<\"t\"<<\" \"<<\"dw1\"<<\" \"<<\"dw2\"<<\" \"<<\"db\"<< \" \"<<\"w1\"<<\" \"<<\"w2\"<<\" \"<<\"b\"<<endl; for(i = 0; i < 4; i++) { // Calaulating Input yi = arr[i][0] * w1 + arr[i][1] * w2 + b; if(yi >= 0) { yo = 1; } else { yo = 0; } if(t[i] == yo) { count++; dw1 = 0; dw2 = 0; db = 0; } // Calaulating Change in Weight else { dw1 = alp*(t[i] - yo) * arr[i][0]; dw2 = alp*(t[i] - yo) * arr[i][1]; db = alp*(t[i] - yo); } w1 = w1 + dw1; w2 = w2 + dw2; b = b + db; cout<<arr[i][0]<<\" \"<<arr[i][1]<<\" \"<<1<<\" \"<<yi<<\" \"<<yo <<\" \"<<t[i]<<\" \"<<dw1<<\" \"<<dw2<<\" \"<<db<<\" \"<<w1<<\" \"<<w2 <<\" \"<<b<<endl; } cout<<endl; if(count == 4) { return 0; } else { count = 0; } }}",
"e": 27210,
"s": 25615,
"text": null
},
{
"code": null,
"e": 27219,
"s": 27210,
"text": "Output :"
},
{
"code": null,
"e": 27829,
"s": 27219,
"text": "x1 x2 b yi yo t dw1 dw2 db w1 w2 b\n0 0 1 0 1 0 0 0 -1 0 0 -1\n0 1 1 -1 0 1 0 1 1 0 1 0\n1 0 1 0 1 1 0 0 0 0 1 0\n1 1 1 1 1 1 0 0 0 0 1 0\n\nx1 x2 b yi yo t dw1 dw2 db w1 w2 b\n0 0 1 0 1 0 0 0 -1 0 1 -1\n0 1 1 0 1 1 0 0 0 0 1 -1\n1 0 1 -1 0 1 1 0 1 1 1 0\n1 1 1 2 1 1 0 0 0 1 1 0\n\nx1 x2 b yi yo t dw1 dw2 db w1 w2 b\n0 0 1 0 1 0 0 0 -1 1 1 -1\n0 1 1 0 1 1 0 0 0 1 1 -1\n1 0 1 0 1 1 0 0 0 1 1 -1\n1 1 1 1 1 1 0 0 0 1 1 -1\n\nx1 x2 b yi yo t dw1 dw2 db w1 w2 b\n0 0 1 -1 0 0 0 0 0 1 1 -1\n0 1 1 0 1 1 0 0 0 1 1 -1\n1 0 1 0 1 1 0 0 0 1 1 -1\n1 1 1 1 1 1 0 0 0 1 1 -1\n\n"
},
{
"code": null,
"e": 27833,
"s": 27829,
"text": "C++"
},
{
"code": null,
"e": 27850,
"s": 27833,
"text": "Machine Learning"
},
{
"code": null,
"e": 27867,
"s": 27850,
"text": "Machine Learning"
},
{
"code": null,
"e": 27871,
"s": 27867,
"text": "CPP"
},
{
"code": null,
"e": 27969,
"s": 27871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27978,
"s": 27969,
"text": "Comments"
},
{
"code": null,
"e": 27991,
"s": 27978,
"text": "Old Comments"
},
{
"code": null,
"e": 28034,
"s": 27991,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28053,
"s": 28034,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28077,
"s": 28053,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 28097,
"s": 28077,
"text": "Constructors in C++"
},
{
"code": null,
"e": 28124,
"s": 28097,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28148,
"s": 28124,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 28190,
"s": 28148,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 28230,
"s": 28190,
"text": "Removing stop words with NLTK in Python"
},
{
"code": null,
"e": 28264,
"s": 28230,
"text": "Agents in Artificial Intelligence"
}
] |
Fraction module in Python
|
In Python the Fraction module supports rational number arithmetic. Using this module, we can create fractions from integers, floats, decimal and from some other numeric values and strings.
There is a concept of Fraction Instance. It is formed by a pair of integers as numerator and denominator.
The class fractions.Fractionis used to create a Fraction object. It takes Numerator and Denominator. The default value of the numerator is 0 and denominator is 1. It raises ZeroDivisionError when the denominator is 0.
At first we will see how the class can create fractions using Numerator and Denominator.
Live Demo
from fractions import Fraction as frac
print(frac(45, 54))
print(frac(12, 47))
print(frac(0, 15))
5/6
12/47
0
We can provide some floating point numbers as an argument of the Fraction object. If we provide the exact floating point value, it will try to convert it to numerator and denominator value of integer type. In this case, it tries to reach to the approximate value. If the floating point number is provided as a string, it will try to find the exact value as Fraction. From the following examples, you can see the differences.
Live Demo
from fractions import Fraction as frac
print(frac(33.33))
print(frac('33.33'))
2345390243441541/70368744177664
3333/100
Let us see, some other examples on string type arguments to the Fraction object. It also supports the sign of the numbers. It supports + or - sign.
Live Demo
from fractions import Fraction as frac
print(frac('5/6'))
print(frac('-25.12'))
print(frac('96.251 \t\n'))
print(frac('3.14159265359'))
5/6
-628/25
96251/1000
314159265359/100000000000
As we have seen, sometimes the denominators are very large in the Fraction object. So we can limit the denominator lengths. The default length is 1000000. It helps to perform rational approximation for floating point data. To limit the denominator, there is a function called limit_denominator().
Sometimes we want only the numerators or the denominators without the whole fraction object. So this method has numerator and denominator keyword to get them.
Live Demo
from fractions import Fraction as frac
print(frac('3.14159265359'))
print(frac('3.14159265359').limit_denominator(1000))
print(frac('3.14159265359').limit_denominator(100))
print(frac('3.14159265359').limit_denominator(10))
print(frac('36.25'))
print(frac('36.25').numerator)
print(frac('36.25').denominator)
314159265359/100000000000
355/113
311/99
22/7
145/4
145
4
Fractions can also support the mathematical operations, like addition, subtraction, multiplication, division, power etc.
Live Demo
from fractions import Fraction as frac
print('Add: ' + str(frac('5/4') + frac('9/8')))
print('Subtract: ' + str(frac('15/20') - frac('2/8')))
print('Multiply: ' + str(frac('2/3') * frac('5/7')))
print('Divide: ' + str(frac('80/125') / frac('12/45')))
print('Power: ' + str(frac('5/6') ** 3))
Add: 19/8
Subtract: 1/2
Multiply: 10/21
Divide: 12/5
Power: 125/216
The square root, floor, ceiling and some other operations are also supported by this object.
Live Demo
from fractions import Fraction as frac
import math
print('Square Root: ' + str(math.sqrt(frac(36, 64))))
print('Square Root: ' + str(frac(math.sqrt(frac(36, 64)))))
print('Floor Value: ' + str(math.floor(frac('22/7'))))
print('Ceiling Value: ' + str(math.ceil(frac('22/7'))))
Square Root: 0.75
Square Root: 3/4
Floor Value: 3
Ceiling Value: 4
|
[
{
"code": null,
"e": 1251,
"s": 1062,
"text": "In Python the Fraction module supports rational number arithmetic. Using this module, we can create fractions from integers, floats, decimal and from some other numeric values and strings."
},
{
"code": null,
"e": 1357,
"s": 1251,
"text": "There is a concept of Fraction Instance. It is formed by a pair of integers as numerator and denominator."
},
{
"code": null,
"e": 1575,
"s": 1357,
"text": "The class fractions.Fractionis used to create a Fraction object. It takes Numerator and Denominator. The default value of the numerator is 0 and denominator is 1. It raises ZeroDivisionError when the denominator is 0."
},
{
"code": null,
"e": 1664,
"s": 1575,
"text": "At first we will see how the class can create fractions using Numerator and Denominator."
},
{
"code": null,
"e": 1675,
"s": 1664,
"text": " Live Demo"
},
{
"code": null,
"e": 1773,
"s": 1675,
"text": "from fractions import Fraction as frac\nprint(frac(45, 54))\nprint(frac(12, 47))\nprint(frac(0, 15))"
},
{
"code": null,
"e": 1786,
"s": 1773,
"text": "5/6\n12/47\n0\n"
},
{
"code": null,
"e": 2211,
"s": 1786,
"text": "We can provide some floating point numbers as an argument of the Fraction object. If we provide the exact floating point value, it will try to convert it to numerator and denominator value of integer type. In this case, it tries to reach to the approximate value. If the floating point number is provided as a string, it will try to find the exact value as Fraction. From the following examples, you can see the differences."
},
{
"code": null,
"e": 2222,
"s": 2211,
"text": " Live Demo"
},
{
"code": null,
"e": 2301,
"s": 2222,
"text": "from fractions import Fraction as frac\nprint(frac(33.33))\nprint(frac('33.33'))"
},
{
"code": null,
"e": 2343,
"s": 2301,
"text": "2345390243441541/70368744177664\n3333/100\n"
},
{
"code": null,
"e": 2491,
"s": 2343,
"text": "Let us see, some other examples on string type arguments to the Fraction object. It also supports the sign of the numbers. It supports + or - sign."
},
{
"code": null,
"e": 2502,
"s": 2491,
"text": " Live Demo"
},
{
"code": null,
"e": 2638,
"s": 2502,
"text": "from fractions import Fraction as frac\nprint(frac('5/6'))\nprint(frac('-25.12'))\nprint(frac('96.251 \\t\\n'))\nprint(frac('3.14159265359'))"
},
{
"code": null,
"e": 2688,
"s": 2638,
"text": "5/6\n-628/25\n96251/1000\n314159265359/100000000000\n"
},
{
"code": null,
"e": 2985,
"s": 2688,
"text": "As we have seen, sometimes the denominators are very large in the Fraction object. So we can limit the denominator lengths. The default length is 1000000. It helps to perform rational approximation for floating point data. To limit the denominator, there is a function called limit_denominator()."
},
{
"code": null,
"e": 3144,
"s": 2985,
"text": "Sometimes we want only the numerators or the denominators without the whole fraction object. So this method has numerator and denominator keyword to get them."
},
{
"code": null,
"e": 3155,
"s": 3144,
"text": " Live Demo"
},
{
"code": null,
"e": 3464,
"s": 3155,
"text": "from fractions import Fraction as frac\nprint(frac('3.14159265359'))\nprint(frac('3.14159265359').limit_denominator(1000))\nprint(frac('3.14159265359').limit_denominator(100))\nprint(frac('3.14159265359').limit_denominator(10))\nprint(frac('36.25'))\nprint(frac('36.25').numerator)\nprint(frac('36.25').denominator)"
},
{
"code": null,
"e": 3523,
"s": 3464,
"text": "314159265359/100000000000\n355/113\n311/99\n22/7\n145/4\n145\n4\n"
},
{
"code": null,
"e": 3644,
"s": 3523,
"text": "Fractions can also support the mathematical operations, like addition, subtraction, multiplication, division, power etc."
},
{
"code": null,
"e": 3655,
"s": 3644,
"text": " Live Demo"
},
{
"code": null,
"e": 3947,
"s": 3655,
"text": "from fractions import Fraction as frac\nprint('Add: ' + str(frac('5/4') + frac('9/8')))\nprint('Subtract: ' + str(frac('15/20') - frac('2/8')))\nprint('Multiply: ' + str(frac('2/3') * frac('5/7')))\nprint('Divide: ' + str(frac('80/125') / frac('12/45')))\nprint('Power: ' + str(frac('5/6') ** 3))"
},
{
"code": null,
"e": 4016,
"s": 3947,
"text": "Add: 19/8\nSubtract: 1/2\nMultiply: 10/21\nDivide: 12/5\nPower: 125/216\n"
},
{
"code": null,
"e": 4109,
"s": 4016,
"text": "The square root, floor, ceiling and some other operations are also supported by this object."
},
{
"code": null,
"e": 4120,
"s": 4109,
"text": " Live Demo"
},
{
"code": null,
"e": 4396,
"s": 4120,
"text": "from fractions import Fraction as frac\nimport math\nprint('Square Root: ' + str(math.sqrt(frac(36, 64))))\nprint('Square Root: ' + str(frac(math.sqrt(frac(36, 64)))))\nprint('Floor Value: ' + str(math.floor(frac('22/7'))))\nprint('Ceiling Value: ' + str(math.ceil(frac('22/7'))))"
},
{
"code": null,
"e": 4464,
"s": 4396,
"text": "Square Root: 0.75\nSquare Root: 3/4\nFloor Value: 3\nCeiling Value: 4\n"
}
] |
Defining Functions in Python. Defining Python Functions | by Sadrach Pierre, Ph.D. | Towards Data Science
|
In computer science, functions provide a set of instructions for performing a specific task. Functions are an important part of software programs as they are at the heart of most applications we use today. In this post, we will discuss how to define different types of functions in python.
Let’s get started!
To starts, let’s define a simple function. We use the ‘def’ keyword to define functions in python. Let’s define a function that prints a quote from Thomas Pynchon’s, Gravity’s Rainbow :
def print_quote(): print("If they can get you asking the wrong questions, they don't have to worry about the answers.")
Now, if we call our function it should display our quote:
print_quote()
If we’d like, we can have the function return the string using the return keyword:
def print_quote(): return "If they can get you asking the wrong questions, they don't have to worry about the answers."
We can then store the function return value in a variable and print the stored values:
quote = print_quote()print(quote)
An even cleaner way to write our function would be to store the string in a variable within the function scope and return the variable:
def print_quote(): quote = "If they can get you asking the wrong questions, they don't have to worry about the answers." return quote
Let’s store the function return value in a variable and print the stored values:
my_quote = print_quote()print(my_quote)
Now, let’s discuss how to define functions with input. Let’s define a function that takes a string as input and returns the length of the string.
def quote_length(input_quote): return len(input_quote)
We can define a few variables storing quotes of different lengths. Let’s use a few quotes from William Gaddis’s The Recognitions:
quote_one = "The most difficult challenge to the ideal is its transformation into reality, and few ideals survive."quote_two = "We've had the goddamn Age of Faith, we've had the goddamn Age of Reason. This is the Age of Publicity."quote_three = "Reading Proust isn't just reading a book, it's an experience and you can't reject an experience."
Let’s call our function with each of these quotes:
quote_length(quote_one)quote_length(quote_two)quote_length(quote_three)
We can also perform various operations on our input string. Let’s define a function that combines our quotes into a single string. We can use the ‘join()’ method to combine a list of strings into a single string:
quote_list = [quote_one, quote_two, quote_three]def combine_quote(string_list): return ''.join(string_list)
If we print our function with our ‘quote_list’ as input we get the following result:
print(combine_quote(quote_list))
We can also have multiple input values in our function. Let’s have our function take an input string that specifies the author name. In the scope of the function, let’s print the author’s name:
def combine_quote(string_list, author_name): print("Author: ", author_name) return ''.join(string_list)
Now, let’s call our function and print its return value:
print(combine_quote(quote_list, 'William Gaddis'))
It is also very straightforward to return multiple values in a function. Let’s define a function that takes a quote, a book title, an author name and the number of pages in the book. In our function we will create a data frame that contains columns for the quote, book titles, authors, and number of pages. The function will return the data frame and its length.
To start, let’s define a list of quotes, corresponding authors, book titles, and number of pages:
quote_list = ["If they can get you asking the wrong questions, they don't have to worry about the answers.", "The most difficult challenge to the ideal is its transformation into reality, and few ideals survive.", "The truth will set you free. But not until it is finished with you."]book_list = ['Gravity's Rainbow', 'The Recognitions', 'Infinite Jest'] author_list = ["Thomas Pynchon", "William Gaddis", "David Foster Wallace"]number_of_pages = [776, 976, 1088]
Next let’s store each list in a dictionary with its appropriate key:
df = {'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages}
Now, let’s pass the dictionary into the data frame constructor from the Pandas library:
import pandas as pd df = pd.DataFrame({'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages})
Let’s also relax the limit on the number of display columns using Pandas, and print the result:
pd.set_option('display.max_columns', None)print(df)
Now let’s wrap this code in a function. Let’s name our function ‘get_dataframe’. Our function will return the data frame and its length:
def get_dataframe(quote, book, author, pages): df = pd.DataFrame({'quotes':quote, 'books':book, 'authors':author, 'pages':pages}) return df, len(df)
Now let’s call our function with our lists and store the return values in two separate variables:
df, length = get_dataframe(quote_list, book_list, author_list, number_of_pages)print(df)print("Data Frame Length: ", length)
We have freedom to choose which and the number of values we return in our function. Let’s also return the pandas series corresponding to the ‘quotes’ and ‘books’ columns:
def get_dataframe(quote, book, author, pages): df = pd.DataFrame({'quotes':quote, 'books':book, 'authors':author, 'pages':pages}) return df, len(df), df['books'], df['quotes']
Now, let’s call our function again:
df, length, books, quotes = get_dataframe(quote_list, book_list, author_list, number_of_pages)
And we can print books:
print(books)
And quotes:
print(quotes)
I’ll stop here but feel free to play around with the code yourself.
To summarize, in this post we discussed how to define functions in python. First, we showed how to define a simple function that prints a string. corresponding to a book quote. Next, we discussed how to define a function that takes input values, manipulates the input, and return a value. Finally, we showed how to define a function that returns multiple values. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 462,
"s": 172,
"text": "In computer science, functions provide a set of instructions for performing a specific task. Functions are an important part of software programs as they are at the heart of most applications we use today. In this post, we will discuss how to define different types of functions in python."
},
{
"code": null,
"e": 481,
"s": 462,
"text": "Let’s get started!"
},
{
"code": null,
"e": 667,
"s": 481,
"text": "To starts, let’s define a simple function. We use the ‘def’ keyword to define functions in python. Let’s define a function that prints a quote from Thomas Pynchon’s, Gravity’s Rainbow :"
},
{
"code": null,
"e": 790,
"s": 667,
"text": "def print_quote(): print(\"If they can get you asking the wrong questions, they don't have to worry about the answers.\")"
},
{
"code": null,
"e": 848,
"s": 790,
"text": "Now, if we call our function it should display our quote:"
},
{
"code": null,
"e": 862,
"s": 848,
"text": "print_quote()"
},
{
"code": null,
"e": 945,
"s": 862,
"text": "If we’d like, we can have the function return the string using the return keyword:"
},
{
"code": null,
"e": 1068,
"s": 945,
"text": "def print_quote(): return \"If they can get you asking the wrong questions, they don't have to worry about the answers.\""
},
{
"code": null,
"e": 1155,
"s": 1068,
"text": "We can then store the function return value in a variable and print the stored values:"
},
{
"code": null,
"e": 1189,
"s": 1155,
"text": "quote = print_quote()print(quote)"
},
{
"code": null,
"e": 1325,
"s": 1189,
"text": "An even cleaner way to write our function would be to store the string in a variable within the function scope and return the variable:"
},
{
"code": null,
"e": 1466,
"s": 1325,
"text": "def print_quote(): quote = \"If they can get you asking the wrong questions, they don't have to worry about the answers.\" return quote"
},
{
"code": null,
"e": 1547,
"s": 1466,
"text": "Let’s store the function return value in a variable and print the stored values:"
},
{
"code": null,
"e": 1587,
"s": 1547,
"text": "my_quote = print_quote()print(my_quote)"
},
{
"code": null,
"e": 1733,
"s": 1587,
"text": "Now, let’s discuss how to define functions with input. Let’s define a function that takes a string as input and returns the length of the string."
},
{
"code": null,
"e": 1791,
"s": 1733,
"text": "def quote_length(input_quote): return len(input_quote)"
},
{
"code": null,
"e": 1921,
"s": 1791,
"text": "We can define a few variables storing quotes of different lengths. Let’s use a few quotes from William Gaddis’s The Recognitions:"
},
{
"code": null,
"e": 2265,
"s": 1921,
"text": "quote_one = \"The most difficult challenge to the ideal is its transformation into reality, and few ideals survive.\"quote_two = \"We've had the goddamn Age of Faith, we've had the goddamn Age of Reason. This is the Age of Publicity.\"quote_three = \"Reading Proust isn't just reading a book, it's an experience and you can't reject an experience.\""
},
{
"code": null,
"e": 2316,
"s": 2265,
"text": "Let’s call our function with each of these quotes:"
},
{
"code": null,
"e": 2388,
"s": 2316,
"text": "quote_length(quote_one)quote_length(quote_two)quote_length(quote_three)"
},
{
"code": null,
"e": 2601,
"s": 2388,
"text": "We can also perform various operations on our input string. Let’s define a function that combines our quotes into a single string. We can use the ‘join()’ method to combine a list of strings into a single string:"
},
{
"code": null,
"e": 2712,
"s": 2601,
"text": "quote_list = [quote_one, quote_two, quote_three]def combine_quote(string_list): return ''.join(string_list)"
},
{
"code": null,
"e": 2797,
"s": 2712,
"text": "If we print our function with our ‘quote_list’ as input we get the following result:"
},
{
"code": null,
"e": 2830,
"s": 2797,
"text": "print(combine_quote(quote_list))"
},
{
"code": null,
"e": 3024,
"s": 2830,
"text": "We can also have multiple input values in our function. Let’s have our function take an input string that specifies the author name. In the scope of the function, let’s print the author’s name:"
},
{
"code": null,
"e": 3132,
"s": 3024,
"text": "def combine_quote(string_list, author_name): print(\"Author: \", author_name) return ''.join(string_list)"
},
{
"code": null,
"e": 3189,
"s": 3132,
"text": "Now, let’s call our function and print its return value:"
},
{
"code": null,
"e": 3240,
"s": 3189,
"text": "print(combine_quote(quote_list, 'William Gaddis'))"
},
{
"code": null,
"e": 3603,
"s": 3240,
"text": "It is also very straightforward to return multiple values in a function. Let’s define a function that takes a quote, a book title, an author name and the number of pages in the book. In our function we will create a data frame that contains columns for the quote, book titles, authors, and number of pages. The function will return the data frame and its length."
},
{
"code": null,
"e": 3701,
"s": 3603,
"text": "To start, let’s define a list of quotes, corresponding authors, book titles, and number of pages:"
},
{
"code": null,
"e": 4165,
"s": 3701,
"text": "quote_list = [\"If they can get you asking the wrong questions, they don't have to worry about the answers.\", \"The most difficult challenge to the ideal is its transformation into reality, and few ideals survive.\", \"The truth will set you free. But not until it is finished with you.\"]book_list = ['Gravity's Rainbow', 'The Recognitions', 'Infinite Jest'] author_list = [\"Thomas Pynchon\", \"William Gaddis\", \"David Foster Wallace\"]number_of_pages = [776, 976, 1088]"
},
{
"code": null,
"e": 4234,
"s": 4165,
"text": "Next let’s store each list in a dictionary with its appropriate key:"
},
{
"code": null,
"e": 4350,
"s": 4234,
"text": "df = {'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages}"
},
{
"code": null,
"e": 4438,
"s": 4350,
"text": "Now, let’s pass the dictionary into the data frame constructor from the Pandas library:"
},
{
"code": null,
"e": 4588,
"s": 4438,
"text": "import pandas as pd df = pd.DataFrame({'quote_list':quote_list, 'book_list':book_list, 'author_list':author_list, 'number_of_pages':number_of_pages})"
},
{
"code": null,
"e": 4684,
"s": 4588,
"text": "Let’s also relax the limit on the number of display columns using Pandas, and print the result:"
},
{
"code": null,
"e": 4736,
"s": 4684,
"text": "pd.set_option('display.max_columns', None)print(df)"
},
{
"code": null,
"e": 4873,
"s": 4736,
"text": "Now let’s wrap this code in a function. Let’s name our function ‘get_dataframe’. Our function will return the data frame and its length:"
},
{
"code": null,
"e": 5030,
"s": 4873,
"text": "def get_dataframe(quote, book, author, pages): df = pd.DataFrame({'quotes':quote, 'books':book, 'authors':author, 'pages':pages}) return df, len(df)"
},
{
"code": null,
"e": 5128,
"s": 5030,
"text": "Now let’s call our function with our lists and store the return values in two separate variables:"
},
{
"code": null,
"e": 5253,
"s": 5128,
"text": "df, length = get_dataframe(quote_list, book_list, author_list, number_of_pages)print(df)print(\"Data Frame Length: \", length)"
},
{
"code": null,
"e": 5424,
"s": 5253,
"text": "We have freedom to choose which and the number of values we return in our function. Let’s also return the pandas series corresponding to the ‘quotes’ and ‘books’ columns:"
},
{
"code": null,
"e": 5608,
"s": 5424,
"text": "def get_dataframe(quote, book, author, pages): df = pd.DataFrame({'quotes':quote, 'books':book, 'authors':author, 'pages':pages}) return df, len(df), df['books'], df['quotes']"
},
{
"code": null,
"e": 5644,
"s": 5608,
"text": "Now, let’s call our function again:"
},
{
"code": null,
"e": 5739,
"s": 5644,
"text": "df, length, books, quotes = get_dataframe(quote_list, book_list, author_list, number_of_pages)"
},
{
"code": null,
"e": 5763,
"s": 5739,
"text": "And we can print books:"
},
{
"code": null,
"e": 5776,
"s": 5763,
"text": "print(books)"
},
{
"code": null,
"e": 5788,
"s": 5776,
"text": "And quotes:"
},
{
"code": null,
"e": 5802,
"s": 5788,
"text": "print(quotes)"
},
{
"code": null,
"e": 5870,
"s": 5802,
"text": "I’ll stop here but feel free to play around with the code yourself."
}
] |
Density Plots with Pandas in Python - GeeksforGeeks
|
26 Nov, 2020
Density Plot is a type of data visualization tool. It is a variation of the histogram that uses ‘kernel smoothing’ while plotting the values. It is a continuous and smooth version of a histogram inferred from a data.
Density plots uses Kernel Density Estimation (so they are also known as Kernel density estimation plots or KDE) which is a probability density function. The region of plot with a higher peak is the region with maximum data points residing between those values.
Density plots can be made using pandas, seaborn, etc. In this article, we will generate density plots using Pandas. We will be using two datasets of the Seaborn Library namely – ‘car_crashes’ and ‘tips’.
Syntax: pandas.DataFrame.plot.density | pandas.DataFrame.plot.kde
where pandas -> the dataset of the type ‘pandas dataframe’
Dataframe -> the column for which the density plot is to be drawn
plot -> keyword directing to draw a plot/graph for the given column
density -> for plotting a density graph
kde -> to plot a density graph using the Kernel Density Estimation function
Example 1: Given the dataset ‘car_crashes’, let’s find out using the density plot which is the most common speed due to which most of the car crashes happened.
Python3
# importing the librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # loading the dataset# from seaborn librarydata = sns.load_dataset('car_crashes') # viewing the datasetprint(data.head(4))
Output:
Plotting the graph:
Python3
# plotting the density plot # for 'speeding' attribute# using plot.density()data.speeding.plot.density(color='green')plt.title('Density plot for Speeding')plt.show()
Output:
Using a density plot, we can figure out that the speed between 4-5 (kmph) was the most common for crash crashes in the dataset because of it being high density (high peak) region.
Example 2: For another dataset ‘tips’, let’s calculate what was the most common tip given by a customer.
Python3
# loading the dataset# from seaborn librarydata = sns.load_dataset('tips') # viewing the datasetprint(data.head(4))
Output:
‘tips’ dataset
Plotting the graph:
Python3
# density plot for 'tip'data.tip.plot.density(color='green')plt.title('Density Plot for Tip')plt.show()
Through the above density plot, we can infer that the most common tip that was given was in the range of 2.5 – 3. The highest peak/density (as represented on the y-axis) was found to be at the tip value of 2.5 – 3.
Plotting the above plot using the plot.kde()
KDE or the Kernel Density Estimation uses Gaussian Kernels to estimate the Probability Density Function of a random variable. Below is the implementation of plotting the density plot using kde() for the dataset ‘tips’.
Python3
# for 'tip' attribute# using plot.kde()data.tip.plot.kde(color='green')plt.title('KDE-Density plot for Tip')plt.show()
Using this we can infer that there is no major difference between plot.density() and plot.kde() and can be therefore used interchangeably.
Density plots have an advantage over Histograms because they determine the Shape of the distribution more efficiently than histograms. They do not have to depend on the number of bins used unlike in histograms.
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23895,
"s": 23867,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24112,
"s": 23895,
"text": "Density Plot is a type of data visualization tool. It is a variation of the histogram that uses ‘kernel smoothing’ while plotting the values. It is a continuous and smooth version of a histogram inferred from a data."
},
{
"code": null,
"e": 24373,
"s": 24112,
"text": "Density plots uses Kernel Density Estimation (so they are also known as Kernel density estimation plots or KDE) which is a probability density function. The region of plot with a higher peak is the region with maximum data points residing between those values."
},
{
"code": null,
"e": 24578,
"s": 24373,
"text": "Density plots can be made using pandas, seaborn, etc. In this article, we will generate density plots using Pandas. We will be using two datasets of the Seaborn Library namely – ‘car_crashes’ and ‘tips’. "
},
{
"code": null,
"e": 24644,
"s": 24578,
"text": "Syntax: pandas.DataFrame.plot.density | pandas.DataFrame.plot.kde"
},
{
"code": null,
"e": 24703,
"s": 24644,
"text": "where pandas -> the dataset of the type ‘pandas dataframe’"
},
{
"code": null,
"e": 24769,
"s": 24703,
"text": "Dataframe -> the column for which the density plot is to be drawn"
},
{
"code": null,
"e": 24837,
"s": 24769,
"text": "plot -> keyword directing to draw a plot/graph for the given column"
},
{
"code": null,
"e": 24878,
"s": 24837,
"text": "density -> for plotting a density graph "
},
{
"code": null,
"e": 24954,
"s": 24878,
"text": "kde -> to plot a density graph using the Kernel Density Estimation function"
},
{
"code": null,
"e": 25114,
"s": 24954,
"text": "Example 1: Given the dataset ‘car_crashes’, let’s find out using the density plot which is the most common speed due to which most of the car crashes happened."
},
{
"code": null,
"e": 25122,
"s": 25114,
"text": "Python3"
},
{
"code": "# importing the librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # loading the dataset# from seaborn librarydata = sns.load_dataset('car_crashes') # viewing the datasetprint(data.head(4))",
"e": 25344,
"s": 25122,
"text": null
},
{
"code": null,
"e": 25352,
"s": 25344,
"text": "Output:"
},
{
"code": null,
"e": 25372,
"s": 25352,
"text": "Plotting the graph:"
},
{
"code": null,
"e": 25380,
"s": 25372,
"text": "Python3"
},
{
"code": "# plotting the density plot # for 'speeding' attribute# using plot.density()data.speeding.plot.density(color='green')plt.title('Density plot for Speeding')plt.show()",
"e": 25546,
"s": 25380,
"text": null
},
{
"code": null,
"e": 25554,
"s": 25546,
"text": "Output:"
},
{
"code": null,
"e": 25734,
"s": 25554,
"text": "Using a density plot, we can figure out that the speed between 4-5 (kmph) was the most common for crash crashes in the dataset because of it being high density (high peak) region."
},
{
"code": null,
"e": 25840,
"s": 25734,
"text": "Example 2: For another dataset ‘tips’, let’s calculate what was the most common tip given by a customer. "
},
{
"code": null,
"e": 25848,
"s": 25840,
"text": "Python3"
},
{
"code": "# loading the dataset# from seaborn librarydata = sns.load_dataset('tips') # viewing the datasetprint(data.head(4))",
"e": 25965,
"s": 25848,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25965,
"text": "Output:"
},
{
"code": null,
"e": 25988,
"s": 25973,
"text": "‘tips’ dataset"
},
{
"code": null,
"e": 26008,
"s": 25988,
"text": "Plotting the graph:"
},
{
"code": null,
"e": 26016,
"s": 26008,
"text": "Python3"
},
{
"code": "# density plot for 'tip'data.tip.plot.density(color='green')plt.title('Density Plot for Tip')plt.show()",
"e": 26120,
"s": 26016,
"text": null
},
{
"code": null,
"e": 26336,
"s": 26120,
"text": "Through the above density plot, we can infer that the most common tip that was given was in the range of 2.5 – 3. The highest peak/density (as represented on the y-axis) was found to be at the tip value of 2.5 – 3. "
},
{
"code": null,
"e": 26381,
"s": 26336,
"text": "Plotting the above plot using the plot.kde()"
},
{
"code": null,
"e": 26600,
"s": 26381,
"text": "KDE or the Kernel Density Estimation uses Gaussian Kernels to estimate the Probability Density Function of a random variable. Below is the implementation of plotting the density plot using kde() for the dataset ‘tips’."
},
{
"code": null,
"e": 26608,
"s": 26600,
"text": "Python3"
},
{
"code": "# for 'tip' attribute# using plot.kde()data.tip.plot.kde(color='green')plt.title('KDE-Density plot for Tip')plt.show()",
"e": 26727,
"s": 26608,
"text": null
},
{
"code": null,
"e": 26866,
"s": 26727,
"text": "Using this we can infer that there is no major difference between plot.density() and plot.kde() and can be therefore used interchangeably."
},
{
"code": null,
"e": 27077,
"s": 26866,
"text": "Density plots have an advantage over Histograms because they determine the Shape of the distribution more efficiently than histograms. They do not have to depend on the number of bins used unlike in histograms."
},
{
"code": null,
"e": 27100,
"s": 27077,
"text": "Python pandas-plotting"
},
{
"code": null,
"e": 27114,
"s": 27100,
"text": "Python-pandas"
},
{
"code": null,
"e": 27121,
"s": 27114,
"text": "Python"
},
{
"code": null,
"e": 27219,
"s": 27121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27228,
"s": 27219,
"text": "Comments"
},
{
"code": null,
"e": 27241,
"s": 27228,
"text": "Old Comments"
},
{
"code": null,
"e": 27259,
"s": 27241,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27294,
"s": 27259,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27316,
"s": 27294,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27348,
"s": 27316,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27378,
"s": 27348,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27420,
"s": 27378,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27446,
"s": 27420,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27489,
"s": 27446,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27533,
"s": 27489,
"text": "Reading and Writing to text files in Python"
}
] |
Find current weather of any city using OpenWeatherMap API in Python
|
In this tutorial, we are going to get the weather of a city using OpenWeatherMap API. To use the OpenWeatherMap API, we have to get the API key. We will get it by creating an account on their website.
Create an account and get your API Key. It's free until 60 calls per minute. You have to pay if you want more than that. For this tutorial, the free version is enough. We need requests module for the HTTP requests and JSON module to work with the response. Follow the below steps to the weather of any city.
Import the requests and JSON modules.
Import the requests and JSON modules.
Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?.
Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?.
Initialize the city and API key.
Initialize the city and API key.
Update the base URL with the API key and city name.
Update the base URL with the API key and city name.
Send a get request using the requests.get() method.
Send a get request using the requests.get() method.
And extract the weather info using the JSON module from the response.
And extract the weather info using the JSON module from the response.
Let's see the code.
# importing requests and json
import requests, json
# base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name CITY = "Hyderabad"
# API key API_KEY = "Your API Key"
# upadting the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# HTTP request
response = requests.get(URL)
# checking the status code of the request
if response.status_code == 200:
# getting data in the json format
data = response.json()
# getting the main dict block
main = data['main']
# getting temperature
temperature = main['temp']
# getting the humidity
humidity = main['humidity']
# getting the pressure
pressure = main['pressure']
# weather report
report = data['weather']
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {report[0]['description']}")
else:
# showing the error message
print("Error in the HTTP request")
If you run the above program, you will get the following results.
----------Hyderabad-----------
Temperature: 295.39
Humidity: 83
Pressure: 1019
Weather Report: mist
If you find any difficulty in following the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "In this tutorial, we are going to get the weather of a city using OpenWeatherMap API. To use the OpenWeatherMap API, we have to get the API key. We will get it by creating an account on their website."
},
{
"code": null,
"e": 1571,
"s": 1263,
"text": "Create an account and get your API Key. It's free until 60 calls per minute. You have to pay if you want more than that. For this tutorial, the free version is enough. We need requests module for the HTTP requests and JSON module to work with the response. Follow the below steps to the weather of any city."
},
{
"code": null,
"e": 1609,
"s": 1571,
"text": "Import the requests and JSON modules."
},
{
"code": null,
"e": 1647,
"s": 1609,
"text": "Import the requests and JSON modules."
},
{
"code": null,
"e": 1740,
"s": 1647,
"text": "Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?."
},
{
"code": null,
"e": 1833,
"s": 1740,
"text": "Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?."
},
{
"code": null,
"e": 1866,
"s": 1833,
"text": "Initialize the city and API key."
},
{
"code": null,
"e": 1899,
"s": 1866,
"text": "Initialize the city and API key."
},
{
"code": null,
"e": 1951,
"s": 1899,
"text": "Update the base URL with the API key and city name."
},
{
"code": null,
"e": 2003,
"s": 1951,
"text": "Update the base URL with the API key and city name."
},
{
"code": null,
"e": 2055,
"s": 2003,
"text": "Send a get request using the requests.get() method."
},
{
"code": null,
"e": 2107,
"s": 2055,
"text": "Send a get request using the requests.get() method."
},
{
"code": null,
"e": 2177,
"s": 2107,
"text": "And extract the weather info using the JSON module from the response."
},
{
"code": null,
"e": 2247,
"s": 2177,
"text": "And extract the weather info using the JSON module from the response."
},
{
"code": null,
"e": 2267,
"s": 2247,
"text": "Let's see the code."
},
{
"code": null,
"e": 3246,
"s": 2267,
"text": "# importing requests and json\nimport requests, json\n# base URL\nBASE_URL = \"https://api.openweathermap.org/data/2.5/weather?\"\n# City Name CITY = \"Hyderabad\"\n# API key API_KEY = \"Your API Key\"\n# upadting the URL\nURL = BASE_URL + \"q=\" + CITY + \"&appid=\" + API_KEY\n# HTTP request\nresponse = requests.get(URL)\n# checking the status code of the request\nif response.status_code == 200:\n # getting data in the json format\n data = response.json()\n # getting the main dict block\n main = data['main']\n # getting temperature\n temperature = main['temp']\n # getting the humidity\n humidity = main['humidity']\n # getting the pressure\n pressure = main['pressure']\n # weather report\n report = data['weather']\n print(f\"{CITY:-^30}\")\n print(f\"Temperature: {temperature}\")\n print(f\"Humidity: {humidity}\")\n print(f\"Pressure: {pressure}\")\n print(f\"Weather Report: {report[0]['description']}\")\nelse:\n # showing the error message\n print(\"Error in the HTTP request\")"
},
{
"code": null,
"e": 3312,
"s": 3246,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 3412,
"s": 3312,
"text": "----------Hyderabad-----------\nTemperature: 295.39\nHumidity: 83\nPressure: 1019\nWeather Report: mist"
},
{
"code": null,
"e": 3503,
"s": 3412,
"text": "If you find any difficulty in following the tutorial, mention them in the comment section."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.