title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to Perform a SUMIF Function in R? | 19 Dec, 2021
In this article, we will discuss the sumif function in R Programming Language.
This function is used to group the data and get the sum of the values by a group of values in the dataframe, so we are going to perform this operation on the dataframe.
In this method to perform a SUMIF() function on one column, the user needs to call the aggregate function with the required parameters as mentioned below to get the results accordingly in the R language.
Syntax:
aggregate(column_sum ~ group_column, dataframe, sum)
Example:
In this example, we are going to create a dataframe with 4 columns, In the first operation, we are performing the sumif operation on subjects by performing group to get sum of marks and in the second operation, we are performing the sumif operation on subjects by performing group to get the sum of id.
R
# create a dataframedata = data.frame(id=c(1, 2, 3, 4, 5), name=c('rupa', 'rani', 'radha', 'ramu', 'roja'), subjects=c('java', 'php', 'java', 'php', 'php'), marks=c(100, 98, 90, 87, 89)) # sumif operation on subjects by# performing group to get sum of marksprint(aggregate(marks ~ subjects, data, sum)) # sumif operation on subjects by# performing group to get sum of idprint(aggregate(id~ subjects, data, sum))
Output:
subjects marks
1 java 190
2 php 274
subjects id
1 java 4
2 php 11
In this approach to perform the SUMIF function on multiple columns of the given data frame the user needs to call the aggregate() function with the cbind() function as the parameters as shown in the syntax below to get the sumif function on multiple columns of the given data frame in the R programming language.
Syntax:
aggregate(cbind(column_sum1,column_sum2,..,) ~ group_column, dataframe, sum)
Example:
In this example, we will be performing the sumif operation on subjects by performing a group to get the sum of id and sum of marks in the R programming language.
R
# create a dataframedata=data.frame(id=c(1,2,3,4,5), name=c('rupa','rani','radha','ramu','roja'), subjects=c('java','php','java','php','php'), marks=c(100,98,90,87,89)) # sumif operation on subjects by performing# group to get sum of id and sum of marksprint(aggregate(cbind(marks,id)~ subjects, data, sum))
Output:
subjects marks id
1 java 190 4
2 php 274 11
In this method to perform a sumif function on all the columns of the given dataframe, the user needs to simply call the aggregate() function of base R and pass the name of the data frame as the parameter into it as shown in the syntax below to get the result to the performing the sumif function on the entire data frame in the R language.
Syntax:
aggregate(. ~ group_column, dataframe, sum)
Example:
In this example, we are performing the sumif operation on subjects by performing a group to get the sum of all columns using the aggregate() function in the R language.
R
# create a dataframedata=data.frame(id=c(1,2,3,4,5), subjects=c('java','php','java','php','php'), marks=c(100,98,90,87,89)) # sumif operation on subjects by # performing group to get sum of all columnsprint(aggregate(. ~ subjects, data, sum))
Output:
subjects id marks
1 java 4 190
2 php 11 274
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "In this article, we will discuss the sumif function in R Programming Language."
},
{
"code": null,
"e": 276,
"s": 107,
"text": "This function is used to group the data and get the sum of the values by a group of values in the dataframe, so we are going to perform this operation on the dataframe."
},
{
"code": null,
"e": 480,
"s": 276,
"text": "In this method to perform a SUMIF() function on one column, the user needs to call the aggregate function with the required parameters as mentioned below to get the results accordingly in the R language."
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Syntax:"
},
{
"code": null,
"e": 541,
"s": 488,
"text": "aggregate(column_sum ~ group_column, dataframe, sum)"
},
{
"code": null,
"e": 550,
"s": 541,
"text": "Example:"
},
{
"code": null,
"e": 853,
"s": 550,
"text": "In this example, we are going to create a dataframe with 4 columns, In the first operation, we are performing the sumif operation on subjects by performing group to get sum of marks and in the second operation, we are performing the sumif operation on subjects by performing group to get the sum of id."
},
{
"code": null,
"e": 855,
"s": 853,
"text": "R"
},
{
"code": "# create a dataframedata = data.frame(id=c(1, 2, 3, 4, 5), name=c('rupa', 'rani', 'radha', 'ramu', 'roja'), subjects=c('java', 'php', 'java', 'php', 'php'), marks=c(100, 98, 90, 87, 89)) # sumif operation on subjects by# performing group to get sum of marksprint(aggregate(marks ~ subjects, data, sum)) # sumif operation on subjects by# performing group to get sum of idprint(aggregate(id~ subjects, data, sum))",
"e": 1320,
"s": 855,
"text": null
},
{
"code": null,
"e": 1328,
"s": 1320,
"text": "Output:"
},
{
"code": null,
"e": 1422,
"s": 1328,
"text": " subjects marks\n1 java 190\n2 php 274\n\n subjects id\n1 java 4\n2 php 11"
},
{
"code": null,
"e": 1735,
"s": 1422,
"text": "In this approach to perform the SUMIF function on multiple columns of the given data frame the user needs to call the aggregate() function with the cbind() function as the parameters as shown in the syntax below to get the sumif function on multiple columns of the given data frame in the R programming language."
},
{
"code": null,
"e": 1743,
"s": 1735,
"text": "Syntax:"
},
{
"code": null,
"e": 1820,
"s": 1743,
"text": "aggregate(cbind(column_sum1,column_sum2,..,) ~ group_column, dataframe, sum)"
},
{
"code": null,
"e": 1829,
"s": 1820,
"text": "Example:"
},
{
"code": null,
"e": 1991,
"s": 1829,
"text": "In this example, we will be performing the sumif operation on subjects by performing a group to get the sum of id and sum of marks in the R programming language."
},
{
"code": null,
"e": 1993,
"s": 1991,
"text": "R"
},
{
"code": "# create a dataframedata=data.frame(id=c(1,2,3,4,5), name=c('rupa','rani','radha','ramu','roja'), subjects=c('java','php','java','php','php'), marks=c(100,98,90,87,89)) # sumif operation on subjects by performing# group to get sum of id and sum of marksprint(aggregate(cbind(marks,id)~ subjects, data, sum))",
"e": 2347,
"s": 1993,
"text": null
},
{
"code": null,
"e": 2355,
"s": 2347,
"text": "Output:"
},
{
"code": null,
"e": 2415,
"s": 2355,
"text": " subjects marks id\n1 java 190 4\n2 php 274 11"
},
{
"code": null,
"e": 2755,
"s": 2415,
"text": "In this method to perform a sumif function on all the columns of the given dataframe, the user needs to simply call the aggregate() function of base R and pass the name of the data frame as the parameter into it as shown in the syntax below to get the result to the performing the sumif function on the entire data frame in the R language."
},
{
"code": null,
"e": 2763,
"s": 2755,
"text": "Syntax:"
},
{
"code": null,
"e": 2807,
"s": 2763,
"text": "aggregate(. ~ group_column, dataframe, sum)"
},
{
"code": null,
"e": 2816,
"s": 2807,
"text": "Example:"
},
{
"code": null,
"e": 2985,
"s": 2816,
"text": "In this example, we are performing the sumif operation on subjects by performing a group to get the sum of all columns using the aggregate() function in the R language."
},
{
"code": null,
"e": 2987,
"s": 2985,
"text": "R"
},
{
"code": "# create a dataframedata=data.frame(id=c(1,2,3,4,5), subjects=c('java','php','java','php','php'), marks=c(100,98,90,87,89)) # sumif operation on subjects by # performing group to get sum of all columnsprint(aggregate(. ~ subjects, data, sum))",
"e": 3261,
"s": 2987,
"text": null
},
{
"code": null,
"e": 3269,
"s": 3261,
"text": "Output:"
},
{
"code": null,
"e": 3329,
"s": 3269,
"text": " subjects id marks\n1 java 4 190\n2 php 11 274"
},
{
"code": null,
"e": 3336,
"s": 3329,
"text": "Picked"
},
{
"code": null,
"e": 3348,
"s": 3336,
"text": "R-Functions"
},
{
"code": null,
"e": 3359,
"s": 3348,
"text": "R Language"
},
{
"code": null,
"e": 3457,
"s": 3359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3509,
"s": 3457,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3567,
"s": 3509,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3602,
"s": 3567,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3640,
"s": 3602,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3657,
"s": 3640,
"text": "R - if statement"
},
{
"code": null,
"e": 3694,
"s": 3657,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3743,
"s": 3694,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3786,
"s": 3743,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3823,
"s": 3786,
"text": "How to import an Excel File into R ?"
}
] |
Ways to capture the backspace and delete on the onkeydown event | 23 Jan, 2020
Given the HTML document. The task is to detect when the backspace and delete keys are pressed on keydown events. Here 2 approaches are discussed, one uses event.key and another uses event.keyCode with the help of JavaScript.
Approach 1:
Take the input from input element and add a event listener to the input element using el.addEventListener() method on onkeydown event.
Use event.key inside the anonymous function called in the addeventlistener method to get the key pressed.
Check if the key pressed is Backspace or Delete.
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Capture the backspace and delete on the onkeydown event. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Type Here: <input id="inp" /> <br> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var el = document.getElementById('inp'); up.innerHTML = "Type in the input box to determine the pressed."; el.addEventListener('keydown', function(event) { const key = event.key; if (key === "Backspace" || key === "Delete") { $('#GFG_DOWN').html(key + ' is Pressed!'); } }); </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Take the input from input element and add a event listener to the input element using el.addEventListener() method on onkeydown event.
Use event.keyCode inside the anonymous function called in the addeventlistener method to get the key pressed.
Check if the key’s code matches with the key code of Backspace or Delete button.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Capture the backspace and delete on the onkeydown event. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Type Here: <input id="inp" /> <br> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var el = document.getElementById('inp'); up.innerHTML = "Type in the input box to determine the pressed."; el.addEventListener('keydown', function(event) { // Checking for Backspace. if (event.keyCode == 8) { $('#GFG_DOWN').html('Backspace is Pressed!'); } // Checking for Delete. if (event.keyCode == 46) { $('#GFG_DOWN').html('Delete is Pressed!'); } }); </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 277,
"s": 52,
"text": "Given the HTML document. The task is to detect when the backspace and delete keys are pressed on keydown events. Here 2 approaches are discussed, one uses event.key and another uses event.keyCode with the help of JavaScript."
},
{
"code": null,
"e": 289,
"s": 277,
"text": "Approach 1:"
},
{
"code": null,
"e": 424,
"s": 289,
"text": "Take the input from input element and add a event listener to the input element using el.addEventListener() method on onkeydown event."
},
{
"code": null,
"e": 530,
"s": 424,
"text": "Use event.key inside the anonymous function called in the addeventlistener method to get the key pressed."
},
{
"code": null,
"e": 579,
"s": 530,
"text": "Check if the key pressed is Backspace or Delete."
},
{
"code": null,
"e": 634,
"s": 579,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Capture the backspace and delete on the onkeydown event. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Type Here: <input id=\"inp\" /> <br> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var el = document.getElementById('inp'); up.innerHTML = \"Type in the input box to determine the pressed.\"; el.addEventListener('keydown', function(event) { const key = event.key; if (key === \"Backspace\" || key === \"Delete\") { $('#GFG_DOWN').html(key + ' is Pressed!'); } }); </script></body> </html>",
"e": 1580,
"s": 634,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1580,
"text": "Output:"
},
{
"code": null,
"e": 1619,
"s": 1588,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1649,
"s": 1619,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1661,
"s": 1649,
"text": "Approach 2:"
},
{
"code": null,
"e": 1796,
"s": 1661,
"text": "Take the input from input element and add a event listener to the input element using el.addEventListener() method on onkeydown event."
},
{
"code": null,
"e": 1906,
"s": 1796,
"text": "Use event.keyCode inside the anonymous function called in the addeventlistener method to get the key pressed."
},
{
"code": null,
"e": 1987,
"s": 1906,
"text": "Check if the key’s code matches with the key code of Backspace or Delete button."
},
{
"code": null,
"e": 2042,
"s": 1987,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Capture the backspace and delete on the onkeydown event. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Type Here: <input id=\"inp\" /> <br> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var el = document.getElementById('inp'); up.innerHTML = \"Type in the input box to determine the pressed.\"; el.addEventListener('keydown', function(event) { // Checking for Backspace. if (event.keyCode == 8) { $('#GFG_DOWN').html('Backspace is Pressed!'); } // Checking for Delete. if (event.keyCode == 46) { $('#GFG_DOWN').html('Delete is Pressed!'); } }); </script></body> </html>",
"e": 3118,
"s": 2042,
"text": null
},
{
"code": null,
"e": 3126,
"s": 3118,
"text": "Output:"
},
{
"code": null,
"e": 3157,
"s": 3126,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3187,
"s": 3157,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3203,
"s": 3187,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3214,
"s": 3203,
"text": "JavaScript"
},
{
"code": null,
"e": 3231,
"s": 3214,
"text": "Web Technologies"
},
{
"code": null,
"e": 3329,
"s": 3231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3390,
"s": 3329,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3462,
"s": 3390,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3502,
"s": 3462,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3543,
"s": 3502,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3585,
"s": 3543,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3647,
"s": 3585,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3680,
"s": 3647,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3741,
"s": 3680,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3791,
"s": 3741,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Pygame – Character Animation | 16 Jun, 2022
PyGame is a Free and Open source python library used to design video games. In this article, we will learn how we can add different animations to our characters.
We can easily add simple animations in our pygame projects by following the below steps.
Create a list of sprites
Iterate over the list
Display the sprite on the screen
Python3
# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Create a list of different sprites# that you want to use in the animationimage_sprite = [pygame.image.load("Sprite1.png"), pygame.image.load("Sprite2.png")] # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new variable# We will use this variable to# iterate over the sprite listvalue = 0 # Creating a boolean variable that# we will use to run the while looprun = True # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 3fps just # to see the result properly clock.tick(3) # Setting 0 in value variable if its # value is greater than the length # of our sprite list if value >= len(image_sprite): value = 0 # Storing the sprite image in an # image variable image = image_sprite[value] # Creating a variable to store the starting # x and y coordinate x = 150 # Changing the y coordinate # according the value stored # in our value variable if value == 0: y = 200 else: y = 265 # Displaying the image in our game window window.blit(image, (x, y)) # Updating the display surface pygame.display.update() # Filling the window with black color window.fill((0, 0, 0)) # Increasing the value of value variable by 1 # after every iteration value += 1
Output:
Explanation:
Create a display surface object of a specific dimension
Then Create a list of different sprites that you want to use in the animation, and then create a new clock object to track the amount of time.
Create a boolean variable that we will use to run the while loop and then Create an infinite loop to run our game. Setting the framerate to 3fps just to see the result properly. Set 0 in value variable if its value is greater than the length of our sprite list.
Store the sprite image in an image variable, and then Create a variable to store the starting x and y coordinate. Change the y-coordinate according to the value stored in our value variable.
Then display the image in our game window and Update the display surface, and fill the window with black color.
If you only want to show animation when your character is moving or when a user presses a specific button then you can do that by following these steps:
Create a variable to check if the character is moving or not.
Create a list of sprites
If the character is moving then iterate over the list of sprites and display the sprites on the screen.
If the character is not moving display the sprite stored at the 0th index in the list.
Python3
# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Create a list of different sprites# that you want to use in the animationimage_sprite = [pygame.image.load("Sprite1.png"), pygame.image.load("Sprite2.png"), pygame.image.load("Sprite3.png"), pygame.image.load("Sprite4.png")] # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new variable# We will use this variable to# iterate over the sprite listvalue = 0 # Creating a boolean variable that# we will use to run the while looprun = True # Creating a boolean variable to# check if the character is moving# or notmoving = False # Creating a variable to store# the velocityvelocity = 12 # Starting coordinates of the spritex = 100y = 150 # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 10fps just # to see the result properly clock.tick(10) # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get(): # Closing the window and program if the # type of the event is QUIT if event.type == pygame.QUIT: run = False pygame.quit() quit() # Checking event key if the type # of the event is KEYUP i.e. # keyboard button is released if event.type == pygame.KEYUP: # Setting the value of moving to False # and the value f value variable to 0 # if the button released is # Left arrow key or right arrow key if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: moving = False value = 0 # Storing the key pressed in a # new variable using key.get_pressed() # method key_pressed_is = pygame.key.get_pressed() # Changing the x coordinate # of the player and setting moving # variable to True if key_pressed_is[K_LEFT]: x -= 8 moving = True if key_pressed_is[K_RIGHT]: x += 8 moving = True # If moving variable is True # then increasing the value of # value variable by 1 if moving: value += 1 # Setting 0 in value variable if its # value is greater than the length # of our sprite list if value >= len(image_sprite): value = 0 # Storing the sprite image in an # image variable image = image_sprite[value] # Scaling the image image = pygame.transform.scale(image, (180, 180)) # Displaying the image in our game window window.blit(image, (x, y)) # Updating the display surface pygame.display.update() # Filling the window with black color window.fill((0, 0, 0))
Output:
Explanation:
Create a display surface object of a specific dimension and then create a list of different sprites that you want to use in the animation.
Create a new clock object to track the amount of time and Create a new variable. We will use this variable to iterate over the sprite list. Create a boolean variable that we will use to run the while loop, and Create a boolean variable to check if the character is moving or not, create a variable to store the velocity starting coordinates of the sprite, and create an infinite loop to run our game and set the framerate to 10fps just to see the result properly, iterate over the list of Event objects that were returned by pygame.event.get() method. Close the window and program if the type of the event is QUIT.
Checking event key if the type of the event is KEYUP i.e. keyboard button is released and set the value of moving to False and the value pf value variable to 0 if the button released is Left arrow key or right arrow key.
Store the key pressed in a new variable using key.get_pressed() method. Change the x coordinate of the player and setting the moving variable to True. If the moving variable is True then increasing the value of the value variable by 1. Set 0 in the value variable if its value is greater than the length of our sprite list. Store the sprite image in an image variable and then Scale the image
sweetyty
sagar0719kumar
surinderdawra388
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 216,
"s": 54,
"text": "PyGame is a Free and Open source python library used to design video games. In this article, we will learn how we can add different animations to our characters."
},
{
"code": null,
"e": 305,
"s": 216,
"text": "We can easily add simple animations in our pygame projects by following the below steps."
},
{
"code": null,
"e": 330,
"s": 305,
"text": "Create a list of sprites"
},
{
"code": null,
"e": 352,
"s": 330,
"text": "Iterate over the list"
},
{
"code": null,
"e": 385,
"s": 352,
"text": "Display the sprite on the screen"
},
{
"code": null,
"e": 393,
"s": 385,
"text": "Python3"
},
{
"code": "# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Create a list of different sprites# that you want to use in the animationimage_sprite = [pygame.image.load(\"Sprite1.png\"), pygame.image.load(\"Sprite2.png\")] # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new variable# We will use this variable to# iterate over the sprite listvalue = 0 # Creating a boolean variable that# we will use to run the while looprun = True # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 3fps just # to see the result properly clock.tick(3) # Setting 0 in value variable if its # value is greater than the length # of our sprite list if value >= len(image_sprite): value = 0 # Storing the sprite image in an # image variable image = image_sprite[value] # Creating a variable to store the starting # x and y coordinate x = 150 # Changing the y coordinate # according the value stored # in our value variable if value == 0: y = 200 else: y = 265 # Displaying the image in our game window window.blit(image, (x, y)) # Updating the display surface pygame.display.update() # Filling the window with black color window.fill((0, 0, 0)) # Increasing the value of value variable by 1 # after every iteration value += 1",
"e": 1998,
"s": 393,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1998,
"text": "Output:"
},
{
"code": null,
"e": 2019,
"s": 2006,
"text": "Explanation:"
},
{
"code": null,
"e": 2075,
"s": 2019,
"text": "Create a display surface object of a specific dimension"
},
{
"code": null,
"e": 2218,
"s": 2075,
"text": "Then Create a list of different sprites that you want to use in the animation, and then create a new clock object to track the amount of time."
},
{
"code": null,
"e": 2480,
"s": 2218,
"text": "Create a boolean variable that we will use to run the while loop and then Create an infinite loop to run our game. Setting the framerate to 3fps just to see the result properly. Set 0 in value variable if its value is greater than the length of our sprite list."
},
{
"code": null,
"e": 2671,
"s": 2480,
"text": "Store the sprite image in an image variable, and then Create a variable to store the starting x and y coordinate. Change the y-coordinate according to the value stored in our value variable."
},
{
"code": null,
"e": 2783,
"s": 2671,
"text": "Then display the image in our game window and Update the display surface, and fill the window with black color."
},
{
"code": null,
"e": 2936,
"s": 2783,
"text": "If you only want to show animation when your character is moving or when a user presses a specific button then you can do that by following these steps:"
},
{
"code": null,
"e": 2998,
"s": 2936,
"text": "Create a variable to check if the character is moving or not."
},
{
"code": null,
"e": 3023,
"s": 2998,
"text": "Create a list of sprites"
},
{
"code": null,
"e": 3127,
"s": 3023,
"text": "If the character is moving then iterate over the list of sprites and display the sprites on the screen."
},
{
"code": null,
"e": 3214,
"s": 3127,
"text": "If the character is not moving display the sprite stored at the 0th index in the list."
},
{
"code": null,
"e": 3222,
"s": 3214,
"text": "Python3"
},
{
"code": "# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Create a list of different sprites# that you want to use in the animationimage_sprite = [pygame.image.load(\"Sprite1.png\"), pygame.image.load(\"Sprite2.png\"), pygame.image.load(\"Sprite3.png\"), pygame.image.load(\"Sprite4.png\")] # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new variable# We will use this variable to# iterate over the sprite listvalue = 0 # Creating a boolean variable that# we will use to run the while looprun = True # Creating a boolean variable to# check if the character is moving# or notmoving = False # Creating a variable to store# the velocityvelocity = 12 # Starting coordinates of the spritex = 100y = 150 # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 10fps just # to see the result properly clock.tick(10) # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get(): # Closing the window and program if the # type of the event is QUIT if event.type == pygame.QUIT: run = False pygame.quit() quit() # Checking event key if the type # of the event is KEYUP i.e. # keyboard button is released if event.type == pygame.KEYUP: # Setting the value of moving to False # and the value f value variable to 0 # if the button released is # Left arrow key or right arrow key if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: moving = False value = 0 # Storing the key pressed in a # new variable using key.get_pressed() # method key_pressed_is = pygame.key.get_pressed() # Changing the x coordinate # of the player and setting moving # variable to True if key_pressed_is[K_LEFT]: x -= 8 moving = True if key_pressed_is[K_RIGHT]: x += 8 moving = True # If moving variable is True # then increasing the value of # value variable by 1 if moving: value += 1 # Setting 0 in value variable if its # value is greater than the length # of our sprite list if value >= len(image_sprite): value = 0 # Storing the sprite image in an # image variable image = image_sprite[value] # Scaling the image image = pygame.transform.scale(image, (180, 180)) # Displaying the image in our game window window.blit(image, (x, y)) # Updating the display surface pygame.display.update() # Filling the window with black color window.fill((0, 0, 0))",
"e": 6147,
"s": 3222,
"text": null
},
{
"code": null,
"e": 6155,
"s": 6147,
"text": "Output:"
},
{
"code": null,
"e": 6168,
"s": 6155,
"text": "Explanation:"
},
{
"code": null,
"e": 6307,
"s": 6168,
"text": "Create a display surface object of a specific dimension and then create a list of different sprites that you want to use in the animation."
},
{
"code": null,
"e": 6922,
"s": 6307,
"text": "Create a new clock object to track the amount of time and Create a new variable. We will use this variable to iterate over the sprite list. Create a boolean variable that we will use to run the while loop, and Create a boolean variable to check if the character is moving or not, create a variable to store the velocity starting coordinates of the sprite, and create an infinite loop to run our game and set the framerate to 10fps just to see the result properly, iterate over the list of Event objects that were returned by pygame.event.get() method. Close the window and program if the type of the event is QUIT."
},
{
"code": null,
"e": 7143,
"s": 6922,
"text": "Checking event key if the type of the event is KEYUP i.e. keyboard button is released and set the value of moving to False and the value pf value variable to 0 if the button released is Left arrow key or right arrow key."
},
{
"code": null,
"e": 7536,
"s": 7143,
"text": "Store the key pressed in a new variable using key.get_pressed() method. Change the x coordinate of the player and setting the moving variable to True. If the moving variable is True then increasing the value of the value variable by 1. Set 0 in the value variable if its value is greater than the length of our sprite list. Store the sprite image in an image variable and then Scale the image"
},
{
"code": null,
"e": 7545,
"s": 7536,
"text": "sweetyty"
},
{
"code": null,
"e": 7560,
"s": 7545,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 7577,
"s": 7560,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7584,
"s": 7577,
"text": "Picked"
},
{
"code": null,
"e": 7598,
"s": 7584,
"text": "Python-PyGame"
},
{
"code": null,
"e": 7605,
"s": 7598,
"text": "Python"
},
{
"code": null,
"e": 7703,
"s": 7605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7735,
"s": 7703,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7762,
"s": 7735,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7783,
"s": 7762,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 7806,
"s": 7783,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 7862,
"s": 7806,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 7893,
"s": 7862,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 7935,
"s": 7893,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 7977,
"s": 7935,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8016,
"s": 7977,
"text": "Python | Get unique values from a list"
}
] |
Integer shortValue() Method in Java | 05 Dec, 2018
The Integer.shortValue() is an inbuilt method of java.lang which returns the value of this Integer in the short type .
Syntax:
public short shortValue()
Parameters: The method does not take any parameters.
Return Value: The method returns the integer value represented by this object after converting it to type short.
Below programs illustrate the Integer.shortValue() method:Program 1: For positive integers.
// Java program that demonstrates// Integer.shortValue() method import java.lang.*; public class Geeks { public static void main(String[] args) { Integer sh_object = new Integer(763); // It will return the value of this Integer as a short type short sh_value = sh_object.shortValue(); System.out.println(" The Value of sh_value = " + sh_value); }}
The Value of sh_value = 763
Program 2: For negative number.
// Java program that demonstrates// Integer.shortValue() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { Integer sh_object = new Integer(-43); // It will return the value of this Integer as a short type short sh_value = sh_object.shortValue(); System.out.println(" The Value of sh_value = " + sh_value); }}
The Value of sh_value = -43
Program 3: For a decimal value and string.Note: It returns an error message when a decimal value and string is passed as an argument.
// java program that demonstrates// Integer.shortValue() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // passing a decimal value Integer sh_object = new Integer(27.51); short sh_value = sh_object.shortValue(); System.out.println(" The Value of sh_value = " + sh_value); // passing a string Integer sh_object2 = new Integer("51"); short sh_value2 = sh_object2.shortValue(); System.out.println(" The Value of sh_value2 = " + sh_value2); }}
Output:
prog.java:10: error: no suitable constructor found for Integer(double)
Integer sh_object = new Integer(27.51);
^
constructor Integer.Integer(int) is not applicable
(argument mismatch; possible lossy conversion from double to int)
constructor Integer.Integer(String) is not applicable
(argument mismatch; double cannot be converted to String)
1 error
Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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": 28,
"s": 0,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "The Integer.shortValue() is an inbuilt method of java.lang which returns the value of this Integer in the short type ."
},
{
"code": null,
"e": 155,
"s": 147,
"text": "Syntax:"
},
{
"code": null,
"e": 182,
"s": 155,
"text": "public short shortValue()\n"
},
{
"code": null,
"e": 235,
"s": 182,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 348,
"s": 235,
"text": "Return Value: The method returns the integer value represented by this object after converting it to type short."
},
{
"code": null,
"e": 440,
"s": 348,
"text": "Below programs illustrate the Integer.shortValue() method:Program 1: For positive integers."
},
{
"code": "// Java program that demonstrates// Integer.shortValue() method import java.lang.*; public class Geeks { public static void main(String[] args) { Integer sh_object = new Integer(763); // It will return the value of this Integer as a short type short sh_value = sh_object.shortValue(); System.out.println(\" The Value of sh_value = \" + sh_value); }}",
"e": 833,
"s": 440,
"text": null
},
{
"code": null,
"e": 862,
"s": 833,
"text": "The Value of sh_value = 763\n"
},
{
"code": null,
"e": 894,
"s": 862,
"text": "Program 2: For negative number."
},
{
"code": "// Java program that demonstrates// Integer.shortValue() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { Integer sh_object = new Integer(-43); // It will return the value of this Integer as a short type short sh_value = sh_object.shortValue(); System.out.println(\" The Value of sh_value = \" + sh_value); }}",
"e": 1285,
"s": 894,
"text": null
},
{
"code": null,
"e": 1314,
"s": 1285,
"text": "The Value of sh_value = -43\n"
},
{
"code": null,
"e": 1448,
"s": 1314,
"text": "Program 3: For a decimal value and string.Note: It returns an error message when a decimal value and string is passed as an argument."
},
{
"code": "// java program that demonstrates// Integer.shortValue() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // passing a decimal value Integer sh_object = new Integer(27.51); short sh_value = sh_object.shortValue(); System.out.println(\" The Value of sh_value = \" + sh_value); // passing a string Integer sh_object2 = new Integer(\"51\"); short sh_value2 = sh_object2.shortValue(); System.out.println(\" The Value of sh_value2 = \" + sh_value2); }}",
"e": 2005,
"s": 1448,
"text": null
},
{
"code": null,
"e": 2013,
"s": 2005,
"text": "Output:"
},
{
"code": null,
"e": 2412,
"s": 2013,
"text": "prog.java:10: error: no suitable constructor found for Integer(double)\n Integer sh_object = new Integer(27.51);\n ^\n constructor Integer.Integer(int) is not applicable\n (argument mismatch; possible lossy conversion from double to int)\n constructor Integer.Integer(String) is not applicable\n (argument mismatch; double cannot be converted to String)\n1 error\n"
},
{
"code": null,
"e": 2427,
"s": 2412,
"text": "Java-Functions"
},
{
"code": null,
"e": 2440,
"s": 2427,
"text": "Java-Integer"
},
{
"code": null,
"e": 2458,
"s": 2440,
"text": "Java-lang package"
},
{
"code": null,
"e": 2463,
"s": 2458,
"text": "Java"
},
{
"code": null,
"e": 2468,
"s": 2463,
"text": "Java"
},
{
"code": null,
"e": 2566,
"s": 2468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2581,
"s": 2566,
"text": "Stream In Java"
},
{
"code": null,
"e": 2602,
"s": 2581,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2623,
"s": 2602,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2642,
"s": 2623,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2659,
"s": 2642,
"text": "Generics in Java"
},
{
"code": null,
"e": 2689,
"s": 2659,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2715,
"s": 2689,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2731,
"s": 2715,
"text": "Strings in Java"
},
{
"code": null,
"e": 2768,
"s": 2731,
"text": "Differences between JDK, JRE and JVM"
}
] |
pidof Command in Linux with Examples | 26 May, 2022
pidof command is used to find out the process IDs of a specific running program. It is basically an identification number that is automatically assigned to each process when it is created. Syntax:
pidof [options] program1 program2 ... programN
1. To find pid of any process
pidof bash
Use the name of the program as input to the command and command produced bash process ID in the output. 2. To get only one pid of a program
pidof -s bash
By default, pidof displays all pids of named command or program. So to display only one process ID of the program we have to pass “-s” option with it. 3. To get pids of scripts
pidof -x bash
The pidof command does not display pids of shell/perl/python scripts. We use the “-x” option to find the process ids of shells running the named script called bash. 4. To limit output based on the root directory
pidof -c bash
If we want that pidof returns only process ids that are running with the same root directory, we use “-c” command-line option. Note: This option is ignored for non-root users, as they are unable to check the current root directory of processes they do not own. 5. To omit processes
pidof -o 87223 bash
If we want to ignore or omit processes with that process id, we can use pidof command to this. This is useful to ignore calling shell or shell script or specific pid. Here, it says we want to find all pids of bash and omit pid #87223. So, we use the given code for that. 6. To find pid of a program and kill it
p=$(pidof chrome)
kill $p
In this, firstly we find all PIDs of chrome server and then kill it.
rkbhola5
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 249,
"s": 52,
"text": "pidof command is used to find out the process IDs of a specific running program. It is basically an identification number that is automatically assigned to each process when it is created. Syntax:"
},
{
"code": null,
"e": 296,
"s": 249,
"text": "pidof [options] program1 program2 ... programN"
},
{
"code": null,
"e": 326,
"s": 296,
"text": "1. To find pid of any process"
},
{
"code": null,
"e": 337,
"s": 326,
"text": "pidof bash"
},
{
"code": null,
"e": 478,
"s": 337,
"text": " Use the name of the program as input to the command and command produced bash process ID in the output. 2. To get only one pid of a program"
},
{
"code": null,
"e": 492,
"s": 478,
"text": "pidof -s bash"
},
{
"code": null,
"e": 670,
"s": 492,
"text": " By default, pidof displays all pids of named command or program. So to display only one process ID of the program we have to pass “-s” option with it. 3. To get pids of scripts"
},
{
"code": null,
"e": 684,
"s": 670,
"text": "pidof -x bash"
},
{
"code": null,
"e": 897,
"s": 684,
"text": " The pidof command does not display pids of shell/perl/python scripts. We use the “-x” option to find the process ids of shells running the named script called bash. 4. To limit output based on the root directory"
},
{
"code": null,
"e": 912,
"s": 897,
"text": "pidof -c bash "
},
{
"code": null,
"e": 1195,
"s": 912,
"text": " If we want that pidof returns only process ids that are running with the same root directory, we use “-c” command-line option. Note: This option is ignored for non-root users, as they are unable to check the current root directory of processes they do not own. 5. To omit processes"
},
{
"code": null,
"e": 1215,
"s": 1195,
"text": "pidof -o 87223 bash"
},
{
"code": null,
"e": 1527,
"s": 1215,
"text": " If we want to ignore or omit processes with that process id, we can use pidof command to this. This is useful to ignore calling shell or shell script or specific pid. Here, it says we want to find all pids of bash and omit pid #87223. So, we use the given code for that. 6. To find pid of a program and kill it"
},
{
"code": null,
"e": 1553,
"s": 1527,
"text": "p=$(pidof chrome)\nkill $p"
},
{
"code": null,
"e": 1623,
"s": 1553,
"text": " In this, firstly we find all PIDs of chrome server and then kill it."
},
{
"code": null,
"e": 1632,
"s": 1623,
"text": "rkbhola5"
},
{
"code": null,
"e": 1646,
"s": 1632,
"text": "linux-command"
},
{
"code": null,
"e": 1668,
"s": 1646,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1679,
"s": 1668,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1777,
"s": 1679,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1803,
"s": 1777,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1838,
"s": 1803,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1875,
"s": 1838,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1943,
"s": 1904,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1980,
"s": 1943,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2020,
"s": 1980,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2054,
"s": 2020,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2091,
"s": 2054,
"text": "chmod command in Linux with examples"
}
] |
Input Events in Android with Example | 23 Feb, 2021
In Android, there’s quite a method to intercept the events from a user’s interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you’re going to use to compose your layout, you’ll notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs thereon object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method is named thereon object. However, to intercept this, you must extend the class and override the method. However, extending every View object to handle such an event would not be practical. This is why the View class also contains a set of nested interfaces with callbacks that you simply can far more easily define. These interfaces, called Event listeners, are your ticket to capturing the user interaction together with your UI.
For Example, if a button is to reply to a click event it must register to look at the .onClickListener event listener and implement the corresponding onClick() callback method. In an application when a button click event is detected, the Android framework will call the onClick() method of that particular view.
Event Listener is an interface within the View class that contains one call-back method. These methods are going to be called by the Android framework when the View which is registered with the listener is triggered by user interaction with the item in UI. Included in the event listener interfaces are the following callback methods:
Methods
Event Listeners
Description
onClick()
View.OnClickListener
This method is called when the user touches the item or focuses upon the item with the navigation-keys or trackball and presses the suitable “enter” key or presses down on the trackball.
onLongClick()
View.OnLongClickListener
This is called when the user either touches and holds the item, or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable “enter” key or presses and holds down on the trackball (for one second).
onFocusChange()
View.OnFocusChangeListener
This is called when the user navigates onto or away from the item, using the navigation-keys or trackball.
onKey()
View.OnKeyListener
This is called when the user is focused on the item and presses or releases a hardware key on the device.
onTouch()
View.OnTouchListener
This is called when the user acts qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).
onCreateContextMenu()
View.OnCreateContextMenuListener
This is called when a Context Menu is being built (as the result of a sustained “long click”).
Note:
onClick() callback does not return any value. But onLongClick(), onKey(), onTouch() callback returns a boolean value that indicates that you simply have consumed the event and it should not be carried further; That is, return true to indicate that you have handled the event and it should stop here; return false if you’ve not handled it and/or the event should continue to any other on-click listeners.
Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. This example illustrates how to register an on-click listener for a Button
Kotlin
protected void onCreate(savedValues: Bundle) { ... val button: Button = findViewById(R.id.button) // Register the onClick listener button.setOnClickListener { view -> // do something when the button is clicked } ...}
Event Handlers are useful to define several callback methods when we are building custom components from view. Following are some of the commonly used callback methods for event handling in android applications.
Method
Description
We have learned about Event Listeners, Event Handlers, and their callback methods. Now we will see their implementations in our android application.
Let us see the way to implement Input Events in Android. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a new project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio in Kotlin. Note that select Kotlin as the programming language.
Step 2: Working with the XML Files
To design the UI, code is present under the res\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- This is the layout for the Button which user will click --> <Button android:id="@+id/btnClick" android:layout_width="200dp" android:layout_height="70dp" android:layout_gravity="center" android:layout_marginTop="200dp" android:text="CLICK ME!" android:textSize="18sp" android:textStyle="bold" /> <!-- This is the layout for the textView, On Click of Button the text will appear on the screen --> <TextView android:id="@+id/textResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="50dp" android:textColor="#86AD33" android:textSize="25sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@id/btnClick" /> </LinearLayout>
Step 3: Working with the MainActivity File
Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Register OnClickListener for button // call Click Handler method findViewById<Button>(R.id.btnClick).setOnClickListener { displayTextOnButtonClick(it) } // Register OnLongClickListener for button // call Click Handler method // Return true to indicate that the event is consumed findViewById<Button>(R.id.btnClick).setOnLongClickListener { displayTextOnLongButtonClick(it) true } } // Click handler for the Click me button. // Display the text below Click me Button // Display text after Button click // It has No Return Value private fun displayTextOnButtonClick(view: View) { val text = findViewById<TextView>(R.id.textResult) text.text = "Button Clicked !" } // Click handler for the Click me button. // Display the text below Click me Button // Display text after Button click for a bit long time (1-2sec) private fun displayTextOnLongButtonClick(view: View) { val text = findViewById<TextView>(R.id.textResult) text.text = "Long Button Clicked !" }}
Android bridges the gap between the user interface and the back end code of the application through the concepts of event listeners and callback methods. The Android View class defines a set of event listeners, which can be registered on view objects. Each event listener also has associated with it a callback method. When an event takes place on a view in a user interface, that event is placed into an event queue and handled on a first-in, first-out basis by the Android runtime. If the view on which the event took place has registered a listener that matches the type of event, the corresponding callback method called. This code then performs any tasks required by the activity before returning. Some callback methods are required to return a Boolean value to point whether the event is consumed or needs to be passed on to any other event listeners registered on the view.
Android-Misc
Picked
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 1129,
"s": 54,
"text": "In Android, there’s quite a method to intercept the events from a user’s interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you’re going to use to compose your layout, you’ll notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs thereon object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method is named thereon object. However, to intercept this, you must extend the class and override the method. However, extending every View object to handle such an event would not be practical. This is why the View class also contains a set of nested interfaces with callbacks that you simply can far more easily define. These interfaces, called Event listeners, are your ticket to capturing the user interaction together with your UI."
},
{
"code": null,
"e": 1441,
"s": 1129,
"text": "For Example, if a button is to reply to a click event it must register to look at the .onClickListener event listener and implement the corresponding onClick() callback method. In an application when a button click event is detected, the Android framework will call the onClick() method of that particular view."
},
{
"code": null,
"e": 1776,
"s": 1441,
"text": "Event Listener is an interface within the View class that contains one call-back method. These methods are going to be called by the Android framework when the View which is registered with the listener is triggered by user interaction with the item in UI. Included in the event listener interfaces are the following callback methods:"
},
{
"code": null,
"e": 1784,
"s": 1776,
"text": "Methods"
},
{
"code": null,
"e": 1800,
"s": 1784,
"text": "Event Listeners"
},
{
"code": null,
"e": 1812,
"s": 1800,
"text": "Description"
},
{
"code": null,
"e": 1822,
"s": 1812,
"text": "onClick()"
},
{
"code": null,
"e": 1843,
"s": 1822,
"text": "View.OnClickListener"
},
{
"code": null,
"e": 2030,
"s": 1843,
"text": "This method is called when the user touches the item or focuses upon the item with the navigation-keys or trackball and presses the suitable “enter” key or presses down on the trackball."
},
{
"code": null,
"e": 2044,
"s": 2030,
"text": "onLongClick()"
},
{
"code": null,
"e": 2069,
"s": 2044,
"text": "View.OnLongClickListener"
},
{
"code": null,
"e": 2304,
"s": 2069,
"text": "This is called when the user either touches and holds the item, or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable “enter” key or presses and holds down on the trackball (for one second)."
},
{
"code": null,
"e": 2320,
"s": 2304,
"text": "onFocusChange()"
},
{
"code": null,
"e": 2347,
"s": 2320,
"text": "View.OnFocusChangeListener"
},
{
"code": null,
"e": 2454,
"s": 2347,
"text": "This is called when the user navigates onto or away from the item, using the navigation-keys or trackball."
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "onKey()"
},
{
"code": null,
"e": 2481,
"s": 2462,
"text": "View.OnKeyListener"
},
{
"code": null,
"e": 2587,
"s": 2481,
"text": "This is called when the user is focused on the item and presses or releases a hardware key on the device."
},
{
"code": null,
"e": 2597,
"s": 2587,
"text": "onTouch()"
},
{
"code": null,
"e": 2618,
"s": 2597,
"text": "View.OnTouchListener"
},
{
"code": null,
"e": 2782,
"s": 2618,
"text": " This is called when the user acts qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item)."
},
{
"code": null,
"e": 2804,
"s": 2782,
"text": "onCreateContextMenu()"
},
{
"code": null,
"e": 2837,
"s": 2804,
"text": "View.OnCreateContextMenuListener"
},
{
"code": null,
"e": 2932,
"s": 2837,
"text": "This is called when a Context Menu is being built (as the result of a sustained “long click”)."
},
{
"code": null,
"e": 2938,
"s": 2932,
"text": "Note:"
},
{
"code": null,
"e": 3342,
"s": 2938,
"text": "onClick() callback does not return any value. But onLongClick(), onKey(), onTouch() callback returns a boolean value that indicates that you simply have consumed the event and it should not be carried further; That is, return true to indicate that you have handled the event and it should stop here; return false if you’ve not handled it and/or the event should continue to any other on-click listeners."
},
{
"code": null,
"e": 3588,
"s": 3342,
"text": "Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. This example illustrates how to register an on-click listener for a Button "
},
{
"code": null,
"e": 3595,
"s": 3588,
"text": "Kotlin"
},
{
"code": "protected void onCreate(savedValues: Bundle) { ... val button: Button = findViewById(R.id.button) // Register the onClick listener button.setOnClickListener { view -> // do something when the button is clicked } ...}",
"e": 3838,
"s": 3595,
"text": null
},
{
"code": null,
"e": 4050,
"s": 3838,
"text": "Event Handlers are useful to define several callback methods when we are building custom components from view. Following are some of the commonly used callback methods for event handling in android applications."
},
{
"code": null,
"e": 4057,
"s": 4050,
"text": "Method"
},
{
"code": null,
"e": 4069,
"s": 4057,
"text": "Description"
},
{
"code": null,
"e": 4218,
"s": 4069,
"text": "We have learned about Event Listeners, Event Handlers, and their callback methods. Now we will see their implementations in our android application."
},
{
"code": null,
"e": 4352,
"s": 4218,
"text": "Let us see the way to implement Input Events in Android. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 4399,
"s": 4352,
"text": "Step 1: Create a new project in Android Studio"
},
{
"code": null,
"e": 4573,
"s": 4399,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio in Kotlin. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 4608,
"s": 4573,
"text": "Step 2: Working with the XML Files"
},
{
"code": null,
"e": 4956,
"s": 4608,
"text": "To design the UI, code is present under the res\\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 4960,
"s": 4956,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!-- This is the layout for the Button which user will click --> <Button android:id=\"@+id/btnClick\" android:layout_width=\"200dp\" android:layout_height=\"70dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"200dp\" android:text=\"CLICK ME!\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <!-- This is the layout for the textView, On Click of Button the text will appear on the screen --> <TextView android:id=\"@+id/textResult\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"50dp\" android:textColor=\"#86AD33\" android:textSize=\"25sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"@id/btnClick\" /> </LinearLayout>",
"e": 6127,
"s": 4960,
"text": null
},
{
"code": null,
"e": 6171,
"s": 6127,
"text": " Step 3: Working with the MainActivity File"
},
{
"code": null,
"e": 6294,
"s": 6171,
"text": "Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 6301,
"s": 6294,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Register OnClickListener for button // call Click Handler method findViewById<Button>(R.id.btnClick).setOnClickListener { displayTextOnButtonClick(it) } // Register OnLongClickListener for button // call Click Handler method // Return true to indicate that the event is consumed findViewById<Button>(R.id.btnClick).setOnLongClickListener { displayTextOnLongButtonClick(it) true } } // Click handler for the Click me button. // Display the text below Click me Button // Display text after Button click // It has No Return Value private fun displayTextOnButtonClick(view: View) { val text = findViewById<TextView>(R.id.textResult) text.text = \"Button Clicked !\" } // Click handler for the Click me button. // Display the text below Click me Button // Display text after Button click for a bit long time (1-2sec) private fun displayTextOnLongButtonClick(view: View) { val text = findViewById<TextView>(R.id.textResult) text.text = \"Long Button Clicked !\" }}",
"e": 7771,
"s": 6301,
"text": null
},
{
"code": null,
"e": 8652,
"s": 7771,
"text": "Android bridges the gap between the user interface and the back end code of the application through the concepts of event listeners and callback methods. The Android View class defines a set of event listeners, which can be registered on view objects. Each event listener also has associated with it a callback method. When an event takes place on a view in a user interface, that event is placed into an event queue and handled on a first-in, first-out basis by the Android runtime. If the view on which the event took place has registered a listener that matches the type of event, the corresponding callback method called. This code then performs any tasks required by the activity before returning. Some callback methods are required to return a Boolean value to point whether the event is consumed or needs to be passed on to any other event listeners registered on the view."
},
{
"code": null,
"e": 8665,
"s": 8652,
"text": "Android-Misc"
},
{
"code": null,
"e": 8672,
"s": 8665,
"text": "Picked"
},
{
"code": null,
"e": 8696,
"s": 8672,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8704,
"s": 8696,
"text": "Android"
},
{
"code": null,
"e": 8711,
"s": 8704,
"text": "Kotlin"
},
{
"code": null,
"e": 8730,
"s": 8711,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8738,
"s": 8730,
"text": "Android"
}
] |
Inheritance in Java - GeeksQuiz | 13 Oct, 2021
Java
1) Private methods are final.
2) Protected members are accessible within a package and
inherited classes outside the package.
3) Protected methods are final.
4) We cannot override private methods.
Base
Derived
Derived
Base
Base
Derived
Base
Derived
Base
Grandparent's Print()
Parent's Print()
Child's Print()
// Guess the output
// filename Main.java
class Grandparent {
public void Print() {
System.out.println("Grandparent's Print()");
}
}
class Parent extends Grandparent {
public void Print() {
super.Print();
System.out.println("Parent's Print()");
}
}
class Child extends Parent {
public void Print() {
super.Print();
System.out.println("Child's Print()");
}
}
class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
}
Complex number is (10.0 + 15.0i)
Complex number is SOME_GARBAGE
Complex number is Complex@8e2fb5
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. | [
{
"code": null,
"e": 29498,
"s": 29470,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 29503,
"s": 29498,
"text": "Java"
},
{
"code": null,
"e": 29706,
"s": 29503,
"text": "\n1) Private methods are final.\n2) Protected members are accessible within a package and \n inherited classes outside the package.\n3) Protected methods are final.\n4) We cannot override private methods. "
},
{
"code": null,
"e": 29727,
"s": 29706,
"text": "Base\nDerived\nDerived"
},
{
"code": null,
"e": 29745,
"s": 29727,
"text": "Base\nBase\nDerived"
},
{
"code": null,
"e": 29763,
"s": 29745,
"text": "Base\nDerived\nBase"
},
{
"code": null,
"e": 29818,
"s": 29763,
"text": "Grandparent's Print()\nParent's Print()\nChild's Print()"
},
{
"code": null,
"e": 30364,
"s": 29818,
"text": "// Guess the output\n// filename Main.java\nclass Grandparent {\n public void Print() {\n System.out.println(\"Grandparent's Print()\");\n }\n}\n \nclass Parent extends Grandparent {\n public void Print() {\n \tsuper.Print(); \n System.out.println(\"Parent's Print()\");\n }\n}\n \nclass Child extends Parent {\n public void Print() {\n super.Print(); \n System.out.println(\"Child's Print()\");\n }\n}\n \nclass Main {\n public static void main(String[] args) {\n Child c = new Child();\n c.Print();\n }\n}\n"
},
{
"code": null,
"e": 30397,
"s": 30364,
"text": "Complex number is (10.0 + 15.0i)"
},
{
"code": null,
"e": 30428,
"s": 30397,
"text": "Complex number is SOME_GARBAGE"
},
{
"code": null,
"e": 30461,
"s": 30428,
"text": "Complex number is Complex@8e2fb5"
}
] |
Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator) | 21 Oct, 2021
Prerequisite: Collection in Java Following are the 4 ways to retrieve any elements from a collection object:
For each loop is meant for traversing items in a collection.
// Iterating over collection 'c' using for-each
for (Element e: c)
System.out.println(e);
We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element e in elements”, here elements are the collection which stores Element type items.
Note:In Java 8 using lambda expressions we can simply replace for-each loop with
elements.forEach (e -> System.out.println(e) );
Using Cursors
Cursor is an interface and it is used to retrieve data from collection object, one by one. Cursor has 3 types, which are given below:
Iterator Interface: Iterator is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection.
// Iterating over collection 'c' using iterator
for (Iterator i = c.iterator(); i.hasNext(); )
System.out.println(i.next());
It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements.elements next(): This method returns the next elements in the iterator.void remove(): This method removes from the collection the last elements returned by the iterator.ListIterator Interface: It is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. This iterator is for list based collections. It has following important methods:booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction.booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction.element next(): This returns the next element in the list.element previous():This returns the previous element in the list.void remove(): This removes from the list the last elements that was returned by the next() or previous() methods.int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)EnumerationIterator Interface: The interface is useful to retrieve one by one the element. This iterator is based on data from Enumeration and has methods: booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not .element nextElement(): This returns the next element that is available in elements that is available in Enumeration
It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements.elements next(): This method returns the next elements in the iterator.void remove(): This method removes from the collection the last elements returned by the iterator.
boolean hasNext(): This method returns true if the iterator has more elements.
elements next(): This method returns the next elements in the iterator.
void remove(): This method removes from the collection the last elements returned by the iterator.
ListIterator Interface: It is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. This iterator is for list based collections. It has following important methods:booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction.booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction.element next(): This returns the next element in the list.element previous():This returns the previous element in the list.void remove(): This removes from the list the last elements that was returned by the next() or previous() methods.int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)
booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction.
booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction.
element next(): This returns the next element in the list.
element previous():This returns the previous element in the list.
void remove(): This removes from the list the last elements that was returned by the next() or previous() methods.
int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)
int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)
EnumerationIterator Interface: The interface is useful to retrieve one by one the element. This iterator is based on data from Enumeration and has methods: booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not .element nextElement(): This returns the next element that is available in elements that is available in Enumeration
booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not .
element nextElement(): This returns the next element that is available in elements that is available in Enumeration
Related Articles: Iterators in Java Iterator vs Foreach In JavaThis article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ManojbabuRTR
sagartomar9927
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 163,
"s": 52,
"text": "Prerequisite: Collection in Java Following are the 4 ways to retrieve any elements from a collection object: "
},
{
"code": null,
"e": 224,
"s": 163,
"text": "For each loop is meant for traversing items in a collection."
},
{
"code": null,
"e": 325,
"s": 224,
"text": "// Iterating over collection 'c' using for-each \n for (Element e: c)\n System.out.println(e);"
},
{
"code": null,
"e": 489,
"s": 325,
"text": "We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element e in elements”, here elements are the collection which stores Element type items."
},
{
"code": null,
"e": 570,
"s": 489,
"text": "Note:In Java 8 using lambda expressions we can simply replace for-each loop with"
},
{
"code": null,
"e": 618,
"s": 570,
"text": "elements.forEach (e -> System.out.println(e) );"
},
{
"code": null,
"e": 633,
"s": 618,
"text": " Using Cursors"
},
{
"code": null,
"e": 769,
"s": 633,
"text": "Cursor is an interface and it is used to retrieve data from collection object, one by one. Cursor has 3 types, which are given below: "
},
{
"code": null,
"e": 928,
"s": 769,
"text": "Iterator Interface: Iterator is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection."
},
{
"code": null,
"e": 1071,
"s": 928,
"text": " \n // Iterating over collection 'c' using iterator\n for (Iterator i = c.iterator(); i.hasNext(); ) \n System.out.println(i.next());"
},
{
"code": null,
"e": 2775,
"s": 1071,
"text": "It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements.elements next(): This method returns the next elements in the iterator.void remove(): This method removes from the collection the last elements returned by the iterator.ListIterator Interface: It is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. This iterator is for list based collections. It has following important methods:booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction.booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction.element next(): This returns the next element in the list.element previous():This returns the previous element in the list.void remove(): This removes from the list the last elements that was returned by the next() or previous() methods.int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)EnumerationIterator Interface: The interface is useful to retrieve one by one the element. This iterator is based on data from Enumeration and has methods: booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not .element nextElement(): This returns the next element that is available in elements that is available in Enumeration"
},
{
"code": null,
"e": 3041,
"s": 2775,
"text": "It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements.elements next(): This method returns the next elements in the iterator.void remove(): This method removes from the collection the last elements returned by the iterator."
},
{
"code": null,
"e": 3120,
"s": 3041,
"text": "boolean hasNext(): This method returns true if the iterator has more elements."
},
{
"code": null,
"e": 3192,
"s": 3120,
"text": "elements next(): This method returns the next elements in the iterator."
},
{
"code": null,
"e": 3291,
"s": 3192,
"text": "void remove(): This method removes from the collection the last elements returned by the iterator."
},
{
"code": null,
"e": 4366,
"s": 3291,
"text": "ListIterator Interface: It is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. This iterator is for list based collections. It has following important methods:booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction.booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction.element next(): This returns the next element in the list.element previous():This returns the previous element in the list.void remove(): This removes from the list the last elements that was returned by the next() or previous() methods.int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)"
},
{
"code": null,
"e": 4491,
"s": 4366,
"text": "booleanhasNext(): This returns true if the ListIterator has more elements when traversing the list in the forward direction."
},
{
"code": null,
"e": 4620,
"s": 4491,
"text": "booleanhasPrevious(): This returns true if the ListIterator has more elements when traversing the list in the reverse direction."
},
{
"code": null,
"e": 4679,
"s": 4620,
"text": "element next(): This returns the next element in the list."
},
{
"code": null,
"e": 4745,
"s": 4679,
"text": "element previous():This returns the previous element in the list."
},
{
"code": null,
"e": 4860,
"s": 4745,
"text": "void remove(): This removes from the list the last elements that was returned by the next() or previous() methods."
},
{
"code": null,
"e": 5032,
"s": 4860,
"text": "int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). (Returns list size if the list iterator is at the end of the list.)"
},
{
"code": null,
"e": 5211,
"s": 5032,
"text": "int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)"
},
{
"code": null,
"e": 5576,
"s": 5211,
"text": "EnumerationIterator Interface: The interface is useful to retrieve one by one the element. This iterator is based on data from Enumeration and has methods: booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not .element nextElement(): This returns the next element that is available in elements that is available in Enumeration"
},
{
"code": null,
"e": 5670,
"s": 5576,
"text": "booleanhasMoreElements(): This method tests if the Enumeration has any more elements or not ."
},
{
"code": null,
"e": 5786,
"s": 5670,
"text": "element nextElement(): This returns the next element that is available in elements that is available in Enumeration"
},
{
"code": null,
"e": 6242,
"s": 5786,
"text": "Related Articles: Iterators in Java Iterator vs Foreach In JavaThis article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 6255,
"s": 6242,
"text": "ManojbabuRTR"
},
{
"code": null,
"e": 6270,
"s": 6255,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6311,
"s": 6270,
"text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g"
},
{
"code": null,
"e": 6316,
"s": 6311,
"text": "Java"
},
{
"code": null,
"e": 6321,
"s": 6316,
"text": "Java"
}
] |
Django manage.py migrate command | Python | 26 Sep, 2019
According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations when to run them, and the common problems you might run into.
migrate is run through the following command for a Django project.
Python manage.py migrate
migrate executes those SQL commands in the database file. So after executing migrate all the tables of your installed apps are created in your database file.
You can confirm this by installing SQLite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command.
For example, if we make a model class-
from django.db import models class Person(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30)
The corresponding sql command after using makemigrations will be
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
and using above command, table will be created in the database when we use migrate.Migrate command is covered in next article.and now form terminal running following command will create table for this model in your database
Python manage.py migrate
Now if we check our database, a table with name geeks_geeksmodel is created,
Django-models
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Sep, 2019"
},
{
"code": null,
"e": 350,
"s": 28,
"text": "According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations when to run them, and the common problems you might run into."
},
{
"code": null,
"e": 417,
"s": 350,
"text": "migrate is run through the following command for a Django project."
},
{
"code": null,
"e": 444,
"s": 417,
"text": " Python manage.py migrate "
},
{
"code": null,
"e": 602,
"s": 444,
"text": "migrate executes those SQL commands in the database file. So after executing migrate all the tables of your installed apps are created in your database file."
},
{
"code": null,
"e": 764,
"s": 602,
"text": "You can confirm this by installing SQLite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command."
},
{
"code": null,
"e": 803,
"s": 764,
"text": "For example, if we make a model class-"
},
{
"code": "from django.db import models class Person(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30)",
"e": 960,
"s": 803,
"text": null
},
{
"code": null,
"e": 1025,
"s": 960,
"text": "The corresponding sql command after using makemigrations will be"
},
{
"code": null,
"e": 1159,
"s": 1025,
"text": "CREATE TABLE myapp_person (\n\"id\" serial NOT NULL PRIMARY KEY,\n\"first_name\" varchar(30) NOT NULL,\n\"last_name\" varchar(30) NOT NULL\n);\n"
},
{
"code": null,
"e": 1383,
"s": 1159,
"text": "and using above command, table will be created in the database when we use migrate.Migrate command is covered in next article.and now form terminal running following command will create table for this model in your database"
},
{
"code": null,
"e": 1409,
"s": 1383,
"text": " Python manage.py migrate"
},
{
"code": null,
"e": 1486,
"s": 1409,
"text": "Now if we check our database, a table with name geeks_geeksmodel is created,"
},
{
"code": null,
"e": 1500,
"s": 1486,
"text": "Django-models"
},
{
"code": null,
"e": 1507,
"s": 1500,
"text": "Python"
},
{
"code": null,
"e": 1605,
"s": 1507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1623,
"s": 1605,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1645,
"s": 1623,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1687,
"s": 1645,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1722,
"s": 1687,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1754,
"s": 1722,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1780,
"s": 1754,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1801,
"s": 1780,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1828,
"s": 1801,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1857,
"s": 1828,
"text": "*args and **kwargs in Python"
}
] |
NLP | Trigrams’n’Tags (TnT) Tagging | 05 Dec, 2019
TnT Tagger : It is a statistical tagger that works on second-order Markov models.
It is a very efficient part-of-speech tagger that can be trained on different languages and on any tagset.
For parameter generation, the component trains on tagged corpora. It incorporates different methods of smoothing and handling unknown words
Linear interpolation is used for smoothing, the respective weights are determined by deleted interpolation.
TnT tagger has different API than the normal taggers. One can explicitly use the train() method after creating it.
Code #1 : Using train() method
from nltk.tag import tntfrom nltk.corpus import treebank # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggertnt_tagging = tnt.TnT() # trainingtnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print ("Accuracy of TnT Tagging : ", a)
Output :
Accuracy of TnT Tagging : 0.8756313403842003
Understanding the working of TnT tagger :
It maintains the number ofinternal FreqDistConditionalFreqDist, which is based on the training data.
internal FreqDist
ConditionalFreqDist, which is based on the training data.
Frequency Distribution (FreqDist) counts the unigrams, bigrams and trigrams.
These frequencies are used for calculations of the probabilities of possible tags for each word.
TnT tagger uses all the ngram models together to choose the best tag instead of constructing a backoff chain of NgramTagger subclasses.
Based on the probabilities of each possible tag, it chooses the most likely model for entire sentence.
Code #2 : Using tagger for unknown words as ‘unk’
from nltk.tag import tntfrom nltk.corpus import treebankfrom nltk.tag import DefaultTagger # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggerunk = DefaultTagger('NN')tnt_tagging = tnt.TnT(unk = unk, Trained = True) # training tnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print ("Accuracy of TnT Tagging : ", a)
Output :
Accuracy of TnT Tagging : 0.892467083962875
unknown tagger’s tag() method is only called with a single word sentence.
TnT tagger can pass in a tagger for unknown words as unk.
One can pass in Trained = True, if this tagger is already trained.
Otherwise, it will call unk.train(data) with the same data one can pass into the train() method.
Controlling Beam Search :
Another parameter to modify for TnT is N i.e. it controls the no. of possible solutions the tagger maintains.
By defaults N = 1000.
Amount of memory will increase if increase the value of N, without any specific increase of accuracy.
Amount of memory will decrease if decrease the value of N, but can decrease the accuracy.
Code #3 : Using N = 100
from nltk.tag import tntfrom nltk.corpus import treebankfrom nltk.tag import DefaultTagger # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggertnt_tagger = tnt.TnT(N = 100) # training tnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print ("Accuracy of TnT Tagging : ", a)
Output :
Accuracy of TnT Tagging : 0.8756313403842003
shubham_singh
Natural-language-processing
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "TnT Tagger : It is a statistical tagger that works on second-order Markov models."
},
{
"code": null,
"e": 217,
"s": 110,
"text": "It is a very efficient part-of-speech tagger that can be trained on different languages and on any tagset."
},
{
"code": null,
"e": 357,
"s": 217,
"text": "For parameter generation, the component trains on tagged corpora. It incorporates different methods of smoothing and handling unknown words"
},
{
"code": null,
"e": 465,
"s": 357,
"text": "Linear interpolation is used for smoothing, the respective weights are determined by deleted interpolation."
},
{
"code": null,
"e": 580,
"s": 465,
"text": "TnT tagger has different API than the normal taggers. One can explicitly use the train() method after creating it."
},
{
"code": null,
"e": 611,
"s": 580,
"text": "Code #1 : Using train() method"
},
{
"code": "from nltk.tag import tntfrom nltk.corpus import treebank # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggertnt_tagging = tnt.TnT() # trainingtnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print (\"Accuracy of TnT Tagging : \", a)",
"e": 975,
"s": 611,
"text": null
},
{
"code": null,
"e": 984,
"s": 975,
"text": "Output :"
},
{
"code": null,
"e": 1030,
"s": 984,
"text": "Accuracy of TnT Tagging : 0.8756313403842003\n"
},
{
"code": null,
"e": 1072,
"s": 1030,
"text": "Understanding the working of TnT tagger :"
},
{
"code": null,
"e": 1173,
"s": 1072,
"text": "It maintains the number ofinternal FreqDistConditionalFreqDist, which is based on the training data."
},
{
"code": null,
"e": 1191,
"s": 1173,
"text": "internal FreqDist"
},
{
"code": null,
"e": 1249,
"s": 1191,
"text": "ConditionalFreqDist, which is based on the training data."
},
{
"code": null,
"e": 1326,
"s": 1249,
"text": "Frequency Distribution (FreqDist) counts the unigrams, bigrams and trigrams."
},
{
"code": null,
"e": 1423,
"s": 1326,
"text": "These frequencies are used for calculations of the probabilities of possible tags for each word."
},
{
"code": null,
"e": 1559,
"s": 1423,
"text": "TnT tagger uses all the ngram models together to choose the best tag instead of constructing a backoff chain of NgramTagger subclasses."
},
{
"code": null,
"e": 1662,
"s": 1559,
"text": "Based on the probabilities of each possible tag, it chooses the most likely model for entire sentence."
},
{
"code": null,
"e": 1712,
"s": 1662,
"text": "Code #2 : Using tagger for unknown words as ‘unk’"
},
{
"code": "from nltk.tag import tntfrom nltk.corpus import treebankfrom nltk.tag import DefaultTagger # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggerunk = DefaultTagger('NN')tnt_tagging = tnt.TnT(unk = unk, Trained = True) # training tnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print (\"Accuracy of TnT Tagging : \", a)",
"e": 2161,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2161,
"text": "Output :"
},
{
"code": null,
"e": 2215,
"s": 2170,
"text": "Accuracy of TnT Tagging : 0.892467083962875\n"
},
{
"code": null,
"e": 2289,
"s": 2215,
"text": "unknown tagger’s tag() method is only called with a single word sentence."
},
{
"code": null,
"e": 2347,
"s": 2289,
"text": "TnT tagger can pass in a tagger for unknown words as unk."
},
{
"code": null,
"e": 2414,
"s": 2347,
"text": "One can pass in Trained = True, if this tagger is already trained."
},
{
"code": null,
"e": 2511,
"s": 2414,
"text": "Otherwise, it will call unk.train(data) with the same data one can pass into the train() method."
},
{
"code": null,
"e": 2537,
"s": 2511,
"text": "Controlling Beam Search :"
},
{
"code": null,
"e": 2647,
"s": 2537,
"text": "Another parameter to modify for TnT is N i.e. it controls the no. of possible solutions the tagger maintains."
},
{
"code": null,
"e": 2669,
"s": 2647,
"text": "By defaults N = 1000."
},
{
"code": null,
"e": 2771,
"s": 2669,
"text": "Amount of memory will increase if increase the value of N, without any specific increase of accuracy."
},
{
"code": null,
"e": 2861,
"s": 2771,
"text": "Amount of memory will decrease if decrease the value of N, but can decrease the accuracy."
},
{
"code": null,
"e": 2885,
"s": 2861,
"text": "Code #3 : Using N = 100"
},
{
"code": "from nltk.tag import tntfrom nltk.corpus import treebankfrom nltk.tag import DefaultTagger # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] # initializing taggertnt_tagger = tnt.TnT(N = 100) # training tnt_tagging.train(train_data) # evaluatinga = tnt_tagging.evaluate(test_data) print (\"Accuracy of TnT Tagging : \", a)",
"e": 3290,
"s": 2885,
"text": null
},
{
"code": null,
"e": 3299,
"s": 3290,
"text": "Output :"
},
{
"code": null,
"e": 3345,
"s": 3299,
"text": "Accuracy of TnT Tagging : 0.8756313403842003\n"
},
{
"code": null,
"e": 3359,
"s": 3345,
"text": "shubham_singh"
},
{
"code": null,
"e": 3387,
"s": 3359,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 3399,
"s": 3387,
"text": "Python-nltk"
},
{
"code": null,
"e": 3406,
"s": 3399,
"text": "Python"
}
] |
JP Morgan Chase Interview Experience | 12 Dec, 2018
JP Morgan visited our campus for full time hiring for quant research and MGG(Model Governance Group). I applied for the MGG role.
Test 2 sectionsQuant – 35 minutes : Problems on probability, expected values, etc. Similar to ones in 50 challenging, heard on the street and BrainstellarCoding – 2 problems — https://leetcode.com/problems/letter-combinations-of-a-phone-number/https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
Interview
Round 1 : He asked me to code a simple problem. Given
1
2 3
4 5 6
7 8 9 10, and so on.
Now Given n, that is the last number(10 in this case), we need to print the complete pattern
This was followed by questions from resume, how Google Maps work(i.e. How do they provide real time traffic data), some questions on Python, like difference between list and tuple? Also some discussions on interests, family background, etc. Chill discussion
2. Round 2 : Write a program to print Fibonacci numbers and then an extended version of the same.https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
Again, some problems on Python, like https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python
A puzzle, https://www.geeksforgeeks.org/puzzle-26-know-average-salary-without-disclosing-individual-salaries/
3. Round 3 : HR – Interests, Do you want to go for higher studies or MBA?, Why JPMC?
4. Round 4 : A puzzle : https://brainstellar.com/puzzles/202
5. Round 5 : Few HR questions, got the offer!
JP Morgan
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience SDE-2 (3 Years Experienced)
Amazon Interview Experience for SDE 1
Google Interview Questions
Nagarro Interview Experience | On-Campus 2021
Interview Experience League 2022
Amazon Interview Experience for SDE-1
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Nagarro Interview Experience
Tejas Networks Interview Experience for R&D Engineer
Zoho Interview | Set 3 (Off-Campus) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2018"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "JP Morgan visited our campus for full time hiring for quant research and MGG(Model Governance Group). I applied for the MGG role."
},
{
"code": null,
"e": 472,
"s": 158,
"text": "Test 2 sectionsQuant – 35 minutes : Problems on probability, expected values, etc. Similar to ones in 50 challenging, heard on the street and BrainstellarCoding – 2 problems — https://leetcode.com/problems/letter-combinations-of-a-phone-number/https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/"
},
{
"code": null,
"e": 482,
"s": 472,
"text": "Interview"
},
{
"code": null,
"e": 536,
"s": 482,
"text": "Round 1 : He asked me to code a simple problem. Given"
},
{
"code": null,
"e": 589,
"s": 536,
"text": " 1\n\n 2 3\n\n 4 5 6\n\n 7 8 9 10, and so on."
},
{
"code": null,
"e": 682,
"s": 589,
"text": "Now Given n, that is the last number(10 in this case), we need to print the complete pattern"
},
{
"code": null,
"e": 940,
"s": 682,
"text": "This was followed by questions from resume, how Google Maps work(i.e. How do they provide real time traffic data), some questions on Python, like difference between list and tuple? Also some discussions on interests, family background, etc. Chill discussion"
},
{
"code": null,
"e": 1095,
"s": 940,
"text": "2. Round 2 : Write a program to print Fibonacci numbers and then an extended version of the same.https://www.geeksforgeeks.org/count-ways-reach-nth-stair/"
},
{
"code": null,
"e": 1221,
"s": 1095,
"text": "Again, some problems on Python, like https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python"
},
{
"code": null,
"e": 1331,
"s": 1221,
"text": "A puzzle, https://www.geeksforgeeks.org/puzzle-26-know-average-salary-without-disclosing-individual-salaries/"
},
{
"code": null,
"e": 1416,
"s": 1331,
"text": "3. Round 3 : HR – Interests, Do you want to go for higher studies or MBA?, Why JPMC?"
},
{
"code": null,
"e": 1477,
"s": 1416,
"text": "4. Round 4 : A puzzle : https://brainstellar.com/puzzles/202"
},
{
"code": null,
"e": 1523,
"s": 1477,
"text": "5. Round 5 : Few HR questions, got the offer!"
},
{
"code": null,
"e": 1533,
"s": 1523,
"text": "JP Morgan"
},
{
"code": null,
"e": 1543,
"s": 1533,
"text": "On-Campus"
},
{
"code": null,
"e": 1565,
"s": 1543,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1663,
"s": 1565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1719,
"s": 1663,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 1757,
"s": 1719,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 1784,
"s": 1757,
"text": "Google Interview Questions"
},
{
"code": null,
"e": 1830,
"s": 1784,
"text": "Nagarro Interview Experience | On-Campus 2021"
},
{
"code": null,
"e": 1863,
"s": 1830,
"text": "Interview Experience League 2022"
},
{
"code": null,
"e": 1901,
"s": 1863,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 1967,
"s": 1901,
"text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)"
},
{
"code": null,
"e": 1996,
"s": 1967,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 2049,
"s": 1996,
"text": "Tejas Networks Interview Experience for R&D Engineer"
}
] |
Django App Model – Python manage.py makemigrations command | 26 Sep, 2019
According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.
makemigrations are run through the following command
Python manage.py makemigrations
If the above commands says no changes detected, You can also do it for individual apps.For example if you have 10 apps named a, b, c, d, e, f, g, h, i, j. You can run makemigrations individually for these apps.
Python manage.py makemigrations a
Python manage.py makemigrations b
Python manage.py makemigrations c
and so on.
makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps’ model which you add in installed apps. It does not execute those commands in your database file. So tables are not created after makemigrations.
After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which have been generated by makemigrations.
For example, if we make a model class-
from django.db import models class Person(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30)
The corresponding sql command after using makemigrations will be
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
and using above command, table will be created in the database when we use migrate.
Django-models
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Sep, 2019"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into."
},
{
"code": null,
"e": 404,
"s": 351,
"text": "makemigrations are run through the following command"
},
{
"code": null,
"e": 436,
"s": 404,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 647,
"s": 436,
"text": "If the above commands says no changes detected, You can also do it for individual apps.For example if you have 10 apps named a, b, c, d, e, f, g, h, i, j. You can run makemigrations individually for these apps."
},
{
"code": null,
"e": 682,
"s": 647,
"text": "Python manage.py makemigrations a "
},
{
"code": null,
"e": 717,
"s": 682,
"text": "Python manage.py makemigrations b "
},
{
"code": null,
"e": 752,
"s": 717,
"text": "Python manage.py makemigrations c "
},
{
"code": null,
"e": 763,
"s": 752,
"text": "and so on."
},
{
"code": null,
"e": 1066,
"s": 763,
"text": "makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps’ model which you add in installed apps. It does not execute those commands in your database file. So tables are not created after makemigrations."
},
{
"code": null,
"e": 1221,
"s": 1066,
"text": "After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which have been generated by makemigrations."
},
{
"code": null,
"e": 1260,
"s": 1221,
"text": "For example, if we make a model class-"
},
{
"code": "from django.db import models class Person(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30)",
"e": 1417,
"s": 1260,
"text": null
},
{
"code": null,
"e": 1482,
"s": 1417,
"text": "The corresponding sql command after using makemigrations will be"
},
{
"code": null,
"e": 1616,
"s": 1482,
"text": "CREATE TABLE myapp_person (\n\"id\" serial NOT NULL PRIMARY KEY,\n\"first_name\" varchar(30) NOT NULL,\n\"last_name\" varchar(30) NOT NULL\n);\n"
},
{
"code": null,
"e": 1700,
"s": 1616,
"text": "and using above command, table will be created in the database when we use migrate."
},
{
"code": null,
"e": 1714,
"s": 1700,
"text": "Django-models"
},
{
"code": null,
"e": 1721,
"s": 1714,
"text": "Python"
}
] |
What is the Difference between Interactive and Script Mode in Python Programming? | 05 Aug, 2021
Python is a programming language that lets you work quickly and integrate systems more efficiently. It is a widely-used general-purpose, high-level programming language. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode
2. Script mode
In this article, we’ll get to know what these modes are and how they differ from each other.
Interactive etymologically means “working simultaneously and creating impact of our work on the other’s work”. Interactive mode is based on this ideology only. In the interactive mode as we enter a command and press enter, the very next step we get the output. The output of the code in the interactive mode is influenced by the last command we give. Interactive mode is very convenient for writing very short lines of code. In python is it also known as REPL which stands for Read Evaluate Print Loop. Here, the read function reads the input from the user and stores it in memory. Eval function evaluates the input to get the desired output. Print function outputs the evaluated result. The loop function executes the loop during the execution of the entire program and terminates when our program ends. This mode is very suitable for beginners in programming as it helps them evaluate their code line by line and understand the execution of code well.
How to run python code in Interactive mode?
In order to run our program in the interactive mode, we can use command prompt in windows, terminal in Linux, and macOS. Let us see understand the execution of python code in the command prompt with the help of an example:
Example 1:
To run python in command prompt type “python”. Then simply type the Python statement on >>> prompt. As we type and press enter we can see the output in the very next line.
Python3
# Python program to display "Hello GFG"print("Hello GFG")
Output:
Example 2
Let us take another example in which we need to perform addition on two numbers and we want to get its output. We will declare two variables a and b and store the result in a third variable c. We further print c. All this is done in the command prompt.
Python3
# Python program to add two numbersa = 2 b = 3 # Adding a and b and storing result in cc = a + b # Printing value of cprint(c)
Output:
We can see the desired output on the screen. This kind of program is a very short program and can be easily executed in interactive mode.
Example 3:
In this example, we will multiply two numbers and take the numbers as an input for two users. You will see that when you execute the input command, you need to give input in the very next line, i.e. code is interpreted line by line.
Python3
# Python program to take input from user # Taking input from usera = int(input()) # Taking input from userb = int(input()) # Multiplying and storing resultc = a * b # Printing the resultprint(c)
Output:
Disadvantages of interactive mode
The interactive mode is not suitable for large programs.
The interactive mode doesn’t save the statements. Once we make a program it is for that time itself, we cannot use it in the future. In order to use it in the future, we need to retype all the statements.
Editing the code written in interactive mode is a tedious task. We need to revisit all our previous commands and if still, we could not edit we need to type everything again.
Script etymologically means a system of writing. In the script mode, a python program can be written in a file. This file can then be saved and executed using the command prompt. We can view the code at any time by opening the file and editing becomes quite easy as we can open and view the entire code as many times as we want. Script mode is very suitable for writing long pieces of code. It is much preferred over interactive mode by experts in the program. The file made in the script made is by default saved in the Python installation folder and the extension to save a python file is “.py”.
How to run python code in script mode?
In order to run a code in script mode follow the following steps.
Step 1: Make a file using a text editor. You can use any text editor of your choice(Here I use notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
Let us understand these steps with the help of the examples:
Example 1:
In order to execute “Hello gfg” using script mode we first make a file and save it.
Now we use the command prompt to execute this file.
Output:
Example 2:
Our second example is the same addition of two numbers as we saw in the interactive mode. But in this case, we first make a file and write the entire code in that file. We then save it and execute it using the command prompt.
Output:
Example 3:
In this example, we write the code for multiplying two numbers. And the numbers which are to be multiplied are taken by the user as an input. In the interactive mode, we saw that as we write the command so does it asks for the input in the very next line. But in script mode we first code the entire program save and then run it in command prompt. The python interpreter executes the code line by line and gives us the result accordingly.
In this example, we see that the whole program is compiled and the code is executed line by line. The output on the shell is entirely different from the interactive mode.
Interactive Mode
Script Mode
Picked
Class 11
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Geometric Series
Steps in Formation of a Company
Importance of Chemistry in Everyday Life
Introduction to Boolean Logic
Nature and Types of Services
How to Align Text in HTML?
Libraries in Python
What are Different Output Devices?
Generations of Computers - Computer Fundamentals | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 445,
"s": 52,
"text": "Python is a programming language that lets you work quickly and integrate systems more efficiently. It is a widely-used general-purpose, high-level programming language. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. In the Python programming language, there are two ways in which we can run our code:"
},
{
"code": null,
"e": 465,
"s": 445,
"text": "1. Interactive mode"
},
{
"code": null,
"e": 480,
"s": 465,
"text": "2. Script mode"
},
{
"code": null,
"e": 573,
"s": 480,
"text": "In this article, we’ll get to know what these modes are and how they differ from each other."
},
{
"code": null,
"e": 1527,
"s": 573,
"text": "Interactive etymologically means “working simultaneously and creating impact of our work on the other’s work”. Interactive mode is based on this ideology only. In the interactive mode as we enter a command and press enter, the very next step we get the output. The output of the code in the interactive mode is influenced by the last command we give. Interactive mode is very convenient for writing very short lines of code. In python is it also known as REPL which stands for Read Evaluate Print Loop. Here, the read function reads the input from the user and stores it in memory. Eval function evaluates the input to get the desired output. Print function outputs the evaluated result. The loop function executes the loop during the execution of the entire program and terminates when our program ends. This mode is very suitable for beginners in programming as it helps them evaluate their code line by line and understand the execution of code well."
},
{
"code": null,
"e": 1571,
"s": 1527,
"text": "How to run python code in Interactive mode?"
},
{
"code": null,
"e": 1794,
"s": 1571,
"text": "In order to run our program in the interactive mode, we can use command prompt in windows, terminal in Linux, and macOS. Let us see understand the execution of python code in the command prompt with the help of an example:"
},
{
"code": null,
"e": 1805,
"s": 1794,
"text": "Example 1:"
},
{
"code": null,
"e": 1978,
"s": 1805,
"text": "To run python in command prompt type “python”. Then simply type the Python statement on >>> prompt. As we type and press enter we can see the output in the very next line."
},
{
"code": null,
"e": 1986,
"s": 1978,
"text": "Python3"
},
{
"code": "# Python program to display \"Hello GFG\"print(\"Hello GFG\")",
"e": 2044,
"s": 1986,
"text": null
},
{
"code": null,
"e": 2052,
"s": 2044,
"text": "Output:"
},
{
"code": null,
"e": 2062,
"s": 2052,
"text": "Example 2"
},
{
"code": null,
"e": 2315,
"s": 2062,
"text": "Let us take another example in which we need to perform addition on two numbers and we want to get its output. We will declare two variables a and b and store the result in a third variable c. We further print c. All this is done in the command prompt."
},
{
"code": null,
"e": 2323,
"s": 2315,
"text": "Python3"
},
{
"code": "# Python program to add two numbersa = 2 b = 3 # Adding a and b and storing result in cc = a + b # Printing value of cprint(c) ",
"e": 2454,
"s": 2323,
"text": null
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "Output:"
},
{
"code": null,
"e": 2600,
"s": 2462,
"text": "We can see the desired output on the screen. This kind of program is a very short program and can be easily executed in interactive mode."
},
{
"code": null,
"e": 2611,
"s": 2600,
"text": "Example 3:"
},
{
"code": null,
"e": 2844,
"s": 2611,
"text": "In this example, we will multiply two numbers and take the numbers as an input for two users. You will see that when you execute the input command, you need to give input in the very next line, i.e. code is interpreted line by line."
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "Python3"
},
{
"code": "# Python program to take input from user # Taking input from usera = int(input()) # Taking input from userb = int(input()) # Multiplying and storing resultc = a * b # Printing the resultprint(c) ",
"e": 3055,
"s": 2852,
"text": null
},
{
"code": null,
"e": 3063,
"s": 3055,
"text": "Output:"
},
{
"code": null,
"e": 3097,
"s": 3063,
"text": "Disadvantages of interactive mode"
},
{
"code": null,
"e": 3154,
"s": 3097,
"text": "The interactive mode is not suitable for large programs."
},
{
"code": null,
"e": 3359,
"s": 3154,
"text": "The interactive mode doesn’t save the statements. Once we make a program it is for that time itself, we cannot use it in the future. In order to use it in the future, we need to retype all the statements."
},
{
"code": null,
"e": 3534,
"s": 3359,
"text": "Editing the code written in interactive mode is a tedious task. We need to revisit all our previous commands and if still, we could not edit we need to type everything again."
},
{
"code": null,
"e": 4132,
"s": 3534,
"text": "Script etymologically means a system of writing. In the script mode, a python program can be written in a file. This file can then be saved and executed using the command prompt. We can view the code at any time by opening the file and editing becomes quite easy as we can open and view the entire code as many times as we want. Script mode is very suitable for writing long pieces of code. It is much preferred over interactive mode by experts in the program. The file made in the script made is by default saved in the Python installation folder and the extension to save a python file is “.py”."
},
{
"code": null,
"e": 4171,
"s": 4132,
"text": "How to run python code in script mode?"
},
{
"code": null,
"e": 4237,
"s": 4171,
"text": "In order to run a code in script mode follow the following steps."
},
{
"code": null,
"e": 4342,
"s": 4237,
"text": "Step 1: Make a file using a text editor. You can use any text editor of your choice(Here I use notepad)."
},
{
"code": null,
"e": 4410,
"s": 4342,
"text": "Step 2: After writing the code save the file using “.py” extension."
},
{
"code": null,
"e": 4506,
"s": 4410,
"text": "Step 3: Now open the command prompt and command directory to the one where your file is stored."
},
{
"code": null,
"e": 4557,
"s": 4506,
"text": "Step 4: Type python “filename.py” and press enter."
},
{
"code": null,
"e": 4613,
"s": 4557,
"text": "Step 5: You will see the output on your command prompt."
},
{
"code": null,
"e": 4674,
"s": 4613,
"text": "Let us understand these steps with the help of the examples:"
},
{
"code": null,
"e": 4685,
"s": 4674,
"text": "Example 1:"
},
{
"code": null,
"e": 4769,
"s": 4685,
"text": "In order to execute “Hello gfg” using script mode we first make a file and save it."
},
{
"code": null,
"e": 4821,
"s": 4769,
"text": "Now we use the command prompt to execute this file."
},
{
"code": null,
"e": 4829,
"s": 4821,
"text": "Output:"
},
{
"code": null,
"e": 4840,
"s": 4829,
"text": "Example 2:"
},
{
"code": null,
"e": 5067,
"s": 4840,
"text": "Our second example is the same addition of two numbers as we saw in the interactive mode. But in this case, we first make a file and write the entire code in that file. We then save it and execute it using the command prompt. "
},
{
"code": null,
"e": 5075,
"s": 5067,
"text": "Output:"
},
{
"code": null,
"e": 5086,
"s": 5075,
"text": "Example 3:"
},
{
"code": null,
"e": 5525,
"s": 5086,
"text": "In this example, we write the code for multiplying two numbers. And the numbers which are to be multiplied are taken by the user as an input. In the interactive mode, we saw that as we write the command so does it asks for the input in the very next line. But in script mode we first code the entire program save and then run it in command prompt. The python interpreter executes the code line by line and gives us the result accordingly."
},
{
"code": null,
"e": 5696,
"s": 5525,
"text": "In this example, we see that the whole program is compiled and the code is executed line by line. The output on the shell is entirely different from the interactive mode."
},
{
"code": null,
"e": 5714,
"s": 5696,
"text": "Interactive Mode "
},
{
"code": null,
"e": 5727,
"s": 5714,
"text": "Script Mode "
},
{
"code": null,
"e": 5734,
"s": 5727,
"text": "Picked"
},
{
"code": null,
"e": 5743,
"s": 5734,
"text": "Class 11"
},
{
"code": null,
"e": 5759,
"s": 5743,
"text": "School Learning"
},
{
"code": null,
"e": 5778,
"s": 5759,
"text": "School Programming"
},
{
"code": null,
"e": 5876,
"s": 5778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5893,
"s": 5876,
"text": "Geometric Series"
},
{
"code": null,
"e": 5925,
"s": 5893,
"text": "Steps in Formation of a Company"
},
{
"code": null,
"e": 5966,
"s": 5925,
"text": "Importance of Chemistry in Everyday Life"
},
{
"code": null,
"e": 5996,
"s": 5966,
"text": "Introduction to Boolean Logic"
},
{
"code": null,
"e": 6025,
"s": 5996,
"text": "Nature and Types of Services"
},
{
"code": null,
"e": 6052,
"s": 6025,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 6072,
"s": 6052,
"text": "Libraries in Python"
},
{
"code": null,
"e": 6107,
"s": 6072,
"text": "What are Different Output Devices?"
}
] |
StringBuilder replace() in Java with Examples | 10 Dec, 2019
The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. At first, the characters of substring are removed and the string passed as parameters are inserted in place of those characters.Syntax:
public StringBuilder replace?(int start, int end, String str)
Parameters:This method accepts three parameters:
start – Integer type value which refers to the starting index.end – Integer type value which refers to the ending index.str – String type value which refer to the String that will replace previous contents.
start – Integer type value which refers to the starting index.
end – Integer type value which refers to the ending index.
str – String type value which refer to the String that will replace previous contents.
Returns:This method returns StringBuilder object after successful replacement of characters.Exception:If the start is negative, greater than length(), or greater than end then StringIndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuilder.replace() method:Example 1:
// Java program to demonstrate// the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("String = " + str.toString()); // replace Character from index 1 to 7 by "e are " StringBuilder strReturn = str.replace(1, 7, "e are "); // print string System.out.println("After Replace() String = " + strReturn.toString()); }}
Output:
String = WelcomeGeeks
After Replace() String = We are Geeks
Example 2:
// Java program to demonstrate// the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Tony Stark will die"); // print string System.out.println("String = " + str.toString()); // replace Character from index 15 to 16 by " not " StringBuilder strReturn = str.replace(15, 16, " not "); // print string System.out.println("After Replace() String = " + strReturn.toString()); }}
Output:
String = Tony Stark will die
After Replace() String = Tony Stark will not die
Example 3: When negative index is passed:
// Java program to demonstrate// Exception thrown by the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Tony Stark"); try { // replace Character from index -15 to 16 by "Captain America" StringBuilder strReturn = str.replace(-15, 16, "Captain America"); } catch (Exception e) { e.printStackTrace(); } }}
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: -15
at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851)
at java.lang.StringBuilder.replace(StringBuilder.java:262)
at GFG.main(File.java:17)
Example 4: When start index passed is greater than end index:
// Java program to demonstrate// Exception thrown by the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Tony Stark"); try { // replace Character from index 5 to 3 by "Captain America" StringBuilder strReturn = str.replace(5, 3, "Captain America"); } catch (Exception e) { e.printStackTrace(); } }}
Output:
java.lang.StringIndexOutOfBoundsException: start > end
at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:855)
at java.lang.StringBuilder.replace(StringBuilder.java:262)
at GFG.main(File.java:17)
References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#replace(int, int, java.lang.String)
nidhi_biet
Java-Functions
Java-StringBuilder
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": "\n10 Dec, 2019"
},
{
"code": null,
"e": 500,
"s": 28,
"text": "The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. At first, the characters of substring are removed and the string passed as parameters are inserted in place of those characters.Syntax:"
},
{
"code": null,
"e": 562,
"s": 500,
"text": "public StringBuilder replace?(int start, int end, String str)"
},
{
"code": null,
"e": 611,
"s": 562,
"text": "Parameters:This method accepts three parameters:"
},
{
"code": null,
"e": 818,
"s": 611,
"text": "start – Integer type value which refers to the starting index.end – Integer type value which refers to the ending index.str – String type value which refer to the String that will replace previous contents."
},
{
"code": null,
"e": 881,
"s": 818,
"text": "start – Integer type value which refers to the starting index."
},
{
"code": null,
"e": 940,
"s": 881,
"text": "end – Integer type value which refers to the ending index."
},
{
"code": null,
"e": 1027,
"s": 940,
"text": "str – String type value which refer to the String that will replace previous contents."
},
{
"code": null,
"e": 1236,
"s": 1027,
"text": "Returns:This method returns StringBuilder object after successful replacement of characters.Exception:If the start is negative, greater than length(), or greater than end then StringIndexOutOfBoundsException."
},
{
"code": null,
"e": 1318,
"s": 1236,
"text": "Below programs illustrate the java.lang.StringBuilder.replace() method:Example 1:"
},
{
"code": "// Java program to demonstrate// the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"String = \" + str.toString()); // replace Character from index 1 to 7 by \"e are \" StringBuilder strReturn = str.replace(1, 7, \"e are \"); // print string System.out.println(\"After Replace() String = \" + strReturn.toString()); }}",
"e": 1956,
"s": 1318,
"text": null
},
{
"code": null,
"e": 1964,
"s": 1956,
"text": "Output:"
},
{
"code": null,
"e": 2025,
"s": 1964,
"text": "String = WelcomeGeeks\nAfter Replace() String = We are Geeks\n"
},
{
"code": null,
"e": 2036,
"s": 2025,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Tony Stark will die\"); // print string System.out.println(\"String = \" + str.toString()); // replace Character from index 15 to 16 by \" not \" StringBuilder strReturn = str.replace(15, 16, \" not \"); // print string System.out.println(\"After Replace() String = \" + strReturn.toString()); }}",
"e": 2683,
"s": 2036,
"text": null
},
{
"code": null,
"e": 2691,
"s": 2683,
"text": "Output:"
},
{
"code": null,
"e": 2770,
"s": 2691,
"text": "String = Tony Stark will die\nAfter Replace() String = Tony Stark will not die\n"
},
{
"code": null,
"e": 2812,
"s": 2770,
"text": "Example 3: When negative index is passed:"
},
{
"code": "// Java program to demonstrate// Exception thrown by the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Tony Stark\"); try { // replace Character from index -15 to 16 by \"Captain America\" StringBuilder strReturn = str.replace(-15, 16, \"Captain America\"); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 3356,
"s": 2812,
"text": null
},
{
"code": null,
"e": 3364,
"s": 3356,
"text": "Output:"
},
{
"code": null,
"e": 3611,
"s": 3364,
"text": "java.lang.StringIndexOutOfBoundsException: String index out of range: -15\n at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851)\n at java.lang.StringBuilder.replace(StringBuilder.java:262)\n at GFG.main(File.java:17)\n"
},
{
"code": null,
"e": 3673,
"s": 3611,
"text": "Example 4: When start index passed is greater than end index:"
},
{
"code": "// Java program to demonstrate// Exception thrown by the replace() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Tony Stark\"); try { // replace Character from index 5 to 3 by \"Captain America\" StringBuilder strReturn = str.replace(5, 3, \"Captain America\"); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 4211,
"s": 3673,
"text": null
},
{
"code": null,
"e": 4219,
"s": 4211,
"text": "Output:"
},
{
"code": null,
"e": 4447,
"s": 4219,
"text": "java.lang.StringIndexOutOfBoundsException: start > end\n at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:855)\n at java.lang.StringBuilder.replace(StringBuilder.java:262)\n at GFG.main(File.java:17)\n"
},
{
"code": null,
"e": 4566,
"s": 4447,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#replace(int, int, java.lang.String)"
},
{
"code": null,
"e": 4577,
"s": 4566,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4592,
"s": 4577,
"text": "Java-Functions"
},
{
"code": null,
"e": 4611,
"s": 4592,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 4616,
"s": 4611,
"text": "Java"
},
{
"code": null,
"e": 4621,
"s": 4616,
"text": "Java"
}
] |
Python Program for 0-1 Knapsack Problem | 23 Oct, 2019
# A naive recursive implementation of 0-1 Knapsack Problem # Returns the maximum value that can be put in a knapsack of# capacity Wdef knapSack(W, wt, val, n): # Base Case if n == 0 or W == 0 : return 0 # If weight of the nth item is more than Knapsack of capacity # W, then this item cannot be included in the optimal solution if (wt[n-1] > W): return knapSack(W, wt, val, n-1) # return the maximum of two cases: # (1) nth item included # (2) not included else: return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) # end of function knapSack # To test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print knapSack(W, wt, val, n) # This code is contributed by Nikhil Kumar Singh
220
# A Dynamic Programming based Python # Program for 0-1 Knapsack problem# Returns the maximum value that can # be put in a knapsack of capacity Wdef knapSack(W, wt, val, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table K[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] # Driver program to test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print(knapSack(W, wt, val, n)) # This code is contributed by Bhavya Jain
220
Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!
knapsack
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Oct, 2019"
},
{
"code": "# A naive recursive implementation of 0-1 Knapsack Problem # Returns the maximum value that can be put in a knapsack of# capacity Wdef knapSack(W, wt, val, n): # Base Case if n == 0 or W == 0 : return 0 # If weight of the nth item is more than Knapsack of capacity # W, then this item cannot be included in the optimal solution if (wt[n-1] > W): return knapSack(W, wt, val, n-1) # return the maximum of two cases: # (1) nth item included # (2) not included else: return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) # end of function knapSack # To test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print knapSack(W, wt, val, n) # This code is contributed by Nikhil Kumar Singh",
"e": 862,
"s": 54,
"text": null
},
{
"code": null,
"e": 867,
"s": 862,
"text": "220\n"
},
{
"code": "# A Dynamic Programming based Python # Program for 0-1 Knapsack problem# Returns the maximum value that can # be put in a knapsack of capacity Wdef knapSack(W, wt, val, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table K[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] # Driver program to test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print(knapSack(W, wt, val, n)) # This code is contributed by Bhavya Jain",
"e": 1599,
"s": 867,
"text": null
},
{
"code": null,
"e": 1604,
"s": 1599,
"text": "220\n"
},
{
"code": null,
"e": 1708,
"s": 1604,
"text": "Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!"
},
{
"code": null,
"e": 1717,
"s": 1708,
"text": "knapsack"
},
{
"code": null,
"e": 1733,
"s": 1717,
"text": "Python Programs"
}
] |
Moment.js moment().valueOf() Function | 29 Jul, 2020
The moment().valueOf() function is used to get the number of milliseconds since the Unix Epoch. Basically the Unix time is a system for describing a point in time.
Syntax:
moment().valueOf();
Parameters: This function has no parameter.
Return Value: This function returns the Unix Timestamp in milliseconds.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below.
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1: Filename: index.js
// Requiring the moduleconst moment = require('moment'); // Function callvar result = moment().valueOf(); console.log("Result:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Result: 1595006948726
The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Result: 1595006948726
node index.js
Output:
Result: 1595006948726
Example 2: Filename: index.js
// Requiring the moduleconst moment = require('moment'); function getUnixTimeStamp() { return moment().valueOf();} // Function callvar result = getUnixTimeStamp();console.log("Unix Timestamp:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164
The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164
node index.js
Output:
Unix Timestamp: 1595007021164
Reference: https://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "The moment().valueOf() function is used to get the number of milliseconds since the Unix Epoch. Basically the Unix time is a system for describing a point in time."
},
{
"code": null,
"e": 200,
"s": 192,
"text": "Syntax:"
},
{
"code": null,
"e": 220,
"s": 200,
"text": "moment().valueOf();"
},
{
"code": null,
"e": 264,
"s": 220,
"text": "Parameters: This function has no parameter."
},
{
"code": null,
"e": 336,
"s": 264,
"text": "Return Value: This function returns the Unix Timestamp in milliseconds."
},
{
"code": null,
"e": 367,
"s": 336,
"text": "Installation of moment module:"
},
{
"code": null,
"e": 703,
"s": 367,
"text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below."
},
{
"code": null,
"e": 822,
"s": 703,
"text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment"
},
{
"code": null,
"e": 841,
"s": 822,
"text": "npm install moment"
},
{
"code": null,
"e": 966,
"s": 841,
"text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment"
},
{
"code": null,
"e": 985,
"s": 966,
"text": "npm version moment"
},
{
"code": null,
"e": 1079,
"s": 985,
"text": "After that, you can just create a folder and add a file for example, index.js as shown below."
},
{
"code": null,
"e": 1109,
"s": 1079,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Requiring the moduleconst moment = require('moment'); // Function callvar result = moment().valueOf(); console.log(\"Result:\", result)",
"e": 1248,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1274,
"s": 1248,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1397,
"s": 1274,
"text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:Result: 1595006948726\n"
},
{
"code": null,
"e": 1440,
"s": 1397,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1521,
"s": 1440,
"text": "Run index.js file using below command:node index.jsOutput:Result: 1595006948726\n"
},
{
"code": null,
"e": 1535,
"s": 1521,
"text": "node index.js"
},
{
"code": null,
"e": 1543,
"s": 1535,
"text": "Output:"
},
{
"code": null,
"e": 1566,
"s": 1543,
"text": "Result: 1595006948726\n"
},
{
"code": null,
"e": 1596,
"s": 1566,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Requiring the moduleconst moment = require('moment'); function getUnixTimeStamp() { return moment().valueOf();} // Function callvar result = getUnixTimeStamp();console.log(\"Unix Timestamp:\", result)",
"e": 1804,
"s": 1596,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1804,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1961,
"s": 1830,
"text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164\n"
},
{
"code": null,
"e": 2004,
"s": 1961,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2093,
"s": 2004,
"text": "Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164\n"
},
{
"code": null,
"e": 2107,
"s": 2093,
"text": "node index.js"
},
{
"code": null,
"e": 2115,
"s": 2107,
"text": "Output:"
},
{
"code": null,
"e": 2146,
"s": 2115,
"text": "Unix Timestamp: 1595007021164\n"
},
{
"code": null,
"e": 2225,
"s": 2146,
"text": "Reference: https://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/"
},
{
"code": null,
"e": 2235,
"s": 2225,
"text": "Moment.js"
},
{
"code": null,
"e": 2243,
"s": 2235,
"text": "Node.js"
},
{
"code": null,
"e": 2260,
"s": 2243,
"text": "Web Technologies"
}
] |
Count non zero values in each column of R dataframe | 05 Apr, 2021
In this article, we are going to count the number of non-zero data entries in the data using R Programming Language.
To check the number of non-zero data entries in the data first we have to put that data in the data frame by using:
data <- data.frame(x1 = c(1,2,0,100,0,3,10),
x2 = c(5,0,1,8,10,0,0),
x3 = 0)
print(data)
Output:
Now we have the data in the data frame. So, to count the number of non-zeroes entries in each column we use colSums() function. This function is used as:
colSums( data != 0)
Output:
As you can clearly see that there are 3 columns in the data frame and Col1 has 5 nonzeroes entries (1,2,100,3,10) and Col2 has 4 non-zeroes entries (5,1,8,10) and Col3 has 0 non-zeroes entries.
Example 1: Here we are going to create a dataframe and then count the non-zero values in each column.
R
# Create example data framedata <- data.frame(x1 = c(1,2,0,100,0,3,10), x2 = c(5,0,1,8,10,0,0), x3 = 0) # print the dataframeprint(data) # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Example 2: In this example, we are using iris3 dataset is used.
R
# put the iris3 data in dataframedata <- data.frame(iris3) # check the dimensions of dataframedim(data) # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Example 3: In this example, the state.x77 dataset is used.
R
# put the state.x77 data in dataframedata <- data.frame(state.x77) # check the dimensions of dataframedim(data) # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Example 4: In this example, the USArrest dataset is used.
R
# put the USArrest data in dataframedata <- data.frame(USArrest) # check the dimensions of dataframedim(data) # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 145,
"s": 28,
"text": "In this article, we are going to count the number of non-zero data entries in the data using R Programming Language."
},
{
"code": null,
"e": 261,
"s": 145,
"text": "To check the number of non-zero data entries in the data first we have to put that data in the data frame by using:"
},
{
"code": null,
"e": 388,
"s": 261,
"text": "data <- data.frame(x1 = c(1,2,0,100,0,3,10), \n x2 = c(5,0,1,8,10,0,0),\n x3 = 0)\n\nprint(data)"
},
{
"code": null,
"e": 396,
"s": 388,
"text": "Output:"
},
{
"code": null,
"e": 550,
"s": 396,
"text": "Now we have the data in the data frame. So, to count the number of non-zeroes entries in each column we use colSums() function. This function is used as:"
},
{
"code": null,
"e": 570,
"s": 550,
"text": "colSums( data != 0)"
},
{
"code": null,
"e": 578,
"s": 570,
"text": "Output:"
},
{
"code": null,
"e": 772,
"s": 578,
"text": "As you can clearly see that there are 3 columns in the data frame and Col1 has 5 nonzeroes entries (1,2,100,3,10) and Col2 has 4 non-zeroes entries (5,1,8,10) and Col3 has 0 non-zeroes entries."
},
{
"code": null,
"e": 874,
"s": 772,
"text": "Example 1: Here we are going to create a dataframe and then count the non-zero values in each column."
},
{
"code": null,
"e": 876,
"s": 874,
"text": "R"
},
{
"code": "# Create example data framedata <- data.frame(x1 = c(1,2,0,100,0,3,10), x2 = c(5,0,1,8,10,0,0), x3 = 0) # print the dataframeprint(data) # check for every non zero entry using \"data!=0\" # and sum the number of entries using colSums()colSums(data != 0)",
"e": 1171,
"s": 876,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1171,
"text": "Output: "
},
{
"code": null,
"e": 1245,
"s": 1180,
"text": "Example 2: In this example, we are using iris3 dataset is used. "
},
{
"code": null,
"e": 1247,
"s": 1245,
"text": "R"
},
{
"code": "# put the iris3 data in dataframedata <- data.frame(iris3) # check the dimensions of dataframedim(data) # check for every non zero entry using \"data!=0\" # and sum the number of entries using colSums()colSums(data != 0)",
"e": 1468,
"s": 1247,
"text": null
},
{
"code": null,
"e": 1476,
"s": 1468,
"text": "Output:"
},
{
"code": null,
"e": 1535,
"s": 1476,
"text": "Example 3: In this example, the state.x77 dataset is used."
},
{
"code": null,
"e": 1537,
"s": 1535,
"text": "R"
},
{
"code": "# put the state.x77 data in dataframedata <- data.frame(state.x77) # check the dimensions of dataframedim(data) # check for every non zero entry using \"data!=0\" # and sum the number of entries using colSums()colSums(data != 0)",
"e": 1768,
"s": 1537,
"text": null
},
{
"code": null,
"e": 1776,
"s": 1768,
"text": "Output:"
},
{
"code": null,
"e": 1834,
"s": 1776,
"text": "Example 4: In this example, the USArrest dataset is used."
},
{
"code": null,
"e": 1836,
"s": 1834,
"text": "R"
},
{
"code": "# put the USArrest data in dataframedata <- data.frame(USArrest) # check the dimensions of dataframedim(data) # check for every non zero entry using \"data!=0\" # and sum the number of entries using colSums()colSums(data != 0)",
"e": 2065,
"s": 1836,
"text": null
},
{
"code": null,
"e": 2074,
"s": 2065,
"text": "Output: "
},
{
"code": null,
"e": 2081,
"s": 2074,
"text": "Picked"
},
{
"code": null,
"e": 2102,
"s": 2081,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 2114,
"s": 2102,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2125,
"s": 2114,
"text": "R Language"
},
{
"code": null,
"e": 2136,
"s": 2125,
"text": "R Programs"
}
] |
Reshaping array as a vector in Julia – vec() Method | 25 Mar, 2020
The vec() is an inbuilt function in julia which is used to reshape the specified array as a one-dimensional column vector i.e, 1D array.
Syntax:vec(a::AbstractArray)
Parameters:
a::AbstractArray: Specified array.
Returns: It returns the reshaped 1D array.
Example 1:
# Julia program to illustrate # the use of Array vec() method # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = ["a", "b", "c", "d"];println(vec(A)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = ["ab" "bc"; "cd" "df"];println(vec(B)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat(["a" "b"; "c" "d"], ["e" "f"; "g" "h"], ["i" "j"; "k" "l"], dims = 3);println(vec(C))
Output:
Example 2:
# Julia program to illustrate # the use of Array vec() method # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = [1, 2, 3, 4];println(vec(A)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = [1 2; 3 4];println(vec(B)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3);println(vec(C))
Output:
Julia Array-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Mar, 2020"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "The vec() is an inbuilt function in julia which is used to reshape the specified array as a one-dimensional column vector i.e, 1D array."
},
{
"code": null,
"e": 194,
"s": 165,
"text": "Syntax:vec(a::AbstractArray)"
},
{
"code": null,
"e": 206,
"s": 194,
"text": "Parameters:"
},
{
"code": null,
"e": 241,
"s": 206,
"text": "a::AbstractArray: Specified array."
},
{
"code": null,
"e": 284,
"s": 241,
"text": "Returns: It returns the reshaped 1D array."
},
{
"code": null,
"e": 295,
"s": 284,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of Array vec() method # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = [\"a\", \"b\", \"c\", \"d\"];println(vec(A)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = [\"ab\" \"bc\"; \"cd\" \"df\"];println(vec(B)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat([\"a\" \"b\"; \"c\" \"d\"], [\"e\" \"f\"; \"g\" \"h\"], [\"i\" \"j\"; \"k\" \"l\"], dims = 3);println(vec(C))",
"e": 793,
"s": 295,
"text": null
},
{
"code": null,
"e": 801,
"s": 793,
"text": "Output:"
},
{
"code": null,
"e": 812,
"s": 801,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of Array vec() method # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = [1, 2, 3, 4];println(vec(A)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = [1 2; 3 4];println(vec(B)) # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3);println(vec(C))",
"e": 1269,
"s": 812,
"text": null
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Output:"
},
{
"code": null,
"e": 1299,
"s": 1277,
"text": "Julia Array-functions"
},
{
"code": null,
"e": 1305,
"s": 1299,
"text": "Julia"
}
] |
Check if two trees are mirror of each other using level order traversal | 18 Aug, 2021
Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not. Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Trees in the above figure are mirrors of each other.
A recursive solution and an iterative method using inorder traversal to check whether the two binary trees is a mirror of each other or not have been already discussed. In this post a solution using level order traversal has been discussed.The idea is to use a queue in which two nodes of both the trees which needs to be checked for equality are present together. At each step of level order traversal, get two nodes from the queue, check for their equality and then insert next two children nodes of these nodes which need to be checked for equality. During insertion step, first left child of first tree node and right child of second tree node are inserted. After this right child of first tree node and left child of second tree node are inserted. If at any stage one node is NULL and other is not, then both trees are not a mirror of each other.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check whether the two// binary trees are mirrors of each other or not#include <bits/stdc++.h>using namespace std; // Structure of a node in binary treestruct Node { int data; struct Node *left, *right;}; // Function to create and return// a new node for a binary treestruct Node* newNode(int data){ struct Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstring areMirrors(Node* a, Node* b){ // If both are NULL, then are mirror. if (a == NULL && b == NULL) return "Yes"; // If only one is NULL, then not // mirror. if (a == NULL || b == NULL) return "No"; queue<Node*> q; // Push root of both trees in queue. q.push(a); q.push(b); while (!q.empty()) { // Pop two elements of queue, to // get two nodes and check if they // are symmetric. a = q.front(); q.pop(); b = q.front(); q.pop(); // If data value of both nodes is // not same, then not mirror. if (a->data != b->data) return "No"; // Push left child of first tree node // and right child of second tree node // into queue if both are not NULL. if (a->left && b->right) { q.push(a->left); q.push(b->right); } // If any one of the nodes is NULL and // other is not NULL, then not mirror. else if (a->left || b->right) return "No"; // Push right child of first tree node // and left child of second tree node // into queue if both are not NULL. if (a->right && b->left) { q.push(a->right); q.push(b->left); } // If any one of the nodes is NULL and // other is not NULL, then not mirror. else if (a->right || b->left) return "No"; } return "Yes";}// Driver Codeint main(){ // 1st binary tree formation /* 1 / \ 3 2 / \ 5 4 */ Node* root1 = newNode(1); root1->left = newNode(3); root1->right = newNode(2); root1->right->left = newNode(5); root1->right->right = newNode(4); // 2nd binary tree formation /* 1 / \ 2 3 / \ 4 5 */ Node* root2 = newNode(1); root2->left = newNode(2); root2->right = newNode(3); root2->left->left = newNode(4); root2->left->right = newNode(5); cout << areMirrors(root1, root2); return 0;}
// Java implementation to check whether the two// binary trees are mirrors of each other or notimport java.util.*; class GFG{ // Structure of a node in binary treestatic class Node{ int data; Node left, right;}; // Function to create and return// a new node for a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){ // If both are null, then are mirror. if (a == null && b == null) return "Yes"; // If only one is null, then not // mirror. if (a == null || b == null) return "No"; Queue<Node> q = new LinkedList<Node>(); // Push root of both trees in queue. q.add(a); q.add(b); while (q.size() > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q.peek(); q.remove(); b = q.peek(); q.remove(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return "No"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.add(a.left); q.add(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return "No"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.add(a.right); q.add(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return "No"; } return "Yes";} // Driver Codepublic static void main(String args[]){ // 1st binary tree formation /* 1 / \ 3 2 / \ 5 4 */ Node root1 = newNode(1); root1.left = newNode(3); root1.right = newNode(2); root1.right.left = newNode(5); root1.right.right = newNode(4); // 2nd binary tree formation /* 1 / \ 2 3 / \ 4 5 */ Node root2 = newNode(1); root2.left = newNode(2); root2.right = newNode(3); root2.left.left = newNode(4); root2.left.right = newNode(5); System.out.print(areMirrors(root1, root2));}} // This code is contributed by Arnab Kundu
# Python3 implementation to check whether the two# binary trees are mirrors of each other or not # Structure of a node in binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to check whether the two binary# trees are mirrors of each other or notdef areMirrors(a, b): # If both are NULL, then are mirror. if a == None and b == None: return "Yes" # If only one is NULL, then not mirror. if a == None or b == None: return "No" q = [] # append root of both trees in queue. q.append(a) q.append(b) while len(q) > 0: # Pop two elements of queue, # to get two nodes and check # if they are symmetric. a = q.pop(0) b = q.pop(0) # If data value of both nodes is # not same, then not mirror. if a.data != b.data: return "No" # append left child of first tree node # and right child of second tree node # into queue if both are not NULL. if a.left and b.right: q.append(a.left) q.append(b.right) # If any one of the nodes is NULL and # other is not NULL, then not mirror. elif a.left or b.right: return "No" # Append right child of first tree node # and left child of second tree node # into queue if both are not NULL. if a.right and b.left: q.append(a.right) q.append(b.left) # If any one of the nodes is NULL and # other is not NULL, then not mirror. elif a.right or b.left: return "No" return "Yes" # Driver Codeif __name__ == "__main__": # 1st binary tree formation root1 = Node(1) root1.left = Node(3) root1.right = Node(2) root1.right.left = Node(5) root1.right.right = Node(4) # 2nd binary tree formation root2 = Node(1) root2.left = Node(2) root2.right = Node(3) root2.left.left = Node(4) root2.left.right = Node(5) print(areMirrors(root1, root2)) # This code is contributed by Rituraj Jain
// C# implementation to check whether the two// binary trees are mirrors of each other or notusing System;using System.Collections.Generic; class GFG{ // Structure of a node in binary treepublic class Node{ public int data; public Node left, right;}; // Function to create and return// a new node for a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){ // If both are null, then are mirror. if (a == null && b == null) return "Yes"; // If only one is null, then not // mirror. if (a == null || b == null) return "No"; Queue<Node> q = new Queue<Node>(); // Push root of both trees in queue. q.Enqueue(a); q.Enqueue(b); while (q.Count > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q.Peek(); q.Dequeue(); b = q.Peek(); q.Dequeue(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return "No"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.Enqueue(a.left); q.Enqueue(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return "No"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.Enqueue(a.right); q.Enqueue(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return "No"; } return "Yes";} // Driver Codepublic static void Main(String []args){ // 1st binary tree formation /* 1 / \ 3 2 / \ 5 4 */ Node root1 = newNode(1); root1.left = newNode(3); root1.right = newNode(2); root1.right.left = newNode(5); root1.right.right = newNode(4); // 2nd binary tree formation /* 1 / \ 2 3 / \ 4 5 */ Node root2 = newNode(1); root2.left = newNode(2); root2.right = newNode(3); root2.left.left = newNode(4); root2.left.right = newNode(5); Console.Write(areMirrors(root1, root2));}} // This code is contributed by Princi Singh
<script> // JavaScript implementation to check whether the two// binary trees are mirrors of each other or not // Structure of a node in binary treeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Function to create and return// a new node for a binary treefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notfunction areMirrors(a, b){ // If both are null, then are mirror. if (a == null && b == null) return "Yes"; // If only one is null, then not // mirror. if (a == null || b == null) return "No"; var q = []; // Push root of both trees in queue. q.push(a); q.push(b); while (q.length > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q[0]; q.shift(); b = q[0]; q.shift(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return "No"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.push(a.left); q.push(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return "No"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.push(a.right); q.push(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return "No"; } return "Yes";} // Driver Code// 1st binary tree formation/* 1 / \ 3 2 / \ 5 4 */var root1 = newNode(1);root1.left = newNode(3);root1.right = newNode(2);root1.right.left = newNode(5);root1.right.right = newNode(4);// 2nd binary tree formation/* 1 / \ 2 3 / \ 4 5 */var root2 = newNode(1);root2.left = newNode(2);root2.right = newNode(3);root2.left.left = newNode(4);root2.left.right = newNode(5);document.write(areMirrors(root1, root2)); </script>
Yes
Time complexity: O(N)Auxiliary Space: O(N)
rituraj_jain
andrew1234
princi singh
Akanksha_Rai
rutvik_56
pankajsharmagfg
gabaa406
Binary Tree
cpp-queue
Data Structures-Tree Traversals
Mirror Tree
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 307,
"s": 54,
"text": "Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not. Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. "
},
{
"code": null,
"e": 361,
"s": 307,
"text": "Trees in the above figure are mirrors of each other. "
},
{
"code": null,
"e": 1260,
"s": 361,
"text": "A recursive solution and an iterative method using inorder traversal to check whether the two binary trees is a mirror of each other or not have been already discussed. In this post a solution using level order traversal has been discussed.The idea is to use a queue in which two nodes of both the trees which needs to be checked for equality are present together. At each step of level order traversal, get two nodes from the queue, check for their equality and then insert next two children nodes of these nodes which need to be checked for equality. During insertion step, first left child of first tree node and right child of second tree node are inserted. After this right child of first tree node and left child of second tree node are inserted. If at any stage one node is NULL and other is not, then both trees are not a mirror of each other.Below is the implementation of above approach: "
},
{
"code": null,
"e": 1264,
"s": 1260,
"text": "C++"
},
{
"code": null,
"e": 1269,
"s": 1264,
"text": "Java"
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Python3"
},
{
"code": null,
"e": 1280,
"s": 1277,
"text": "C#"
},
{
"code": null,
"e": 1291,
"s": 1280,
"text": "Javascript"
},
{
"code": "// C++ implementation to check whether the two// binary trees are mirrors of each other or not#include <bits/stdc++.h>using namespace std; // Structure of a node in binary treestruct Node { int data; struct Node *left, *right;}; // Function to create and return// a new node for a binary treestruct Node* newNode(int data){ struct Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstring areMirrors(Node* a, Node* b){ // If both are NULL, then are mirror. if (a == NULL && b == NULL) return \"Yes\"; // If only one is NULL, then not // mirror. if (a == NULL || b == NULL) return \"No\"; queue<Node*> q; // Push root of both trees in queue. q.push(a); q.push(b); while (!q.empty()) { // Pop two elements of queue, to // get two nodes and check if they // are symmetric. a = q.front(); q.pop(); b = q.front(); q.pop(); // If data value of both nodes is // not same, then not mirror. if (a->data != b->data) return \"No\"; // Push left child of first tree node // and right child of second tree node // into queue if both are not NULL. if (a->left && b->right) { q.push(a->left); q.push(b->right); } // If any one of the nodes is NULL and // other is not NULL, then not mirror. else if (a->left || b->right) return \"No\"; // Push right child of first tree node // and left child of second tree node // into queue if both are not NULL. if (a->right && b->left) { q.push(a->right); q.push(b->left); } // If any one of the nodes is NULL and // other is not NULL, then not mirror. else if (a->right || b->left) return \"No\"; } return \"Yes\";}// Driver Codeint main(){ // 1st binary tree formation /* 1 / \\ 3 2 / \\ 5 4 */ Node* root1 = newNode(1); root1->left = newNode(3); root1->right = newNode(2); root1->right->left = newNode(5); root1->right->right = newNode(4); // 2nd binary tree formation /* 1 / \\ 2 3 / \\ 4 5 */ Node* root2 = newNode(1); root2->left = newNode(2); root2->right = newNode(3); root2->left->left = newNode(4); root2->left->right = newNode(5); cout << areMirrors(root1, root2); return 0;}",
"e": 3918,
"s": 1291,
"text": null
},
{
"code": "// Java implementation to check whether the two// binary trees are mirrors of each other or notimport java.util.*; class GFG{ // Structure of a node in binary treestatic class Node{ int data; Node left, right;}; // Function to create and return// a new node for a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){ // If both are null, then are mirror. if (a == null && b == null) return \"Yes\"; // If only one is null, then not // mirror. if (a == null || b == null) return \"No\"; Queue<Node> q = new LinkedList<Node>(); // Push root of both trees in queue. q.add(a); q.add(b); while (q.size() > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q.peek(); q.remove(); b = q.peek(); q.remove(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return \"No\"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.add(a.left); q.add(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return \"No\"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.add(a.right); q.add(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return \"No\"; } return \"Yes\";} // Driver Codepublic static void main(String args[]){ // 1st binary tree formation /* 1 / \\ 3 2 / \\ 5 4 */ Node root1 = newNode(1); root1.left = newNode(3); root1.right = newNode(2); root1.right.left = newNode(5); root1.right.right = newNode(4); // 2nd binary tree formation /* 1 / \\ 2 3 / \\ 4 5 */ Node root2 = newNode(1); root2.left = newNode(2); root2.right = newNode(3); root2.left.left = newNode(4); root2.left.right = newNode(5); System.out.print(areMirrors(root1, root2));}} // This code is contributed by Arnab Kundu",
"e": 6650,
"s": 3918,
"text": null
},
{
"code": "# Python3 implementation to check whether the two# binary trees are mirrors of each other or not # Structure of a node in binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to check whether the two binary# trees are mirrors of each other or notdef areMirrors(a, b): # If both are NULL, then are mirror. if a == None and b == None: return \"Yes\" # If only one is NULL, then not mirror. if a == None or b == None: return \"No\" q = [] # append root of both trees in queue. q.append(a) q.append(b) while len(q) > 0: # Pop two elements of queue, # to get two nodes and check # if they are symmetric. a = q.pop(0) b = q.pop(0) # If data value of both nodes is # not same, then not mirror. if a.data != b.data: return \"No\" # append left child of first tree node # and right child of second tree node # into queue if both are not NULL. if a.left and b.right: q.append(a.left) q.append(b.right) # If any one of the nodes is NULL and # other is not NULL, then not mirror. elif a.left or b.right: return \"No\" # Append right child of first tree node # and left child of second tree node # into queue if both are not NULL. if a.right and b.left: q.append(a.right) q.append(b.left) # If any one of the nodes is NULL and # other is not NULL, then not mirror. elif a.right or b.left: return \"No\" return \"Yes\" # Driver Codeif __name__ == \"__main__\": # 1st binary tree formation root1 = Node(1) root1.left = Node(3) root1.right = Node(2) root1.right.left = Node(5) root1.right.right = Node(4) # 2nd binary tree formation root2 = Node(1) root2.left = Node(2) root2.right = Node(3) root2.left.left = Node(4) root2.left.right = Node(5) print(areMirrors(root1, root2)) # This code is contributed by Rituraj Jain",
"e": 8773,
"s": 6650,
"text": null
},
{
"code": "// C# implementation to check whether the two// binary trees are mirrors of each other or notusing System;using System.Collections.Generic; class GFG{ // Structure of a node in binary treepublic class Node{ public int data; public Node left, right;}; // Function to create and return// a new node for a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){ // If both are null, then are mirror. if (a == null && b == null) return \"Yes\"; // If only one is null, then not // mirror. if (a == null || b == null) return \"No\"; Queue<Node> q = new Queue<Node>(); // Push root of both trees in queue. q.Enqueue(a); q.Enqueue(b); while (q.Count > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q.Peek(); q.Dequeue(); b = q.Peek(); q.Dequeue(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return \"No\"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.Enqueue(a.left); q.Enqueue(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return \"No\"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.Enqueue(a.right); q.Enqueue(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return \"No\"; } return \"Yes\";} // Driver Codepublic static void Main(String []args){ // 1st binary tree formation /* 1 / \\ 3 2 / \\ 5 4 */ Node root1 = newNode(1); root1.left = newNode(3); root1.right = newNode(2); root1.right.left = newNode(5); root1.right.right = newNode(4); // 2nd binary tree formation /* 1 / \\ 2 3 / \\ 4 5 */ Node root2 = newNode(1); root2.left = newNode(2); root2.right = newNode(3); root2.left.left = newNode(4); root2.left.right = newNode(5); Console.Write(areMirrors(root1, root2));}} // This code is contributed by Princi Singh",
"e": 11561,
"s": 8773,
"text": null
},
{
"code": "<script> // JavaScript implementation to check whether the two// binary trees are mirrors of each other or not // Structure of a node in binary treeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Function to create and return// a new node for a binary treefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to check whether the two binary trees// are mirrors of each other or notfunction areMirrors(a, b){ // If both are null, then are mirror. if (a == null && b == null) return \"Yes\"; // If only one is null, then not // mirror. if (a == null || b == null) return \"No\"; var q = []; // Push root of both trees in queue. q.push(a); q.push(b); while (q.length > 0) { // remove two elements of queue, to // get two nodes and check if they // are symmetric. a = q[0]; q.shift(); b = q[0]; q.shift(); // If data value of both nodes is // not same, then not mirror. if (a.data != b.data) return \"No\"; // Push left child of first tree node // and right child of second tree node // into queue if both are not null. if (a.left != null && b.right != null) { q.push(a.left); q.push(b.right); } // If any one of the nodes is null and // other is not null, then not mirror. else if (a.left != null || b.right != null) return \"No\"; // Push right child of first tree node // and left child of second tree node // into queue if both are not null. if (a.right != null && b.left != null) { q.push(a.right); q.push(b.left); } //If any one of the nodes is null and // other is not null, then not mirror. else if (a.right != null || b.left != null) return \"No\"; } return \"Yes\";} // Driver Code// 1st binary tree formation/* 1 / \\ 3 2 / \\ 5 4 */var root1 = newNode(1);root1.left = newNode(3);root1.right = newNode(2);root1.right.left = newNode(5);root1.right.right = newNode(4);// 2nd binary tree formation/* 1 / \\ 2 3 / \\ 4 5 */var root2 = newNode(1);root2.left = newNode(2);root2.right = newNode(3);root2.left.left = newNode(4);root2.left.right = newNode(5);document.write(areMirrors(root1, root2)); </script>",
"e": 14094,
"s": 11561,
"text": null
},
{
"code": null,
"e": 14098,
"s": 14094,
"text": "Yes"
},
{
"code": null,
"e": 14145,
"s": 14100,
"text": "Time complexity: O(N)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 14158,
"s": 14145,
"text": "rituraj_jain"
},
{
"code": null,
"e": 14169,
"s": 14158,
"text": "andrew1234"
},
{
"code": null,
"e": 14182,
"s": 14169,
"text": "princi singh"
},
{
"code": null,
"e": 14195,
"s": 14182,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14205,
"s": 14195,
"text": "rutvik_56"
},
{
"code": null,
"e": 14221,
"s": 14205,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 14230,
"s": 14221,
"text": "gabaa406"
},
{
"code": null,
"e": 14242,
"s": 14230,
"text": "Binary Tree"
},
{
"code": null,
"e": 14252,
"s": 14242,
"text": "cpp-queue"
},
{
"code": null,
"e": 14284,
"s": 14252,
"text": "Data Structures-Tree Traversals"
},
{
"code": null,
"e": 14296,
"s": 14284,
"text": "Mirror Tree"
},
{
"code": null,
"e": 14312,
"s": 14296,
"text": "Data Structures"
},
{
"code": null,
"e": 14317,
"s": 14312,
"text": "Tree"
},
{
"code": null,
"e": 14333,
"s": 14317,
"text": "Data Structures"
},
{
"code": null,
"e": 14338,
"s": 14333,
"text": "Tree"
}
] |
How to Use Picasso Image Loader Library in Android? | 11 Jul, 2022
Picasso is open source and one of the widely used image download libraries in Android. It is created and maintained by Square. It is among the powerful image download and caching library for Android. Picasso simplifies the process of loading images from external URLs and displays them on your application. For example, downloading an image from the server is one of the most common tasks in any application. And it needs quite a larger amount of code to achieve this via android networking API. By using Picasso, you can achieve this with a few lines of code.
Step 1: Create an empty activity project
Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Java as the programming language.
Step 2: Adding the required dependency to app-level gradle file
For using Picasso in the android project, we have to add a dependency in the app-level gradle file. So, For adding dependency open app/build.gradle file in the app folder in your Android project and add the following lines inside it. Add these lines inside dependencies{}.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
implementation ‘com.squareup.picasso:picasso:2.5.2’
Refer to the following image, if unable to locate the app-level gradle file and invoke the dependency.
Now click on the “Sync Now” button. So that the Android Studio downloads the required dependency files. If you get any type of error then you may check the error on stackoverflow.
Step 3: Working with the Manifest File
Now add InternetPermission inside the AndroidManifest.xml file. Open the manifest.xml file and add the following line.
<users-permission android:name=”android.permission.INTERNET”/>
Step 4: Working with the activity_main.xml file
Open the layout file for the activity_main.xml file. We need to add an ImageView to the application’s main layout.
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" android:background="@color/colorAccent" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:padding="16dp" /> </RelativeLayout>
Step 5: Working with the MainActivity.java file
Now Navigate to the MainActivity.java file and add the following block of code. In the first line, we are getting the ImageView instance from the layout. And then load the image from the remote URL mentioned in the JAVA code using the Picasso library.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load("https://media.geeksforgeeks.org/wp-content/cdn-uploads/logo-new-2.svg") .into(imageView); }}
Note: Make sure the mobile device or Android Emulator has the network connectivity to load the image.
For any real-time application, we must think of all possible cases. In the above code, we just download the image from the server link. But how to display that image in the app.How to resize it and what if the image loading failed? We need to have another image showing an error message that image loading failed. This all matters for an app developer. The following code changes are made in the MainActivity.java file.
Here we are using Picasso to fetch a remote image and resize it before displaying it in an ImageView.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load("https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png") .resize(300, 300) .into(imageView); }}
Output:
If your application relies on remote assets, then it’s important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Picasso has finished fetching it.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load("https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png") .placeholder(R.mipmap.ic_launcher) .into(imageView); }}
Output:
Picasso supports two types of placeholder images. We already saw how the placeholder method works, but there’s also an error method that accepts a placeholder image. Picasso will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset.
The error image will be shown, in this case when there is no internet connectivity for the application. Instead of loading the image from the URL, the Picasso library shows the error image.
Note: To see this result uninstall the previously loaded application and then install the fresh version of the application from the Android Studio.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load("https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png") .error(R.drawable.error_gfg) .into(imageView); }}
Output:
If you are not sure about the size of the image loaded from the remote server that what will be the size of the image. So in this code snippet image will make the image center cropped.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load("https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo-300x300.png") // Equivalent of what ends up in onBitmapLoaded .placeholder(R.mipmap.ic_launcher) .error(R.drawable.error_gfg) .centerCrop() .fit() .into(imageView); }}
Output:
If an image or set of images aren’t loading, make sure to check the Android monitor log in Android Studio. There’s a good chance you might see a java.lang.OutOfMemoryError “Failed to allocate a [...] byte allocation with [...] free bytes” or an Out of memory on a 51121168-byte allocation. This is quite common and means that you are loading one or more large images that have not been properly resized.
First, you have to find which image(s) being loaded are likely causing this error. For any given Picasso call, we can fix this by one or more of the following approaches:
Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(...).load(imageUri).fit().into(...)Open up your static placeholder or error images and make sure their dimensions are relatively small (< 500px width). If not, resize those static images and save them back to your project.Try removing android:adjustViewBounds=”true” from your ImageView if present and if you are calling .fit() rather than using .resize(width, height)Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: Picasso.with(...).load(imageUri).resize(500, 0).into(...). By passing 0, the correct height is automatically calculated.
Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(...).load(imageUri).fit().into(...)
Open up your static placeholder or error images and make sure their dimensions are relatively small (< 500px width). If not, resize those static images and save them back to your project.
Try removing android:adjustViewBounds=”true” from your ImageView if present and if you are calling .fit() rather than using .resize(width, height)
Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: Picasso.with(...).load(imageUri).resize(500, 0).into(...). By passing 0, the correct height is automatically calculated.
Reference: https://github.com/square/picasso
adityamshidlyali
android
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 616,
"s": 54,
"text": "Picasso is open source and one of the widely used image download libraries in Android. It is created and maintained by Square. It is among the powerful image download and caching library for Android. Picasso simplifies the process of loading images from external URLs and displays them on your application. For example, downloading an image from the server is one of the most common tasks in any application. And it needs quite a larger amount of code to achieve this via android networking API. By using Picasso, you can achieve this with a few lines of code. "
},
{
"code": null,
"e": 657,
"s": 616,
"text": "Step 1: Create an empty activity project"
},
{
"code": null,
"e": 893,
"s": 657,
"text": "Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Java as the programming language."
},
{
"code": null,
"e": 957,
"s": 893,
"text": "Step 2: Adding the required dependency to app-level gradle file"
},
{
"code": null,
"e": 1230,
"s": 957,
"text": "For using Picasso in the android project, we have to add a dependency in the app-level gradle file. So, For adding dependency open app/build.gradle file in the app folder in your Android project and add the following lines inside it. Add these lines inside dependencies{}."
},
{
"code": null,
"e": 1239,
"s": 1230,
"text": "Chapters"
},
{
"code": null,
"e": 1266,
"s": 1239,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1316,
"s": 1266,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1339,
"s": 1316,
"text": "captions off, selected"
},
{
"code": null,
"e": 1347,
"s": 1339,
"text": "English"
},
{
"code": null,
"e": 1371,
"s": 1347,
"text": "This is a modal window."
},
{
"code": null,
"e": 1440,
"s": 1371,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1462,
"s": 1440,
"text": "End of dialog window."
},
{
"code": null,
"e": 1515,
"s": 1462,
"text": "implementation ‘com.squareup.picasso:picasso:2.5.2’ "
},
{
"code": null,
"e": 1618,
"s": 1515,
"text": "Refer to the following image, if unable to locate the app-level gradle file and invoke the dependency."
},
{
"code": null,
"e": 1798,
"s": 1618,
"text": "Now click on the “Sync Now” button. So that the Android Studio downloads the required dependency files. If you get any type of error then you may check the error on stackoverflow."
},
{
"code": null,
"e": 1837,
"s": 1798,
"text": "Step 3: Working with the Manifest File"
},
{
"code": null,
"e": 1957,
"s": 1837,
"text": "Now add InternetPermission inside the AndroidManifest.xml file. Open the manifest.xml file and add the following line. "
},
{
"code": null,
"e": 2020,
"s": 1957,
"text": "<users-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 2068,
"s": 2020,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2183,
"s": 2068,
"text": "Open the layout file for the activity_main.xml file. We need to add an ImageView to the application’s main layout."
},
{
"code": null,
"e": 2187,
"s": 2183,
"text": "XML"
},
{
"code": "<?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\" android:background=\"@color/colorAccent\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:padding=\"16dp\" /> </RelativeLayout>",
"e": 2790,
"s": 2187,
"text": null
},
{
"code": null,
"e": 2838,
"s": 2790,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 3090,
"s": 2838,
"text": "Now Navigate to the MainActivity.java file and add the following block of code. In the first line, we are getting the ImageView instance from the layout. And then load the image from the remote URL mentioned in the JAVA code using the Picasso library."
},
{
"code": null,
"e": 3095,
"s": 3090,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/logo-new-2.svg\") .into(imageView); }}",
"e": 3677,
"s": 3095,
"text": null
},
{
"code": null,
"e": 3779,
"s": 3677,
"text": "Note: Make sure the mobile device or Android Emulator has the network connectivity to load the image."
},
{
"code": null,
"e": 4199,
"s": 3779,
"text": "For any real-time application, we must think of all possible cases. In the above code, we just download the image from the server link. But how to display that image in the app.How to resize it and what if the image loading failed? We need to have another image showing an error message that image loading failed. This all matters for an app developer. The following code changes are made in the MainActivity.java file."
},
{
"code": null,
"e": 4301,
"s": 4199,
"text": "Here we are using Picasso to fetch a remote image and resize it before displaying it in an ImageView."
},
{
"code": null,
"e": 4306,
"s": 4301,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load(\"https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png\") .resize(300, 300) .into(imageView); }}",
"e": 4929,
"s": 4306,
"text": null
},
{
"code": null,
"e": 4937,
"s": 4929,
"text": "Output:"
},
{
"code": null,
"e": 5171,
"s": 4937,
"text": "If your application relies on remote assets, then it’s important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Picasso has finished fetching it."
},
{
"code": null,
"e": 5176,
"s": 5171,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load(\"https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png\") .placeholder(R.mipmap.ic_launcher) .into(imageView); }}",
"e": 5816,
"s": 5176,
"text": null
},
{
"code": null,
"e": 5824,
"s": 5816,
"text": "Output:"
},
{
"code": null,
"e": 6132,
"s": 5824,
"text": "Picasso supports two types of placeholder images. We already saw how the placeholder method works, but there’s also an error method that accepts a placeholder image. Picasso will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset."
},
{
"code": null,
"e": 6322,
"s": 6132,
"text": "The error image will be shown, in this case when there is no internet connectivity for the application. Instead of loading the image from the URL, the Picasso library shows the error image."
},
{
"code": null,
"e": 6470,
"s": 6322,
"text": "Note: To see this result uninstall the previously loaded application and then install the fresh version of the application from the Android Studio."
},
{
"code": null,
"e": 6475,
"s": 6470,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load(\"https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png\") .error(R.drawable.error_gfg) .into(imageView); }}",
"e": 7109,
"s": 6475,
"text": null
},
{
"code": null,
"e": 7117,
"s": 7109,
"text": "Output:"
},
{
"code": null,
"e": 7302,
"s": 7117,
"text": "If you are not sure about the size of the image loaded from the remote server that what will be the size of the image. So in this code snippet image will make the image center cropped."
},
{
"code": null,
"e": 7307,
"s": 7302,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Picasso.with(this) .load(\"https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo-300x300.png\") // Equivalent of what ends up in onBitmapLoaded .placeholder(R.mipmap.ic_launcher) .error(R.drawable.error_gfg) .centerCrop() .fit() .into(imageView); }}",
"e": 8098,
"s": 7307,
"text": null
},
{
"code": null,
"e": 8106,
"s": 8098,
"text": "Output:"
},
{
"code": null,
"e": 8511,
"s": 8106,
"text": "If an image or set of images aren’t loading, make sure to check the Android monitor log in Android Studio. There’s a good chance you might see a java.lang.OutOfMemoryError “Failed to allocate a [...] byte allocation with [...] free bytes” or an Out of memory on a 51121168-byte allocation. This is quite common and means that you are loading one or more large images that have not been properly resized. "
},
{
"code": null,
"e": 8683,
"s": 8511,
"text": "First, you have to find which image(s) being loaded are likely causing this error. For any given Picasso call, we can fix this by one or more of the following approaches: "
},
{
"code": null,
"e": 9444,
"s": 8683,
"text": "Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(...).load(imageUri).fit().into(...)Open up your static placeholder or error images and make sure their dimensions are relatively small (< 500px width). If not, resize those static images and save them back to your project.Try removing android:adjustViewBounds=”true” from your ImageView if present and if you are calling .fit() rather than using .resize(width, height)Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: Picasso.with(...).load(imageUri).resize(500, 0).into(...). By passing 0, the correct height is automatically calculated."
},
{
"code": null,
"e": 9640,
"s": 9444,
"text": "Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(...).load(imageUri).fit().into(...)"
},
{
"code": null,
"e": 9828,
"s": 9640,
"text": "Open up your static placeholder or error images and make sure their dimensions are relatively small (< 500px width). If not, resize those static images and save them back to your project."
},
{
"code": null,
"e": 9975,
"s": 9828,
"text": "Try removing android:adjustViewBounds=”true” from your ImageView if present and if you are calling .fit() rather than using .resize(width, height)"
},
{
"code": null,
"e": 10208,
"s": 9975,
"text": "Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: Picasso.with(...).load(imageUri).resize(500, 0).into(...). By passing 0, the correct height is automatically calculated."
},
{
"code": null,
"e": 10253,
"s": 10208,
"text": "Reference: https://github.com/square/picasso"
},
{
"code": null,
"e": 10270,
"s": 10253,
"text": "adityamshidlyali"
},
{
"code": null,
"e": 10278,
"s": 10270,
"text": "android"
},
{
"code": null,
"e": 10283,
"s": 10278,
"text": "Misc"
},
{
"code": null,
"e": 10288,
"s": 10283,
"text": "Misc"
},
{
"code": null,
"e": 10293,
"s": 10288,
"text": "Misc"
}
] |
Node.js | fs.copyFile() Function | 07 Oct, 2021
The fs.copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node.js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.
Syntax:
fs.copyFile( src, dest, mode, callback )
Parameters: This method accepts three parameters as mentioned above and described below:
src: It is a String, Buffer or URL that denotes the source filename to copy.
dest: It is a String, Buffer or URL that denotes the destination filename that the copy operation would create.
mode: It is an integer that specifies the behavior of the copy operation. The values can be given predefined constants that have their respective behaviours: fs.constants.COPYFILE_EXCL: This constant specifies that the copy operation would fail if the destination filename already exists.fs.constants.COPYFILE_FICLONE: This constant specifies that the copy operation would try to create a copy-on-write reflink. A fallback mechanism is used if the platform does not support copy-on-write.fs.constants.COPYFILE_FICLONE_FORCE: This constant specifies that the copy operation would try to create a copy-on-write reflink. The operation would fail if the platform does not support copy-on-write, unlike the previous one.
fs.constants.COPYFILE_EXCL: This constant specifies that the copy operation would fail if the destination filename already exists.
fs.constants.COPYFILE_FICLONE: This constant specifies that the copy operation would try to create a copy-on-write reflink. A fallback mechanism is used if the platform does not support copy-on-write.
fs.constants.COPYFILE_FICLONE_FORCE: This constant specifies that the copy operation would try to create a copy-on-write reflink. The operation would fail if the platform does not support copy-on-write, unlike the previous one.
These constants can also be combined with bitwise OR to create a mask of more than one value. It is an optional parameter. The default value of the parameter is 0.
callback: It is a function that would be called when the method is executed. err: It is an error that would be thrown if the method fails.
err: It is an error that would be thrown if the method fails.
Below examples illustrate the fs.copyFile() method in Node.js:
Example 1: This example shows the copy operation of the “example_file.txt” file to “copied_file.txt” file.
Javascript
// Node.js program to demonstrate the// fs.copyFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// before the functiongetCurrentFilenames();console.log("\nFile Contents of example_file:", fs.readFileSync("example_file.txt", "utf8")); // Copying the file to a the same namefs.copyFile("example_file.txt", "copied_file.txt", (err) => { if (err) { console.log("Error Found:", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log("\nFile Contents of copied_file:", fs.readFileSync("copied_file.txt", "utf8")); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}
Output:
Current filenames:
example_file.txt
index.js
File Contents of example_file: This is a test file.
Current filenames:
copied_file.txt
example_file.txt
index.js
File Contents of copied_file: This is a test file.
Example 2: This example shows the failure of the copy operation when the destination already exists.
Javascript
// Node.js program to demonstrate the// fs.copyFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// before the functiongetCurrentFilenames();console.log("\nFile Contents of example_file:", fs.readFileSync("example_file.txt", "utf8")); // Copying the file to a the same namefs.copyFile("example_file.txt", "copied_file.txt", fs.constants.COPYFILE_EXCL, (err) => { if (err) { console.log("Error Found:", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log("\nFile Contents of copied_file:", fs.readFileSync("copied_file.txt", "utf8")); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}
Output:
Current filenames:
copied_file.txt
example_file.txt
index.js
File Contents of example_file: This is a test file.
Error: [Error: EEXIST: file already exists, copyfile
'G:\tutorials\nodejs-fs-copyFile\example_file.txt' ->
'G:\tutorials\nodejs-fs-copyFile\copied_file.txt'] {
errno: -4075,
code: 'EEXIST',
syscall: 'copyfile',
path: 'G:\\tutorials\\nodejs-fs-copyFile\\example_file.txt',
dest: 'G:\\tutorials\\nodejs-fs-copyFile\\copied_file.txt'
}
Reference: https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_mode_callback
rajeev0719singh
varshagumber28
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Node.js forEach() function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "The fs.copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node.js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation."
},
{
"code": null,
"e": 319,
"s": 310,
"text": "Syntax: "
},
{
"code": null,
"e": 360,
"s": 319,
"text": "fs.copyFile( src, dest, mode, callback )"
},
{
"code": null,
"e": 450,
"s": 360,
"text": "Parameters: This method accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 527,
"s": 450,
"text": "src: It is a String, Buffer or URL that denotes the source filename to copy."
},
{
"code": null,
"e": 639,
"s": 527,
"text": "dest: It is a String, Buffer or URL that denotes the destination filename that the copy operation would create."
},
{
"code": null,
"e": 1355,
"s": 639,
"text": "mode: It is an integer that specifies the behavior of the copy operation. The values can be given predefined constants that have their respective behaviours: fs.constants.COPYFILE_EXCL: This constant specifies that the copy operation would fail if the destination filename already exists.fs.constants.COPYFILE_FICLONE: This constant specifies that the copy operation would try to create a copy-on-write reflink. A fallback mechanism is used if the platform does not support copy-on-write.fs.constants.COPYFILE_FICLONE_FORCE: This constant specifies that the copy operation would try to create a copy-on-write reflink. The operation would fail if the platform does not support copy-on-write, unlike the previous one."
},
{
"code": null,
"e": 1486,
"s": 1355,
"text": "fs.constants.COPYFILE_EXCL: This constant specifies that the copy operation would fail if the destination filename already exists."
},
{
"code": null,
"e": 1687,
"s": 1486,
"text": "fs.constants.COPYFILE_FICLONE: This constant specifies that the copy operation would try to create a copy-on-write reflink. A fallback mechanism is used if the platform does not support copy-on-write."
},
{
"code": null,
"e": 1915,
"s": 1687,
"text": "fs.constants.COPYFILE_FICLONE_FORCE: This constant specifies that the copy operation would try to create a copy-on-write reflink. The operation would fail if the platform does not support copy-on-write, unlike the previous one."
},
{
"code": null,
"e": 2079,
"s": 1915,
"text": "These constants can also be combined with bitwise OR to create a mask of more than one value. It is an optional parameter. The default value of the parameter is 0."
},
{
"code": null,
"e": 2218,
"s": 2079,
"text": "callback: It is a function that would be called when the method is executed. err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 2280,
"s": 2218,
"text": "err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 2343,
"s": 2280,
"text": "Below examples illustrate the fs.copyFile() method in Node.js:"
},
{
"code": null,
"e": 2450,
"s": 2343,
"text": "Example 1: This example shows the copy operation of the “example_file.txt” file to “copied_file.txt” file."
},
{
"code": null,
"e": 2461,
"s": 2450,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.copyFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// before the functiongetCurrentFilenames();console.log(\"\\nFile Contents of example_file:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); // Copying the file to a the same namefs.copyFile(\"example_file.txt\", \"copied_file.txt\", (err) => { if (err) { console.log(\"Error Found:\", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log(\"\\nFile Contents of copied_file:\", fs.readFileSync(\"copied_file.txt\", \"utf8\")); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}",
"e": 3291,
"s": 2461,
"text": null
},
{
"code": null,
"e": 3300,
"s": 3291,
"text": "Output: "
},
{
"code": null,
"e": 3512,
"s": 3300,
"text": "Current filenames:\nexample_file.txt\nindex.js\n\nFile Contents of example_file: This is a test file.\n\nCurrent filenames:\ncopied_file.txt\nexample_file.txt\nindex.js\n\nFile Contents of copied_file: This is a test file."
},
{
"code": null,
"e": 3613,
"s": 3512,
"text": "Example 2: This example shows the failure of the copy operation when the destination already exists."
},
{
"code": null,
"e": 3624,
"s": 3613,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.copyFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// before the functiongetCurrentFilenames();console.log(\"\\nFile Contents of example_file:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); // Copying the file to a the same namefs.copyFile(\"example_file.txt\", \"copied_file.txt\", fs.constants.COPYFILE_EXCL, (err) => { if (err) { console.log(\"Error Found:\", err); } else { // Get the current filenames // after the function getCurrentFilenames(); console.log(\"\\nFile Contents of copied_file:\", fs.readFileSync(\"copied_file.txt\", \"utf8\")); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); });}",
"e": 4491,
"s": 3624,
"text": null
},
{
"code": null,
"e": 4500,
"s": 4491,
"text": "Output: "
},
{
"code": null,
"e": 4963,
"s": 4500,
"text": "Current filenames:\ncopied_file.txt\nexample_file.txt\nindex.js\n\nFile Contents of example_file: This is a test file.\nError: [Error: EEXIST: file already exists, copyfile \n 'G:\\tutorials\\nodejs-fs-copyFile\\example_file.txt' -> \n 'G:\\tutorials\\nodejs-fs-copyFile\\copied_file.txt'] {\n errno: -4075,\n code: 'EEXIST',\n syscall: 'copyfile',\n path: 'G:\\\\tutorials\\\\nodejs-fs-copyFile\\\\example_file.txt',\n dest: 'G:\\\\tutorials\\\\nodejs-fs-copyFile\\\\copied_file.txt'\n}"
},
{
"code": null,
"e": 5044,
"s": 4963,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_mode_callback "
},
{
"code": null,
"e": 5060,
"s": 5044,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 5075,
"s": 5060,
"text": "varshagumber28"
},
{
"code": null,
"e": 5093,
"s": 5075,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 5101,
"s": 5093,
"text": "Node.js"
},
{
"code": null,
"e": 5118,
"s": 5101,
"text": "Web Technologies"
},
{
"code": null,
"e": 5216,
"s": 5118,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5273,
"s": 5216,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 5327,
"s": 5273,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 5367,
"s": 5327,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 5394,
"s": 5367,
"text": "Node.js forEach() function"
},
{
"code": null,
"e": 5426,
"s": 5394,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5488,
"s": 5426,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5549,
"s": 5488,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5599,
"s": 5549,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5642,
"s": 5599,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
atol(), atoll() and atof() functions in C/C++ | 09 Jun, 2020
atol(): This function converts a C-type string, passed as an argument to function call, to a long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long int atol ( const char * str )
Parameters: The function accepts one mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = "5672345"; // Function calling to convert to a long int long int num1 = atol(str1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char str2[] = "10000002 0"; // Function calling to convert to a long int long int num2 = atol(str2); cout << "Number is " << num2 << "\n"; return 0;}Output:Number is 5672345
Number is 10000002
atoll(): This function converts a C-type string, passed as an argument to function call, to a long long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found.If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long long int atoll ( const char * str )
Parameters: The function accepts a mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = "8239206483232728"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char big_num2[] = "100000 9 1324100"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << "Number is " << num2 << "\n"; return 0;}Output:Number is 8239206483232728
Number is 100000
atof() function: This function converts a C-type string, passed as an argument to function call, to double. It parses the C-string str interpreting its content as a floating point number, which is returned as a value of type double. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid floating point number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and 0.0 is returned.Syntax:double atof ( const char * str )
Parameters: The function accepts a single mandatory parameter str which is the representation of a floating point number.Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0).Return Value:// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = "3.1415926535"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << "Value of pi = " << pi_val << "\n"; // char array char acc_g[] = "9.8"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << "Value of acceleration due to gravity = " << acc_g_val << "\n"; return 0;}Output:Value of pi = 3.14159
Value of acceleration due to gravity = 9.8
atol(): This function converts a C-type string, passed as an argument to function call, to a long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long int atol ( const char * str )
Parameters: The function accepts one mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = "5672345"; // Function calling to convert to a long int long int num1 = atol(str1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char str2[] = "10000002 0"; // Function calling to convert to a long int long int num2 = atol(str2); cout << "Number is " << num2 << "\n"; return 0;}Output:Number is 5672345
Number is 10000002
Syntax:
long int atol ( const char * str )
Parameters: The function accepts one mandatory parameter str which is the representation of an integral number.
Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero.
// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = "5672345"; // Function calling to convert to a long int long int num1 = atol(str1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char str2[] = "10000002 0"; // Function calling to convert to a long int long int num2 = atol(str2); cout << "Number is " << num2 << "\n"; return 0;}
Number is 5672345
Number is 10000002
atoll(): This function converts a C-type string, passed as an argument to function call, to a long long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found.If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long long int atoll ( const char * str )
Parameters: The function accepts a mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = "8239206483232728"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char big_num2[] = "100000 9 1324100"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << "Number is " << num2 << "\n"; return 0;}Output:Number is 8239206483232728
Number is 100000
Syntax:
long long int atoll ( const char * str )
Parameters: The function accepts a mandatory parameter str which is the representation of an integral number.
Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero.
// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = "8239206483232728"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << "Number is " << num1 << "\n"; // char array of numbers of spaces char big_num2[] = "100000 9 1324100"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << "Number is " << num2 << "\n"; return 0;}
Number is 8239206483232728
Number is 100000
atof() function: This function converts a C-type string, passed as an argument to function call, to double. It parses the C-string str interpreting its content as a floating point number, which is returned as a value of type double. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid floating point number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and 0.0 is returned.Syntax:double atof ( const char * str )
Parameters: The function accepts a single mandatory parameter str which is the representation of a floating point number.Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0).Return Value:// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = "3.1415926535"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << "Value of pi = " << pi_val << "\n"; // char array char acc_g[] = "9.8"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << "Value of acceleration due to gravity = " << acc_g_val << "\n"; return 0;}Output:Value of pi = 3.14159
Value of acceleration due to gravity = 9.8
Syntax:
double atof ( const char * str )
Parameters: The function accepts a single mandatory parameter str which is the representation of a floating point number.
Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0).
Return Value:
// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = "3.1415926535"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << "Value of pi = " << pi_val << "\n"; // char array char acc_g[] = "9.8"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << "Value of acceleration due to gravity = " << acc_g_val << "\n"; return 0;}
Value of pi = 3.14159
Value of acceleration due to gravity = 9.8
jm1
C-Library
CPP-Functions
C Language
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2020"
},
{
"code": null,
"e": 4594,
"s": 52,
"text": "atol(): This function converts a C-type string, passed as an argument to function call, to a long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long int atol ( const char * str )\nParameters: The function accepts one mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = \"5672345\"; // Function calling to convert to a long int long int num1 = atol(str1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char str2[] = \"10000002 0\"; // Function calling to convert to a long int long int num2 = atol(str2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}Output:Number is 5672345\nNumber is 10000002\natoll(): This function converts a C-type string, passed as an argument to function call, to a long long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found.If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long long int atoll ( const char * str )\nParameters: The function accepts a mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = \"8239206483232728\"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char big_num2[] = \"100000 9 1324100\"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}Output:Number is 8239206483232728\nNumber is 100000\natof() function: This function converts a C-type string, passed as an argument to function call, to double. It parses the C-string str interpreting its content as a floating point number, which is returned as a value of type double. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid floating point number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and 0.0 is returned.Syntax:double atof ( const char * str )\nParameters: The function accepts a single mandatory parameter str which is the representation of a floating point number.Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0).Return Value:// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = \"3.1415926535\"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << \"Value of pi = \" << pi_val << \"\\n\"; // char array char acc_g[] = \"9.8\"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << \"Value of acceleration due to gravity = \" << acc_g_val << \"\\n\"; return 0;}Output:Value of pi = 3.14159\nValue of acceleration due to gravity = 9.8\n"
},
{
"code": null,
"e": 6035,
"s": 4594,
"text": "atol(): This function converts a C-type string, passed as an argument to function call, to a long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long int atol ( const char * str )\nParameters: The function accepts one mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = \"5672345\"; // Function calling to convert to a long int long int num1 = atol(str1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char str2[] = \"10000002 0\"; // Function calling to convert to a long int long int num2 = atol(str2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}Output:Number is 5672345\nNumber is 10000002\n"
},
{
"code": null,
"e": 6043,
"s": 6035,
"text": "Syntax:"
},
{
"code": null,
"e": 6079,
"s": 6043,
"text": "long int atol ( const char * str )\n"
},
{
"code": null,
"e": 6191,
"s": 6079,
"text": "Parameters: The function accepts one mandatory parameter str which is the representation of an integral number."
},
{
"code": null,
"e": 6329,
"s": 6191,
"text": "Return Value: The function returns the converted integral number as a long int. If no valid conversion can be performed, it returns zero."
},
{
"code": "// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char str1[] = \"5672345\"; // Function calling to convert to a long int long int num1 = atol(str1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char str2[] = \"10000002 0\"; // Function calling to convert to a long int long int num2 = atol(str2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}",
"e": 6835,
"s": 6329,
"text": null
},
{
"code": null,
"e": 6873,
"s": 6835,
"text": "Number is 5672345\nNumber is 10000002\n"
},
{
"code": null,
"e": 8382,
"s": 6873,
"text": "atoll(): This function converts a C-type string, passed as an argument to function call, to a long long integer. It parses the C-string str interpreting its content as an integral number, which is returned as a value of type long long int. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found.If the sequence of non-whitespace characters in C-string str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.Syntax:long long int atoll ( const char * str )\nParameters: The function accepts a mandatory parameter str which is the representation of an integral number.Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero.// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = \"8239206483232728\"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char big_num2[] = \"100000 9 1324100\"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}Output:Number is 8239206483232728\nNumber is 100000\n"
},
{
"code": null,
"e": 8390,
"s": 8382,
"text": "Syntax:"
},
{
"code": null,
"e": 8432,
"s": 8390,
"text": "long long int atoll ( const char * str )\n"
},
{
"code": null,
"e": 8542,
"s": 8432,
"text": "Parameters: The function accepts a mandatory parameter str which is the representation of an integral number."
},
{
"code": null,
"e": 8685,
"s": 8542,
"text": "Return Value: The function returns the converted integral number as a long long int. If no valid conversion can be performed, it returns zero."
},
{
"code": "// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array of numbers char big_num1[] = \"8239206483232728\"; // Function calling to convert to a long int long long int num1 = atoll(big_num1); cout << \"Number is \" << num1 << \"\\n\"; // char array of numbers of spaces char big_num2[] = \"100000 9 1324100\"; // Function calling to convert to a long int long long int num2 = atoll(big_num2); cout << \"Number is \" << num2 << \"\\n\"; return 0;}",
"e": 9233,
"s": 8685,
"text": null
},
{
"code": null,
"e": 9278,
"s": 9233,
"text": "Number is 8239206483232728\nNumber is 100000\n"
},
{
"code": null,
"e": 10872,
"s": 9278,
"text": "atof() function: This function converts a C-type string, passed as an argument to function call, to double. It parses the C-string str interpreting its content as a floating point number, which is returned as a value of type double. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid floating point number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and 0.0 is returned.Syntax:double atof ( const char * str )\nParameters: The function accepts a single mandatory parameter str which is the representation of a floating point number.Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0).Return Value:// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = \"3.1415926535\"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << \"Value of pi = \" << pi_val << \"\\n\"; // char array char acc_g[] = \"9.8\"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << \"Value of acceleration due to gravity = \" << acc_g_val << \"\\n\"; return 0;}Output:Value of pi = 3.14159\nValue of acceleration due to gravity = 9.8\n"
},
{
"code": null,
"e": 10880,
"s": 10872,
"text": "Syntax:"
},
{
"code": null,
"e": 10914,
"s": 10880,
"text": "double atof ( const char * str )\n"
},
{
"code": null,
"e": 11036,
"s": 10914,
"text": "Parameters: The function accepts a single mandatory parameter str which is the representation of a floating point number."
},
{
"code": null,
"e": 11199,
"s": 11036,
"text": "Return Value:The function returns the converted floating point number as a double value. If no valid conversion can be performed, the function returns zero (0.0)."
},
{
"code": null,
"e": 11213,
"s": 11199,
"text": "Return Value:"
},
{
"code": "// CPP program to illustrate// working of atol() function.#include <bits/stdc++.h>using namespace std; int main(){ // char array char pi[] = \"3.1415926535\"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << \"Value of pi = \" << pi_val << \"\\n\"; // char array char acc_g[] = \"9.8\"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << \"Value of acceleration due to gravity = \" << acc_g_val << \"\\n\"; return 0;}",
"e": 11789,
"s": 11213,
"text": null
},
{
"code": null,
"e": 11855,
"s": 11789,
"text": "Value of pi = 3.14159\nValue of acceleration due to gravity = 9.8\n"
},
{
"code": null,
"e": 11859,
"s": 11855,
"text": "jm1"
},
{
"code": null,
"e": 11869,
"s": 11859,
"text": "C-Library"
},
{
"code": null,
"e": 11883,
"s": 11869,
"text": "CPP-Functions"
},
{
"code": null,
"e": 11894,
"s": 11883,
"text": "C Language"
},
{
"code": null,
"e": 11905,
"s": 11894,
"text": "C Programs"
},
{
"code": null,
"e": 11918,
"s": 11905,
"text": "C++ Programs"
}
] |
Minimum number of Cuboids required to form a Cube | 07 Sep, 2021
Given L, B, and H which denotes the length, breadth, and height of a cuboid, the task is to find the minimum number of cuboids of specified dimensions that can be placed together to form a cube.
Examples:
Input: L = 1, B = 1, H = 2Output: 4Explanation: Volume of a cuboid of given dimensions = 1 * 1 * 2 = 2.Volume of the cube that can be formed by combining these cuboids = 2 * 2 * 2 = 8. Therefore, the number of cuboids required = 8 / 2 = 4.
Input: L = 2, B = 5, H = 10Output: 10
Naive Approach: Find the maximum of the given dimensions and start iterating over integer values starting from the obtained maximum. For every integer, check if it can be a possible dimension of a cube that can be formed by the given cuboids or not. In order to do so, calculate the volume of the cube and the volume of the cuboid formed by given dimensions. Check if former is divisible by the latter or not. If found to be true, then print the quotient as the required answer.
Time Complexity: O(L * B * H)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the following observation:
The minimum length of a cube obtained by combining cuboids of given dimensions is equal to LCM of L, B, and H. This is because the dimension of the cube must be divisible by L, B, and H.
In order to find the number of cuboids required, calculate the volume of the cube ( = LCM(L, B, H)3) and the cuboid ( = L * B * H) and print ( Volume of cube ) / ( Volume of cuboid ) a the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate and// return LCM of a, b, and cint find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubevoid minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube cout << (volume_cube / volume_cuboid);} // Driver Codeint main(){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to calculate and// return LCM of a, b, and cstatic int find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubestatic void minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube System.out.print((volume_cube / volume_cuboid));}static int __gcd(int a, int b) { return b == 0 ? a:__gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H);}} // This code is contributed by 29AjayKumar
# Python program for the above approach # Function to calculate and# return LCM of a, b, and cdef find_lcm(a, b, c): # Find GCD of a and b g = __gcd(a, b); # Find LCM of a and b LCM1 = (a * b) // g; # LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); # Finding LCM of a, b, c LCM = (LCM1 * c) // g; # return LCM(a, b, c) return LCM; # Function to find the minimum# number of cuboids required to# make the volume of a valid cubedef minimumCuboids(L, B, H): # Find the LCM of L, B, H lcm = find_lcm(L, B, H); # Volume of the cube volume_cube = lcm * lcm * lcm; # Volume of the cuboid volume_cuboid = L * B * H; # Minimum number cuboids required # to form a cube print((volume_cube // volume_cuboid));def __gcd(a, b): if(b == 0): return a; else: return __gcd(b, a % b); # Driver Codeif __name__ == '__main__': # Given dimensions of cuboid L = 1; B = 1; H = 2; # Function Call minimumCuboids(L, B, H); # This code contributed by shikhasingrajput
// C# program for the above approachusing System;class GFG{ // Function to calculate and// return LCM of a, b, and cstatic int find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubestatic void minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube Console.Write((volume_cube / volume_cuboid));}static int __gcd(int a, int b) { return b == 0 ? a:__gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to calculate and// return LCM of a, b, and cfunction find_lcm(a, b, c){ // Find GCD of a and b let g = __gcd(a, b); // Find LCM of a and b let LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c let LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubefunction minimumCuboids(L, B, H){ // Find the LCM of L, B, H let lcm = find_lcm(L, B, H); // Volume of the cube let volume_cube = lcm * lcm * lcm; // Volume of the cuboid let volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube document.write((volume_cube / volume_cuboid));} function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code // Given dimensions of cuboidlet L = 1, B = 1, H = 2; // Function CallminimumCuboids(L, B, H); // This code is contributed by splevel62 </script>
4
Time Complexity: O(log(min(L, B, H)))Auxiliary Space: O(1)
29AjayKumar
shikhasingrajput
splevel62
simmytarika5
varshagumber28
area-volume-programs
GCD-LCM
LCM
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Area of the largest rectangle possible from given coordinates
Total area of two overlapping rectangles
Equation of circle when three points on the circle are given
Count ways to divide circle using N non-intersecting chords
Program to find line passing through 2 Points
Set in C++ Standard Template Library (STL)
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Coin Change | DP-7 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Given L, B, and H which denotes the length, breadth, and height of a cuboid, the task is to find the minimum number of cuboids of specified dimensions that can be placed together to form a cube."
},
{
"code": null,
"e": 233,
"s": 223,
"text": "Examples:"
},
{
"code": null,
"e": 473,
"s": 233,
"text": "Input: L = 1, B = 1, H = 2Output: 4Explanation: Volume of a cuboid of given dimensions = 1 * 1 * 2 = 2.Volume of the cube that can be formed by combining these cuboids = 2 * 2 * 2 = 8. Therefore, the number of cuboids required = 8 / 2 = 4."
},
{
"code": null,
"e": 511,
"s": 473,
"text": "Input: L = 2, B = 5, H = 10Output: 10"
},
{
"code": null,
"e": 991,
"s": 511,
"text": "Naive Approach: Find the maximum of the given dimensions and start iterating over integer values starting from the obtained maximum. For every integer, check if it can be a possible dimension of a cube that can be formed by the given cuboids or not. In order to do so, calculate the volume of the cube and the volume of the cuboid formed by given dimensions. Check if former is divisible by the latter or not. If found to be true, then print the quotient as the required answer. "
},
{
"code": null,
"e": 1042,
"s": 991,
"text": "Time Complexity: O(L * B * H)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1142,
"s": 1042,
"text": "Efficient Approach: To optimize the above approach, the idea is based on the following observation:"
},
{
"code": null,
"e": 1329,
"s": 1142,
"text": "The minimum length of a cube obtained by combining cuboids of given dimensions is equal to LCM of L, B, and H. This is because the dimension of the cube must be divisible by L, B, and H."
},
{
"code": null,
"e": 1535,
"s": 1329,
"text": "In order to find the number of cuboids required, calculate the volume of the cube ( = LCM(L, B, H)3) and the cuboid ( = L * B * H) and print ( Volume of cube ) / ( Volume of cuboid ) a the required answer."
},
{
"code": null,
"e": 1586,
"s": 1535,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1590,
"s": 1586,
"text": "C++"
},
{
"code": null,
"e": 1595,
"s": 1590,
"text": "Java"
},
{
"code": null,
"e": 1603,
"s": 1595,
"text": "Python3"
},
{
"code": null,
"e": 1606,
"s": 1603,
"text": "C#"
},
{
"code": null,
"e": 1617,
"s": 1606,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate and// return LCM of a, b, and cint find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubevoid minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube cout << (volume_cube / volume_cuboid);} // Driver Codeint main(){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H); return 0;}",
"e": 2641,
"s": 1617,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to calculate and// return LCM of a, b, and cstatic int find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubestatic void minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube System.out.print((volume_cube / volume_cuboid));}static int __gcd(int a, int b) { return b == 0 ? a:__gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H);}} // This code is contributed by 29AjayKumar",
"e": 3819,
"s": 2641,
"text": null
},
{
"code": "# Python program for the above approach # Function to calculate and# return LCM of a, b, and cdef find_lcm(a, b, c): # Find GCD of a and b g = __gcd(a, b); # Find LCM of a and b LCM1 = (a * b) // g; # LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); # Finding LCM of a, b, c LCM = (LCM1 * c) // g; # return LCM(a, b, c) return LCM; # Function to find the minimum# number of cuboids required to# make the volume of a valid cubedef minimumCuboids(L, B, H): # Find the LCM of L, B, H lcm = find_lcm(L, B, H); # Volume of the cube volume_cube = lcm * lcm * lcm; # Volume of the cuboid volume_cuboid = L * B * H; # Minimum number cuboids required # to form a cube print((volume_cube // volume_cuboid));def __gcd(a, b): if(b == 0): return a; else: return __gcd(b, a % b); # Driver Codeif __name__ == '__main__': # Given dimensions of cuboid L = 1; B = 1; H = 2; # Function Call minimumCuboids(L, B, H); # This code contributed by shikhasingrajput",
"e": 4864,
"s": 3819,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to calculate and// return LCM of a, b, and cstatic int find_lcm(int a, int b, int c){ // Find GCD of a and b int g = __gcd(a, b); // Find LCM of a and b int LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c int LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubestatic void minimumCuboids(int L, int B, int H){ // Find the LCM of L, B, H int lcm = find_lcm(L, B, H); // Volume of the cube int volume_cube = lcm * lcm * lcm; // Volume of the cuboid int volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube Console.Write((volume_cube / volume_cuboid));}static int __gcd(int a, int b) { return b == 0 ? a:__gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ // Given dimensions of cuboid int L = 1, B = 1, H = 2; // Function Call minimumCuboids(L, B, H);}} // This code is contributed by 29AjayKumar",
"e": 6031,
"s": 4864,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to calculate and// return LCM of a, b, and cfunction find_lcm(a, b, c){ // Find GCD of a and b let g = __gcd(a, b); // Find LCM of a and b let LCM1 = (a * b) / g; // LCM(a, b, c) = LCM(LCM(a, b), c) g = __gcd(LCM1, c); // Finding LCM of a, b, c let LCM = (LCM1 * c) / g; // return LCM(a, b, c) return LCM;} // Function to find the minimum// number of cuboids required to// make the volume of a valid cubefunction minimumCuboids(L, B, H){ // Find the LCM of L, B, H let lcm = find_lcm(L, B, H); // Volume of the cube let volume_cube = lcm * lcm * lcm; // Volume of the cuboid let volume_cuboid = L * B * H; // Minimum number cuboids required // to form a cube document.write((volume_cube / volume_cuboid));} function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code // Given dimensions of cuboidlet L = 1, B = 1, H = 2; // Function CallminimumCuboids(L, B, H); // This code is contributed by splevel62 </script>",
"e": 7123,
"s": 6031,
"text": null
},
{
"code": null,
"e": 7125,
"s": 7123,
"text": "4"
},
{
"code": null,
"e": 7186,
"s": 7127,
"text": "Time Complexity: O(log(min(L, B, H)))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7198,
"s": 7186,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7215,
"s": 7198,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 7225,
"s": 7215,
"text": "splevel62"
},
{
"code": null,
"e": 7238,
"s": 7225,
"text": "simmytarika5"
},
{
"code": null,
"e": 7253,
"s": 7238,
"text": "varshagumber28"
},
{
"code": null,
"e": 7274,
"s": 7253,
"text": "area-volume-programs"
},
{
"code": null,
"e": 7282,
"s": 7274,
"text": "GCD-LCM"
},
{
"code": null,
"e": 7286,
"s": 7282,
"text": "LCM"
},
{
"code": null,
"e": 7296,
"s": 7286,
"text": "Geometric"
},
{
"code": null,
"e": 7309,
"s": 7296,
"text": "Mathematical"
},
{
"code": null,
"e": 7322,
"s": 7309,
"text": "Mathematical"
},
{
"code": null,
"e": 7332,
"s": 7322,
"text": "Geometric"
},
{
"code": null,
"e": 7430,
"s": 7332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7492,
"s": 7430,
"text": "Area of the largest rectangle possible from given coordinates"
},
{
"code": null,
"e": 7533,
"s": 7492,
"text": "Total area of two overlapping rectangles"
},
{
"code": null,
"e": 7594,
"s": 7533,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 7654,
"s": 7594,
"text": "Count ways to divide circle using N non-intersecting chords"
},
{
"code": null,
"e": 7700,
"s": 7654,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 7743,
"s": 7700,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7773,
"s": 7743,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7788,
"s": 7773,
"text": "C++ Data Types"
},
{
"code": null,
"e": 7848,
"s": 7788,
"text": "Write a program to print all permutations of a given string"
}
] |
How to select rows based on range of values of a column in an R data frame? | Extraction or selection of data can be done in many ways such as based on an individual value, range of values, etc. This is mostly required when we want to either compare the subsets of the data set or use the subset for analysis. The selection of rows based on range of value may be done for testing as well. We can do this by subset function.
Consider the below data frame −
Live Demo
> x1<-rpois(20,2)
> x2<-rpois(20,5)
> x3<-rpois(20,10)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 3 2 6
2 3 4 9
3 4 4 12
4 4 8 12
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
12 0 2 5
13 2 6 12
14 2 4 16
15 0 8 14
16 4 1 5
17 1 7 12
18 3 5 9
19 1 6 3
20 0 3 4
> subset(df,df$x1>0 & df$x1<4)
x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<4)
x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<3)
x1 x2 x3
6 2 1 9
8 1 5 12
9 1 4 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
19 1 6 3
> subset(df,df$x1>2 & df$x1<=3)
x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
7 3 5 8
10 3 3 5
18 3 5 9
> subset(df,df$x2>2 & df$x2<6)
x1 x2 x3
2 3 4 9
3 4 4 12
5 3 5 11
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
14 2 4 16
18 3 5 9
20 0 3 4
> subset(df,df$x3>2 & df$x3<11)
x1 x2 x3
1 3 2 6
2 3 4 9
6 2 1 9
7 3 5 8
9 1 4 5
10 3 3 5
12 0 2 5
16 4 1 5
18 3 5 9
19 1 6 3
20 0 3 4 | [
{
"code": null,
"e": 1408,
"s": 1062,
"text": "Extraction or selection of data can be done in many ways such as based on an individual value, range of values, etc. This is mostly required when we want to either compare the subsets of the data set or use the subset for analysis. The selection of rows based on range of value may be done for testing as well. We can do this by subset function."
},
{
"code": null,
"e": 1440,
"s": 1408,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1451,
"s": 1440,
"text": " Live Demo"
},
{
"code": null,
"e": 1538,
"s": 1451,
"text": "> x1<-rpois(20,2)\n> x2<-rpois(20,5)\n> x3<-rpois(20,10)\n> df<-data.frame(x1,x2,x3)\n> df"
},
{
"code": null,
"e": 1728,
"s": 1538,
"text": " x1 x2 x3\n1 3 2 6\n2 3 4 9\n3 4 4 12\n4 4 8 12\n5 3 5 11\n6 2 1 9\n7 3 5 8\n8 1 5 12\n9 1 4 5\n10 3 3 5\n11 2 6 15\n12 0 2 5\n13 2 6 12\n14 2 4 16\n15 0 8 14\n16 4 1 5\n17 1 7 12\n18 3 5 9\n19 1 6 3\n20 0 3 4"
},
{
"code": null,
"e": 1759,
"s": 1728,
"text": "> subset(df,df$x1>0 & df$x1<4)"
},
{
"code": null,
"e": 1894,
"s": 1759,
"text": " x1 x2 x3\n1 3 2 6\n2 3 4 9\n5 3 5 11\n6 2 1 9\n7 3 5 8\n8 1 5 12\n9 1 4 5\n10 3 3 5\n11 2 6 15\n13 2 6 12\n14 2 4 16\n17 1 7 12\n18 3 5 9\n19 1 6 3"
},
{
"code": null,
"e": 1926,
"s": 1894,
"text": "> subset(df,df$x1>=1 & df$x1<4)"
},
{
"code": null,
"e": 2061,
"s": 1926,
"text": " x1 x2 x3\n1 3 2 6\n2 3 4 9\n5 3 5 11\n6 2 1 9\n7 3 5 8\n8 1 5 12\n9 1 4 5\n10 3 3 5\n11 2 6 15\n13 2 6 12\n14 2 4 16\n17 1 7 12\n18 3 5 9\n19 1 6 3"
},
{
"code": null,
"e": 2093,
"s": 2061,
"text": "> subset(df,df$x1>=1 & df$x1<3)"
},
{
"code": null,
"e": 2177,
"s": 2093,
"text": " x1 x2 x3\n6 2 1 9\n8 1 5 12\n9 1 4 5\n11 2 6 15\n13 2 6 12\n14 2 4 16\n17 1 7 12\n19 1 6 3"
},
{
"code": null,
"e": 2209,
"s": 2177,
"text": "> subset(df,df$x1>2 & df$x1<=3)"
},
{
"code": null,
"e": 2270,
"s": 2209,
"text": " x1 x2 x3\n1 3 2 6\n2 3 4 9\n5 3 5 11\n7 3 5 8\n10 3 3 5\n18 3 5 9"
},
{
"code": null,
"e": 2301,
"s": 2270,
"text": "> subset(df,df$x2>2 & df$x2<6)"
},
{
"code": null,
"e": 2399,
"s": 2301,
"text": " x1 x2 x3\n2 3 4 9\n3 4 4 12\n5 3 5 11\n7 3 5 8\n8 1 5 12\n9 1 4 5\n10 3 3 5\n14 2 4 16\n18 3 5 9\n20 0 3 4"
},
{
"code": null,
"e": 2431,
"s": 2399,
"text": "> subset(df,df$x3>2 & df$x3<11)"
},
{
"code": null,
"e": 2535,
"s": 2431,
"text": " x1 x2 x3\n1 3 2 6\n2 3 4 9\n6 2 1 9\n7 3 5 8\n9 1 4 5\n10 3 3 5\n12 0 2 5\n16 4 1 5\n18 3 5 9\n19 1 6 3\n20 0 3 4"
}
] |
How does one use Glide to download an image into a bitmap? | This example demonstrates how do I does one Glide to download an image into a bitmap.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project
Add the following dependency in build.gradle: Module: app
implementation 'com.github.bumptech.glide:glide:4.9.0'
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">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Glide.with(this).asBitmap().load("https://www.google.es/images/srpr/logo11w.png").into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET"/>
<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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates how do I does one Glide to download an image into a bitmap."
},
{
"code": null,
"e": 1276,
"s": 1148,
"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": 1334,
"s": 1276,
"text": "Add the following dependency in build.gradle: Module: app"
},
{
"code": null,
"e": 1389,
"s": 1334,
"text": "implementation 'com.github.bumptech.glide:glide:4.9.0'"
},
{
"code": null,
"e": 1454,
"s": 1389,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1885,
"s": 1454,
"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 <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1942,
"s": 1885,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3056,
"s": 1942,
"text": "import androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport com.bumptech.glide.Glide;\nimport com.bumptech.glide.request.target.CustomTarget;\nimport com.bumptech.glide.request.transition.Transition;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n Glide.with(this).asBitmap().load(\"https://www.google.es/images/srpr/logo11w.png\").into(new CustomTarget<Bitmap>() {\n @Override\n public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {\n imageView.setImageBitmap(resource);\n }\n @Override\n public void onLoadCleared(@Nullable Drawable placeholder) {\n }\n });\n }\n}"
},
{
"code": null,
"e": 3111,
"s": 3056,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3864,
"s": 3111,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android: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": 4215,
"s": 3864,
"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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4256,
"s": 4215,
"text": "Click here to download the project code."
}
] |
Calendar in Python - GeeksforGeeks | 30 Jun, 2021
Python has a built-in function, calendar to work with date related tasks. You will learn to display the calendar of a given date in this example.Examples:
Input 1 :
yy = 2017
mm = 11
Output : November 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Input 2 :
yy = 2017
Output:
2017
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 4 5
2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19
16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26
23 24 25 26 27 28 29 27 28 27 28 29 30 31
30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 7 1 2 3 4
3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11
10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18
17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25
24 25 26 27 28 29 30 29 30 31 26 27 28 29 30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 1 2 3
3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10
10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17
17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24
24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30
31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3
2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10
9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17
16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24
23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31
30 31
Implementation 1 : Displaying Month In the program below, we import the calendar module. The built-in function month() inside the module takes in the year and the month and displays the calendar for that month of the year.
Python
# Python program to display calendar of# given month of the year # import moduleimport calendar yy = 2017mm = 11 # display the calendarprint(calendar.month(yy, mm))
Output:
November 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
OR you can directly run
from command line (CMD in windows or TERMINAL in Linux ) for displaying a month of a yearfor example :
C:\Users\chatu\Desktop>python -m calendar 2019 7
July 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Implementation 2 : Displaying Year In the program below, we import the calendar module. The built-in function calendar () inside the module takes in the year and displays the calendar for that year.
Python3
# Python program to display calendar of# given year # import moduleimport calendar yy = 2017 # display the calendarprint(calendar.calendar(yy))
Output:
2017
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 4 5
2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19
16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26
23 24 25 26 27 28 29 27 28 27 28 29 30 31
30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 7 1 2 3 4
3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11
10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18
17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25
24 25 26 27 28 29 30 29 30 31 26 27 28 29 30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 1 2 3
3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10
10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17
17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24
24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30
31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3
2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10
9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17
16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24
23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31
30 31
OR you can directly run
from command line (CMD in windows or TERMINAL in Linux ) for displaying a yearThis article is contributed by ajay0007. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
manjeet_04
clintra
Python Calander-module
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 24473,
"s": 24316,
"text": "Python has a built-in function, calendar to work with date related tasks. You will learn to display the calendar of a given date in this example.Examples: "
},
{
"code": null,
"e": 26736,
"s": 24473,
"text": "Input 1 : \nyy = 2017\nmm = 11\n\nOutput : November 2017\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n13 14 15 16 17 18 19\n20 21 22 23 24 25 26\n27 28 29 30\n\nInput 2 :\nyy = 2017\n\nOutput:\n\n 2017\n\n January February March\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3 4 5\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26\n23 24 25 26 27 28 29 27 28 27 28 29 30 31\n30 31\n\n April May June\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 7 1 2 3 4\n 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n\n July August September\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 1 2 3\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n31\n\n October November December\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n30 31"
},
{
"code": null,
"e": 26962,
"s": 26738,
"text": "Implementation 1 : Displaying Month In the program below, we import the calendar module. The built-in function month() inside the module takes in the year and the month and displays the calendar for that month of the year. "
},
{
"code": null,
"e": 26969,
"s": 26962,
"text": "Python"
},
{
"code": "# Python program to display calendar of# given month of the year # import moduleimport calendar yy = 2017mm = 11 # display the calendarprint(calendar.month(yy, mm))",
"e": 27134,
"s": 26969,
"text": null
},
{
"code": null,
"e": 27144,
"s": 27134,
"text": "Output: "
},
{
"code": null,
"e": 27279,
"s": 27144,
"text": " November 2017\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n13 14 15 16 17 18 19\n20 21 22 23 24 25 26\n27 28 29 30"
},
{
"code": null,
"e": 27305,
"s": 27279,
"text": "OR you can directly run "
},
{
"code": null,
"e": 27412,
"s": 27307,
"text": "from command line (CMD in windows or TERMINAL in Linux ) for displaying a month of a yearfor example : "
},
{
"code": null,
"e": 27590,
"s": 27412,
"text": "C:\\Users\\chatu\\Desktop>python -m calendar 2019 7\n July 2019\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6 7\n 8 9 10 11 12 13 14\n15 16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30 31"
},
{
"code": null,
"e": 27790,
"s": 27590,
"text": "Implementation 2 : Displaying Year In the program below, we import the calendar module. The built-in function calendar () inside the module takes in the year and displays the calendar for that year. "
},
{
"code": null,
"e": 27798,
"s": 27790,
"text": "Python3"
},
{
"code": "# Python program to display calendar of# given year # import moduleimport calendar yy = 2017 # display the calendarprint(calendar.calendar(yy))",
"e": 27942,
"s": 27798,
"text": null
},
{
"code": null,
"e": 27952,
"s": 27942,
"text": "Output: "
},
{
"code": null,
"e": 30011,
"s": 27952,
"text": " 2017\n\n January February March\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3 4 5\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26\n23 24 25 26 27 28 29 27 28 27 28 29 30 31\n30 31\n\n April May June\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 7 1 2 3 4\n 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n\n July August September\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 1 2 3\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n31\n\n October November December\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n30 31"
},
{
"code": null,
"e": 30037,
"s": 30011,
"text": "OR you can directly run "
},
{
"code": null,
"e": 30534,
"s": 30039,
"text": "from command line (CMD in windows or TERMINAL in Linux ) for displaying a yearThis article is contributed by ajay0007. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30545,
"s": 30534,
"text": "manjeet_04"
},
{
"code": null,
"e": 30553,
"s": 30545,
"text": "clintra"
},
{
"code": null,
"e": 30576,
"s": 30553,
"text": "Python Calander-module"
},
{
"code": null,
"e": 30583,
"s": 30576,
"text": "Python"
},
{
"code": null,
"e": 30602,
"s": 30583,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30700,
"s": 30602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30709,
"s": 30700,
"text": "Comments"
},
{
"code": null,
"e": 30722,
"s": 30709,
"text": "Old Comments"
},
{
"code": null,
"e": 30754,
"s": 30722,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30810,
"s": 30754,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30865,
"s": 30810,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 30907,
"s": 30865,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30949,
"s": 30907,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30980,
"s": 30949,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31019,
"s": 30980,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31041,
"s": 31019,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31070,
"s": 31041,
"text": "Create a directory in Python"
}
] |
Java Program to Find the Intersection Between Two Collection - GeeksforGeeks | 28 Apr, 2021
Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss out how to find the intersection between the two collections i.e Remove all the elements from the first collection if it is not available in the second collection.
In this article we will use two collection framework classes vector class and ArrayList class to find the intersection between the two collection.
Methods:
Using ArrayList.contains() MethodUsing Vector.retainAll() method
Using ArrayList.contains() Method
Using Vector.retainAll() method
Approach 1:
Store the elements in the First collection and in the second collection (Array List).
Now Iterate the First collection and checks whether the second collection contains elements of the first collection or not.
If not contains remove the element from the first collection.
Print the first collection.
Example:
Java
// Java Program to Remove All the Elements from the First// Collection if it is not Available in the Second// Using ArrayList.contains() Method // Importing input output classesimport java.io.*;// Importing utility classesimport java.util.*; // Main classpublic class GFG { // Method 1 of this class // To remove the elements from the collection static ArrayList<Integer> RemoveElements(ArrayList<Integer> A, ArrayList<Integer> B) { // Iterating over elements in object // using for loop for (int i = 0; i < A.size(); ++i) { // Removing the elements from the collection if (B.contains(A.get(i)) == false) { A.remove(i); } } // Returning the update ArrayList return A; } // Method 2 of this class // To print the collection static void print(ArrayList<Integer> A) { // Iterating over elements in object // using for-each loop for (int element : A) { // Printing the elements of the linked list System.out.print(element + " "); } } // Method 3 of this class // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class // Declaring object of Integer type ArrayList<Integer> A = new ArrayList<>(); // Inserting elements to ArrayList object // Custom input entries A.add(1); A.add(2); A.add(3); A.add(4); // Creating another object of ArrayList class // Again declaring object of Integer type ArrayList<Integer> B = new ArrayList<>(); // Inserting elements to ArrayList object // Custom input entries B.add(1); B.add(2); B.add(3); // Calling the Function ArrayList<Integer> UpdatedCollection = RemoveElements(A, B); // Lastly printing the updated collection print(A); }}
1 2 3
Approach 2: Using Vector.retainAll() method
Store the elements in the First collection and in the second collection (Vector).
Now use Vector.retainAll() method
Print the first collection.
Example:
Java
// Java Program to Remove All the Elements from the First// Collection if it is not Available in the Second// Using Vector.retainAll() method // Importing librariesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Method 1 of this class // To remove the elements from the collection static Vector<Integer> RemoveElements(Vector<Integer> A, Vector<Integer> B) { A.retainAll(B); // Returning the update ArrayList return A; } // Method 2 of this class // To print the collection static void print(Vector<Integer> A) { // Iterating elements in object using for loop for (int element : A) { // Printing the elements of the linked list System.out.print(element + " "); } } // Method 3 of this class // Main driver method public static void main(String[] args) { // Creating an ArrayList object // Declaring object of integer type Vector<Integer> A = new Vector<>(); // Inserting elements in the ArrayList // Custom input entries A.add(1); A.add(2); A.add(3); A.add(4); // Creating another ArrayList // Again declaring object of integer type Vector<Integer> B = new Vector<>(); // Inserting elements in the ArrayList // Custom input entries B.add(1); B.add(2); B.add(3); // Calling the Method1 now to // remove the elements from the collection Vector<Integer> UpdatedCollection = RemoveElements(A, B); // Printing the updated collection print(A); }}
1 2 3
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 24020,
"s": 23557,
"text": "Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss out how to find the intersection between the two collections i.e Remove all the elements from the first collection if it is not available in the second collection."
},
{
"code": null,
"e": 24167,
"s": 24020,
"text": "In this article we will use two collection framework classes vector class and ArrayList class to find the intersection between the two collection."
},
{
"code": null,
"e": 24176,
"s": 24167,
"text": "Methods:"
},
{
"code": null,
"e": 24241,
"s": 24176,
"text": "Using ArrayList.contains() MethodUsing Vector.retainAll() method"
},
{
"code": null,
"e": 24275,
"s": 24241,
"text": "Using ArrayList.contains() Method"
},
{
"code": null,
"e": 24307,
"s": 24275,
"text": "Using Vector.retainAll() method"
},
{
"code": null,
"e": 24320,
"s": 24307,
"text": "Approach 1: "
},
{
"code": null,
"e": 24406,
"s": 24320,
"text": "Store the elements in the First collection and in the second collection (Array List)."
},
{
"code": null,
"e": 24530,
"s": 24406,
"text": "Now Iterate the First collection and checks whether the second collection contains elements of the first collection or not."
},
{
"code": null,
"e": 24592,
"s": 24530,
"text": "If not contains remove the element from the first collection."
},
{
"code": null,
"e": 24620,
"s": 24592,
"text": "Print the first collection."
},
{
"code": null,
"e": 24629,
"s": 24620,
"text": "Example:"
},
{
"code": null,
"e": 24634,
"s": 24629,
"text": "Java"
},
{
"code": "// Java Program to Remove All the Elements from the First// Collection if it is not Available in the Second// Using ArrayList.contains() Method // Importing input output classesimport java.io.*;// Importing utility classesimport java.util.*; // Main classpublic class GFG { // Method 1 of this class // To remove the elements from the collection static ArrayList<Integer> RemoveElements(ArrayList<Integer> A, ArrayList<Integer> B) { // Iterating over elements in object // using for loop for (int i = 0; i < A.size(); ++i) { // Removing the elements from the collection if (B.contains(A.get(i)) == false) { A.remove(i); } } // Returning the update ArrayList return A; } // Method 2 of this class // To print the collection static void print(ArrayList<Integer> A) { // Iterating over elements in object // using for-each loop for (int element : A) { // Printing the elements of the linked list System.out.print(element + \" \"); } } // Method 3 of this class // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class // Declaring object of Integer type ArrayList<Integer> A = new ArrayList<>(); // Inserting elements to ArrayList object // Custom input entries A.add(1); A.add(2); A.add(3); A.add(4); // Creating another object of ArrayList class // Again declaring object of Integer type ArrayList<Integer> B = new ArrayList<>(); // Inserting elements to ArrayList object // Custom input entries B.add(1); B.add(2); B.add(3); // Calling the Function ArrayList<Integer> UpdatedCollection = RemoveElements(A, B); // Lastly printing the updated collection print(A); }}",
"e": 26634,
"s": 24634,
"text": null
},
{
"code": null,
"e": 26641,
"s": 26634,
"text": "1 2 3 "
},
{
"code": null,
"e": 26685,
"s": 26641,
"text": "Approach 2: Using Vector.retainAll() method"
},
{
"code": null,
"e": 26767,
"s": 26685,
"text": "Store the elements in the First collection and in the second collection (Vector)."
},
{
"code": null,
"e": 26801,
"s": 26767,
"text": "Now use Vector.retainAll() method"
},
{
"code": null,
"e": 26829,
"s": 26801,
"text": "Print the first collection."
},
{
"code": null,
"e": 26838,
"s": 26829,
"text": "Example:"
},
{
"code": null,
"e": 26843,
"s": 26838,
"text": "Java"
},
{
"code": "// Java Program to Remove All the Elements from the First// Collection if it is not Available in the Second// Using Vector.retainAll() method // Importing librariesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Method 1 of this class // To remove the elements from the collection static Vector<Integer> RemoveElements(Vector<Integer> A, Vector<Integer> B) { A.retainAll(B); // Returning the update ArrayList return A; } // Method 2 of this class // To print the collection static void print(Vector<Integer> A) { // Iterating elements in object using for loop for (int element : A) { // Printing the elements of the linked list System.out.print(element + \" \"); } } // Method 3 of this class // Main driver method public static void main(String[] args) { // Creating an ArrayList object // Declaring object of integer type Vector<Integer> A = new Vector<>(); // Inserting elements in the ArrayList // Custom input entries A.add(1); A.add(2); A.add(3); A.add(4); // Creating another ArrayList // Again declaring object of integer type Vector<Integer> B = new Vector<>(); // Inserting elements in the ArrayList // Custom input entries B.add(1); B.add(2); B.add(3); // Calling the Method1 now to // remove the elements from the collection Vector<Integer> UpdatedCollection = RemoveElements(A, B); // Printing the updated collection print(A); }}",
"e": 28539,
"s": 26843,
"text": null
},
{
"code": null,
"e": 28546,
"s": 28539,
"text": "1 2 3 "
},
{
"code": null,
"e": 28563,
"s": 28546,
"text": "Java-Collections"
},
{
"code": null,
"e": 28570,
"s": 28563,
"text": "Picked"
},
{
"code": null,
"e": 28575,
"s": 28570,
"text": "Java"
},
{
"code": null,
"e": 28589,
"s": 28575,
"text": "Java Programs"
},
{
"code": null,
"e": 28594,
"s": 28589,
"text": "Java"
},
{
"code": null,
"e": 28611,
"s": 28594,
"text": "Java-Collections"
},
{
"code": null,
"e": 28709,
"s": 28611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28718,
"s": 28709,
"text": "Comments"
},
{
"code": null,
"e": 28731,
"s": 28718,
"text": "Old Comments"
},
{
"code": null,
"e": 28761,
"s": 28731,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28776,
"s": 28761,
"text": "Stream In Java"
},
{
"code": null,
"e": 28797,
"s": 28776,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28843,
"s": 28797,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28862,
"s": 28843,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28906,
"s": 28862,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28932,
"s": 28906,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28966,
"s": 28932,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29013,
"s": 28966,
"text": "Implementing a Linked List in Java using Class"
}
] |
Prove that the Hamiltonian Path is NP-Complete in TOC | A Hamilton cycle is a round trip path along n edges of graph G which visits every vertex once and returns to its starting vertex
Given below is an example of the Hamilton cycle path −
Hamilton cycle path: 1,2,8,7,6,5,4,3,1
The travelling salesman problem (TSP) is having a salesman and a set of cities. The salesman needs to visit each one of the cities starting from a certain one and returning to the same city i.e. back to starting position. The challenge of this problem is that the travelling salesman wants to minimise the total length of the trip.
To prove TSP is NP-Complete, first try to prove TSP belongs to Non-deterministic Polynomial (NP).
In TSP, we have to find a tour and check that the tour contains each vertex once.
Then, we calculate the total cost of the edges of the tour. Finally, we check if the cost is minimum or not. This can be done in polynomial time.
Therefore, TSP belongs to NP.
Next, we have to prove that TSP is NP-hard.
To prove this, one way is to show that the Hamiltonian cycle ≤p TSP (as we know that the Hamiltonian cycle problem is NP Complete).
Assume G = (V, E) to be an instance of the Hamiltonian cycle.
Hence, an instance of TSP is constructed. We can create the complete graph G' = (V, E'), where
E′={(i,j):i,j∈Vandi≠j
Thus, the cost function is defined as follows:
t(i,j)= 0 if (i,j) ∈ E
=1 otherwise
Now, assume that a Hamiltonian cycle H exists in G. The cost of each edge in H is 0 in G' as each edge belongs to E. Therefore, H is having a cost of 0 in G'. Thus, if graph G has a Hamiltonian cycle, then graph G' has a tour of 0 cost.
Now let us assume that G' has a tour H’ of cost at most 0. The cost of edges in E' are 0 and 1 by definition. Hence, each edge must have a cost of 0 as the cost of H’ is 0. We finally conclude that H' contains only edges in E.
Finally proved that G has a Hamiltonian cycle, if and only if G' has a tour of cost at most 0. TSP is NP-complete. | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "A Hamilton cycle is a round trip path along n edges of graph G which visits every vertex once and returns to its starting vertex"
},
{
"code": null,
"e": 1246,
"s": 1191,
"text": "Given below is an example of the Hamilton cycle path −"
},
{
"code": null,
"e": 1285,
"s": 1246,
"text": "Hamilton cycle path: 1,2,8,7,6,5,4,3,1"
},
{
"code": null,
"e": 1617,
"s": 1285,
"text": "The travelling salesman problem (TSP) is having a salesman and a set of cities. The salesman needs to visit each one of the cities starting from a certain one and returning to the same city i.e. back to starting position. The challenge of this problem is that the travelling salesman wants to minimise the total length of the trip."
},
{
"code": null,
"e": 1715,
"s": 1617,
"text": "To prove TSP is NP-Complete, first try to prove TSP belongs to Non-deterministic Polynomial (NP)."
},
{
"code": null,
"e": 1797,
"s": 1715,
"text": "In TSP, we have to find a tour and check that the tour contains each vertex once."
},
{
"code": null,
"e": 1943,
"s": 1797,
"text": "Then, we calculate the total cost of the edges of the tour. Finally, we check if the cost is minimum or not. This can be done in polynomial time."
},
{
"code": null,
"e": 1973,
"s": 1943,
"text": "Therefore, TSP belongs to NP."
},
{
"code": null,
"e": 2017,
"s": 1973,
"text": "Next, we have to prove that TSP is NP-hard."
},
{
"code": null,
"e": 2149,
"s": 2017,
"text": "To prove this, one way is to show that the Hamiltonian cycle ≤p TSP (as we know that the Hamiltonian cycle problem is NP Complete)."
},
{
"code": null,
"e": 2211,
"s": 2149,
"text": "Assume G = (V, E) to be an instance of the Hamiltonian cycle."
},
{
"code": null,
"e": 2306,
"s": 2211,
"text": "Hence, an instance of TSP is constructed. We can create the complete graph G' = (V, E'), where"
},
{
"code": null,
"e": 2415,
"s": 2306,
"text": "E′={(i,j):i,j∈Vandi≠j\nThus, the cost function is defined as follows:\nt(i,j)= 0 if (i,j) ∈ E\n =1 otherwise"
},
{
"code": null,
"e": 2652,
"s": 2415,
"text": "Now, assume that a Hamiltonian cycle H exists in G. The cost of each edge in H is 0 in G' as each edge belongs to E. Therefore, H is having a cost of 0 in G'. Thus, if graph G has a Hamiltonian cycle, then graph G' has a tour of 0 cost."
},
{
"code": null,
"e": 2879,
"s": 2652,
"text": "Now let us assume that G' has a tour H’ of cost at most 0. The cost of edges in E' are 0 and 1 by definition. Hence, each edge must have a cost of 0 as the cost of H’ is 0. We finally conclude that H' contains only edges in E."
},
{
"code": null,
"e": 2994,
"s": 2879,
"text": "Finally proved that G has a Hamiltonian cycle, if and only if G' has a tour of cost at most 0. TSP is NP-complete."
}
] |
Program to compare two fractions in C | Given two fractions with some numerator nume1 and nume2 and deno1 and deno2 as their respective denominator, the task is to compare both the fractions and find out the greater one. Like we have a fraction 1/2 and 2/3 and the higher one is 2/3 because the value of 1/2 is 0.5 and the value of 2/3 is 0.66667 which is higher.
Input
first.nume = 2, first.deno = 3
second.nume = 4, second.deno = 3
Output
4/3
Explanation
2/3 = 0.66667 < 4/3 = 1.33333
Input
first.nume = 1, first.deno = 2
second.nume = 4, second.deno = 3
Output
4/3
//baadme likhunga
Start
Declare a struct Fraction with elements
nume, deno
In function Fraction greater(Fraction first, Fraction sec)
Step 1→ Declare and Initialize t Y = first.nume * sec.deno - first.deno *
sec.nume
Step 2→ Return (Y > 0) ? first : sec
In function int main()
Step 1→ Declare Fraction first = { 4, 5 }
Step 2→Fraction sec = { 3, 4 }
Step 3→ Fraction res = greater(first, sec)
Step 4→ Print res.nume, res.deno
Stop
#include <stdio.h>
struct Fraction {
int nume, deno;
};
// Get max of the two fractions
Fraction greater(Fraction first, Fraction sec){
//check if the result is in negative then the
//second fraction is greater else first is greater
int Y = first.nume * sec.deno - first.deno * sec.nume;
return (Y > 0) ? first : sec;
}
int main(){
Fraction first = { 4, 5 };
Fraction sec = { 3, 4 };
Fraction res = greater(first, sec);
printf("The greater fraction is: %d/%d\n", res.nume, res.deno);
return 0;
}
If run the above code it will generate the following output −
The greater fraction is: 4/5 | [
{
"code": null,
"e": 1386,
"s": 1062,
"text": "Given two fractions with some numerator nume1 and nume2 and deno1 and deno2 as their respective denominator, the task is to compare both the fractions and find out the greater one. Like we have a fraction 1/2 and 2/3 and the higher one is 2/3 because the value of 1/2 is 0.5 and the value of 2/3 is 0.66667 which is higher."
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": "Input "
},
{
"code": null,
"e": 1457,
"s": 1393,
"text": "first.nume = 2, first.deno = 3\nsecond.nume = 4, second.deno = 3"
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Output "
},
{
"code": null,
"e": 1469,
"s": 1465,
"text": "4/3"
},
{
"code": null,
"e": 1482,
"s": 1469,
"text": "Explanation "
},
{
"code": null,
"e": 1512,
"s": 1482,
"text": "2/3 = 0.66667 < 4/3 = 1.33333"
},
{
"code": null,
"e": 1519,
"s": 1512,
"text": "Input "
},
{
"code": null,
"e": 1583,
"s": 1519,
"text": "first.nume = 1, first.deno = 2\nsecond.nume = 4, second.deno = 3"
},
{
"code": null,
"e": 1591,
"s": 1583,
"text": "Output "
},
{
"code": null,
"e": 1595,
"s": 1591,
"text": "4/3"
},
{
"code": null,
"e": 1613,
"s": 1595,
"text": "//baadme likhunga"
},
{
"code": null,
"e": 2047,
"s": 1613,
"text": "Start\nDeclare a struct Fraction with elements\n nume, deno\nIn function Fraction greater(Fraction first, Fraction sec)\n Step 1→ Declare and Initialize t Y = first.nume * sec.deno - first.deno *\nsec.nume\n Step 2→ Return (Y > 0) ? first : sec\nIn function int main()\n Step 1→ Declare Fraction first = { 4, 5 }\n Step 2→Fraction sec = { 3, 4 }\n Step 3→ Fraction res = greater(first, sec)\n Step 4→ Print res.nume, res.deno\nStop"
},
{
"code": null,
"e": 2573,
"s": 2047,
"text": "#include <stdio.h>\nstruct Fraction {\n int nume, deno;\n};\n// Get max of the two fractions\nFraction greater(Fraction first, Fraction sec){\n //check if the result is in negative then the\n //second fraction is greater else first is greater\n int Y = first.nume * sec.deno - first.deno * sec.nume;\n return (Y > 0) ? first : sec;\n}\nint main(){\n Fraction first = { 4, 5 };\n Fraction sec = { 3, 4 };\n Fraction res = greater(first, sec);\n printf(\"The greater fraction is: %d/%d\\n\", res.nume, res.deno);\n return 0;\n}"
},
{
"code": null,
"e": 2635,
"s": 2573,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 2664,
"s": 2635,
"text": "The greater fraction is: 4/5"
}
] |
Catch block and type conversion in C++ - GeeksforGeeks | 12 Nov, 2021
Predict the output of following C++ program.
C++
#include <iostream>using namespace std; int main(){ try { throw 'x'; } catch(int x) { cout << " Caught int " << x; } catch(...) { cout << "Default catch block"; }}
Output:
Default catch block
In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.
C++
#include <iostream>using namespace std; class MyExcept1 {}; class MyExcept2{public: // Conversion constructor MyExcept2 (const MyExcept1 &e ) { cout << "Conversion constructor called"; }}; int main(){ try { MyExcept1 myexp1; throw myexp1; } catch(MyExcept2 e2) { cout << "Caught MyExcept2 " << endl; } catch(...) { cout << " Default catch block " << endl; } return 0;}
Output:
Default catch block
As a side note, the derived type objects are converted to base type when a derived object is thrown and there is a catch block to catch base type. See this GFact for more details.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
yurychaikou
kashishsoda
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++ | [
{
"code": null,
"e": 26962,
"s": 26934,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 27007,
"s": 26962,
"text": "Predict the output of following C++ program."
},
{
"code": null,
"e": 27011,
"s": 27007,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ try { throw 'x'; } catch(int x) { cout << \" Caught int \" << x; } catch(...) { cout << \"Default catch block\"; }}",
"e": 27223,
"s": 27011,
"text": null
},
{
"code": null,
"e": 27231,
"s": 27223,
"text": "Output:"
},
{
"code": null,
"e": 27252,
"s": 27231,
"text": " Default catch block"
},
{
"code": null,
"e": 27606,
"s": 27252,
"text": "In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object."
},
{
"code": null,
"e": 27610,
"s": 27606,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class MyExcept1 {}; class MyExcept2{public: // Conversion constructor MyExcept2 (const MyExcept1 &e ) { cout << \"Conversion constructor called\"; }}; int main(){ try { MyExcept1 myexp1; throw myexp1; } catch(MyExcept2 e2) { cout << \"Caught MyExcept2 \" << endl; } catch(...) { cout << \" Default catch block \" << endl; } return 0;}",
"e": 28057,
"s": 27610,
"text": null
},
{
"code": null,
"e": 28065,
"s": 28057,
"text": "Output:"
},
{
"code": null,
"e": 28085,
"s": 28065,
"text": "Default catch block"
},
{
"code": null,
"e": 28390,
"s": 28085,
"text": "As a side note, the derived type objects are converted to base type when a derived object is thrown and there is a catch block to catch base type. See this GFact for more details.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28402,
"s": 28390,
"text": "yurychaikou"
},
{
"code": null,
"e": 28414,
"s": 28402,
"text": "kashishsoda"
},
{
"code": null,
"e": 28425,
"s": 28414,
"text": "C Language"
},
{
"code": null,
"e": 28429,
"s": 28425,
"text": "C++"
},
{
"code": null,
"e": 28448,
"s": 28429,
"text": "School Programming"
},
{
"code": null,
"e": 28452,
"s": 28448,
"text": "CPP"
},
{
"code": null,
"e": 28550,
"s": 28452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28628,
"s": 28550,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 28651,
"s": 28628,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 28678,
"s": 28651,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28706,
"s": 28678,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28752,
"s": 28706,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28770,
"s": 28752,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28816,
"s": 28770,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28839,
"s": 28816,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 28866,
"s": 28839,
"text": "Bitwise Operators in C/C++"
}
] |
Python and Apache CassandraTM for Beginners | by Andreas Adamides | Towards Data Science | Python is one of the most widely used programming languages with a huge and supportive community, while Cassandra is one of the most popular NoSQL databases traditionally used for web applications storage or also data centric applications that are dependent on quick retrieval of data. Together, they are found in many applications across various industries as well as in academia.
This Cassandra Python tutorial is intended for beginners in Python and Cassandra. The code samples you can see throughout the article are publicly available in this Github repository. We will guide you through setting up Python as well as DataStax Astra, a managed Cassandra-as-a-Service application hosted on any cloud for free. We will show you how to connect Python to Cassandra and insert data with the Datastax ODBC driver as well as use the Astra web console to query data stored in Cassandra with the CQL console. The upcoming Python SDK for Astra will enable API access for REST, GraphQL and a schemaless JSON document API for a given Astra database instance, which will be reviewed in an upcoming article.
Python has gained plenty of popularity over the past decade and with good reasons. Simply put it is a programming language that is very readable, easy and free to use. It is also easy to get started with, but at the same time it can be used for a variety of different applications and different areas. Multiple Python libraries exist that allow solving problems like string manipulation, implementing machine learning algorithms, object-oriented programming and for data engineering purposes which we will be focusing more on in this tutorial.
There are two major versions of Python available, Python 2 and Python 3. The former is no longer receiving updates nor supported, while the latter is the latest version and the one we will be using. Installing Python can be easily achieved irrespective of the OS that you are using.
The best way to install Python on your computer is through the official Python page. Based on the OS you are using, pick the appropriate installer from the official page.
To verify that Python is correctly installed on your computer, open a command line window and execute the following:
python --version
This will return with the version that you just installed:
Python 3.8.2
If you correctly installed Python and got a command not found or a similar error message, this will most likely mean that Python has not correctly been added to the PATH variable on your OS; so make sure to double-check that the path that Python was installed on, is part of the PATH.
Like any other programming language, Python also uses a separate utility to install packages. The built-in package manager for Python is called pip. Except from pip, other popular Python package managers include virtualenv and conda, but for the purposes of this Cassandra Python tutorial we are going to be using pip.
Each Python project that uses pip, will usually have a file called requirements.txt in the root directory of the repository, in the same way we have our requirements.txt in our Github project. The contents of this file are very simple; each line consists of the name of the package, optionally followed by a specific version for that package:
cassandra-driver==3.25.0numpy==1.19.3astrapy==0.0.2simplejson==3.17.2
To install the required packages which includes Cassandra Python libraries cassandra-driver and astrapy, simply navigate to the root directory in your command line and execute:
pip install -r requirements.txt
What happens in the background, is that pip will fetch these packages from the default and public Python Package Index, PyPi. You can inspect the PyPi homepage of each package, including available versions, further documentation, links to each package’s Github repository and examples of how to use each package. For example this is the page for numpy, and this is the page for cassandra-driver.
This completes the installation of the dependencies of our Python project.
Cassandra is the leading open-source NoSQL distributed database management system(DBMS). In contrast to traditional SQL DBMS like Oracle or SQL Server, NoSQL databases follow a different storage model. While in SQL systems data is organised in tables and columns that are driven from fixed schemas, in Cassandra a fixed schema is not enforced, a dynamic number of columns within the same table(or column-family as a table is often called within Cassandra) is allowed as well as being able to handle and store unstructured data. In addition to the above, the language which is used to interact with Cassandra is a variant (and subset) of the traditional SQL, called Cassandra Query Language(CQL).
Cassandra is used by 90% of Fortune 100 companies. The fact that is rapidly growing can be explained by its set of rich features that are particularly beneficial for large amounts of data. Its distributed architecture ensures ultra fast write performance, and fast retrievals for data querying, no single point of failure which results in 100% high availability and significant reduction in time to market due to the simplicity of deploying, managing and maintaining a Cassandra Cluster.
Cassandra is open source which means it’s free to use. Depending on the OS you are using, you can download Cassandra and its dependencies locally, configure and install them. Kubernetes users can also use Docker images, but all of this process can be tiresome, especially for first-time users.
The best way to get started with Cassandra, is through a managed Cassandra database which is available through the web. Datastax Astra is a serverless database-as-a-Service powered by Apache Cassandra which can be launched with just a few clicks, has a generous free tier, and is available in major cloud providers (Amazon Web Services, Azure or Google Cloud).
The official Astra guide has all the information you need to create an Astra service; you need to register for an account and then select a few more details, such as choosing a cloud provider and naming your database.
Using React, Angular or Vue as a frontend? astrapy is a handy Cassandra Python library that creates a schemaless, JSON document oriented API atop Datastax Astra’s REST API. In this example we are going to authenticate to Astra using a token(instead of client secret), generate a dummy JSON document and issue a PUT REST call to insert the JSON in an Astra collection.
Before navigating through the code make sure you have astrapy and simplejson libraries installed. You can check that by executing pip freeze. If you don’t have them install them from the requirements.txt file in the root of the project with pip install -r requirements.txt.
First in the code, we will get an Astra HTTP client. Before doing so, we need to generate an application token and export five environment variables in total. Navigate to Datastax Astra homepage and click on the database name:
Then, just below the database name, click on Connect:
This time, remain on the Connect using an API option:
Note 3 of the 5 environment variables that you need to export in the right part of the page:
ASTRA_DB_ID
ASTRA_DB_REGION
ASTRA_DB_KEYSPACE
For the ASTRA_DB_APPLICATION_TOKEN environment variable, let’s generate the connection credentials. Click where it says “here”:
A new page will popup, select the role(select R/W User) and click on Generate Token:
Once you do, you will get a window with all the details:
Make sure to keep the other(Client Id, Client Secret) information in a place where you can reference them as we will use them later. Export the ASTRA_DB_APPLICATION_TOKEN environment variable, which is equal to the token that was generated in this step..
Fill in any name you like for the fifth and final environment variable ASTRA_DB_COLLECTION. In my case this variable is equal to demo_book.
Once you have exported the five environment variables according to the OS you are using, you are ready to start execution of the Python script. The first part will authenticate against Datastax Astra using token authentication:
Once we have the HTTP client object, that is passed to the next method in which we create and insert a JSON document to an Astra collection:
To execute the Python script type python json_document_api.py and hit enter.
Finally we can confirm that the document has been inserted successfully by issuing a curl command to retrieve it through the command line as follows:
This command will return all documents that have been inserted, in our case:
The Cassandra Python cassandra-driver makes it easy to authenticate and insert tabular data in Datastax Astra.Up to this point we have made sure to install Python and to have an Astra serverless instance that we can work with using a schemless, JSON Document — oriented API. Let’s continue by actually interacting with our Astra database using the cassandra-driver as an schema — driven alternative to the Document API in the Astra Python SDK.
Before starting to code, we need to get the prerequisites for configuring the connection from Python to Astra. From the Astra dashboard page, click on the database name from the left hand side of the page:
Then, just below the database name, click on Connect:
Choose Python from the drivers list:
Now you will see a detailed guide of the steps you need to follow pop up on the right side of the page. First, we will make sure to download the bundle and store it in our local storage. We will reference this later in our code. On the right hand side of the page, click on the Download Bundle button and then on click on Secure Connect Bundle popup button
This will download the bundle in the default downloads directory configured from your browser. This is usually located in your home directory, with the name of the bundle following a specific naming format of secure-connect-<database-name>.zip, for example in our case it is named secure-connect-cassandra-pythondemo.zip. Note the location of the downloaded zip.
In this section we are going to be generating a fictional time series dataset in Python and insert the data in our Astra database using the Datastax Python ODBC/JDBC driver.
First, we are going to create the Astra table that will hold our data. Navigate to the Astra dashboard page, click on the database name from the left hand side of the page:
Click on the Cassandra Query Language(CQL) Console:
Copy the intro/demo_readings.sql from the Github repo and paste it on the CQL Console and hit Enter:
This completes the creation of the Astra table. As you can see in the above DDL script, this timeseries dataset consists of floating value metric(value) that is captured in continuous intervals(value_ts) for a fictional pair of hardware(device_id and timeseries_id), while the timestamp of when the record was captured is also included(publication_ts).
Following the creation of the Cassandra table, let’s navigate to Python. First, make sure to git clone the project in your local filesystem:
git clone [email protected]:andyadamides/python-cassandra-intro.git
Note: If you don’t have git installed, follow this Github guide to do so.
The program consists of one Python script called main.py. The entrypoint is located in the final two lines of the script. The Python interpreter knows by design to start execution from this part of the script:
if __name__ == “__main__”: main()
The main() method performs two high level tasks, it establishes the connection with the Astra database and then it inserts data that have been generated:
def main():“””The main routine.””” session = getDBSession() generateDataEntrypoint(session)
Establishing the connection to the Astra database, takes place in the getDBSession() method:
At this step make sure to fill in the correct details for connecting to Astra. In particular make sure to export the three environment variables that the Python codes expects in order to securely and successfully establish the connection to Astra:
ASTRA_PATH_TO_SECURE_BUNDLE
ASTRA_CLIENT_ID
ASTRA_CLIENT_SECRET
Note: ASTRA_CLIENT_ID and ASTRA_CLIENT_SECRET were generated in the above section.
Locate the downloaded bundle zip from the previous step, and copy it in a directory that can be configured as part of the ASTRA_PATH_TO_SECURE_BUNDLE environment variable:
cloud_config= {
‘secure_connect_bundle’: os.environ.get(‘ASTRA_PATH_TO_SECURE_BUNDLE’)
}
For example, if you put the secure bundle zip in the root of the Python project the value of ASTRA_PATH_TO_SECURE_BUNDLE environment variable would need to be equal to ‘../secure-connect-cassandra-pythondemo.zip’ and the root directory of the project would include the following files and folders:
Similarly set ASTRA_CLIENT_ID and ASTRA_CLIENT_SECRET environment variables with the values from the previous step.
Once connection is established, we proceed by generating and inserting data in the generateDataEntrypoint(session) method by passing the Astra session object that was generated in the getDBSession() method in the previous step.
Note: Having hardcoded secrets is not recommended as a best practice; make sure to not use this in production and design your applications with security first mindset. We will not be covering best practices for sourcing secrets securely in this article.
As we are generating fictional data, we are making use of the numpy and random Python libraries to help create a list of ids based on an arbitrary range and then randomly pick one id:
We are also surrounding our generation script with two loops and we run as many times as we configure based on two static variables. For example, the following script will generate 2 timeseries with 10 rows each(based on the timeseries_to_generate and number_of_rows variables):
Inserting the data to Astra takes place in the generateInsertData(t_id, number_of_rows, session) method:
First, we are preparing dummy data with the readings and device_ids variables. For these variables we are creating two more numpy arbitrary lists in the same way we did with timeseries ids previously. We are also introducing a new Python module called datetime in which we use for creating the value_ts and t_pub_ts variables.
Following the initialisation of the above variables, we are preparing the insert statement to Astra with the insert_query variable. A PreparedStatement is particularly useful for queries that are executed multiple times in an application, which fits our use-case. As you can see we are going to call insert_query within the following for loop as many times as the number_of_rows variable is, inserting data to the table we created in the previous step:
session.execute(insert_query, [device_id, t_id, value_ts, t_pub_ts, round(random.choice(readings),2)])
The session.execute(insert_query, data) function call is effectively using the Astra database session that we created in the above step. Its first argument is the insert_query prepared statement, and the second argument is an array-like object that contains the actual data to be inserted into the database table.
Executing the Python script and checking results in Astra
Let’s go ahead and execute the Python script.
Note: Make sure to git clone the repo as well as to follow all the prerequisites as listed at the beginning of this article(installing Python, setting up Astra, setting up the Astra bundle and client id/secret in Python) before attempting to execute this script.
Open a command prompt and navigate to the location of the Python script file. Make sure to configure the number of data to be generated(timeseries_to_generate and number_of_rows variables). Then, execute:
python main.py
Based on the configurations you put together you will get an output similar to the following:
Processing:130483SuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessProcessing:176990SuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccess
The above indicates the execution of the Python program was successful. To check that data has been inserted in Astra, let’s move to the Astra console and execute a CQL script.
In the Astra console, navigate to the CQL Console tab:
Type the following CQL query and hit enter:
select * from cassandra_pythondemo.demo_readings;
This gives the following result set:
The insertion script in Python worked like a charm and we have successfully inserted data in the Astra Cassandra database.
We have now successfully built a Python script that connects to Astra, a serverless Database-as-a-Service powered by Apache Cassandra. We have shown how to navigate the Astra website to create new Cassandra tables, execute queries through the CQL Console, how to generate data in Python using multiple Python libraries such as numpy and datetime and how to configure the connection to Astra with Python cassandra-driver, and insert data with prepared statements. We have also used the astrapy Cassandra Python library to interact with the Astra Document API to insert and retrieve JSON data.
Learn More:
AstraPy
Python Driver for Astra
The code for this Cassandra Python tutorial can be found here:https://github.com/andyadamides/python-cassandra-intro | [
{
"code": null,
"e": 428,
"s": 46,
"text": "Python is one of the most widely used programming languages with a huge and supportive community, while Cassandra is one of the most popular NoSQL databases traditionally used for web applications storage or also data centric applications that are dependent on quick retrieval of data. Together, they are found in many applications across various industries as well as in academia."
},
{
"code": null,
"e": 1143,
"s": 428,
"text": "This Cassandra Python tutorial is intended for beginners in Python and Cassandra. The code samples you can see throughout the article are publicly available in this Github repository. We will guide you through setting up Python as well as DataStax Astra, a managed Cassandra-as-a-Service application hosted on any cloud for free. We will show you how to connect Python to Cassandra and insert data with the Datastax ODBC driver as well as use the Astra web console to query data stored in Cassandra with the CQL console. The upcoming Python SDK for Astra will enable API access for REST, GraphQL and a schemaless JSON document API for a given Astra database instance, which will be reviewed in an upcoming article."
},
{
"code": null,
"e": 1687,
"s": 1143,
"text": "Python has gained plenty of popularity over the past decade and with good reasons. Simply put it is a programming language that is very readable, easy and free to use. It is also easy to get started with, but at the same time it can be used for a variety of different applications and different areas. Multiple Python libraries exist that allow solving problems like string manipulation, implementing machine learning algorithms, object-oriented programming and for data engineering purposes which we will be focusing more on in this tutorial."
},
{
"code": null,
"e": 1970,
"s": 1687,
"text": "There are two major versions of Python available, Python 2 and Python 3. The former is no longer receiving updates nor supported, while the latter is the latest version and the one we will be using. Installing Python can be easily achieved irrespective of the OS that you are using."
},
{
"code": null,
"e": 2141,
"s": 1970,
"text": "The best way to install Python on your computer is through the official Python page. Based on the OS you are using, pick the appropriate installer from the official page."
},
{
"code": null,
"e": 2258,
"s": 2141,
"text": "To verify that Python is correctly installed on your computer, open a command line window and execute the following:"
},
{
"code": null,
"e": 2275,
"s": 2258,
"text": "python --version"
},
{
"code": null,
"e": 2334,
"s": 2275,
"text": "This will return with the version that you just installed:"
},
{
"code": null,
"e": 2347,
"s": 2334,
"text": "Python 3.8.2"
},
{
"code": null,
"e": 2632,
"s": 2347,
"text": "If you correctly installed Python and got a command not found or a similar error message, this will most likely mean that Python has not correctly been added to the PATH variable on your OS; so make sure to double-check that the path that Python was installed on, is part of the PATH."
},
{
"code": null,
"e": 2951,
"s": 2632,
"text": "Like any other programming language, Python also uses a separate utility to install packages. The built-in package manager for Python is called pip. Except from pip, other popular Python package managers include virtualenv and conda, but for the purposes of this Cassandra Python tutorial we are going to be using pip."
},
{
"code": null,
"e": 3294,
"s": 2951,
"text": "Each Python project that uses pip, will usually have a file called requirements.txt in the root directory of the repository, in the same way we have our requirements.txt in our Github project. The contents of this file are very simple; each line consists of the name of the package, optionally followed by a specific version for that package:"
},
{
"code": null,
"e": 3364,
"s": 3294,
"text": "cassandra-driver==3.25.0numpy==1.19.3astrapy==0.0.2simplejson==3.17.2"
},
{
"code": null,
"e": 3541,
"s": 3364,
"text": "To install the required packages which includes Cassandra Python libraries cassandra-driver and astrapy, simply navigate to the root directory in your command line and execute:"
},
{
"code": null,
"e": 3573,
"s": 3541,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 3969,
"s": 3573,
"text": "What happens in the background, is that pip will fetch these packages from the default and public Python Package Index, PyPi. You can inspect the PyPi homepage of each package, including available versions, further documentation, links to each package’s Github repository and examples of how to use each package. For example this is the page for numpy, and this is the page for cassandra-driver."
},
{
"code": null,
"e": 4044,
"s": 3969,
"text": "This completes the installation of the dependencies of our Python project."
},
{
"code": null,
"e": 4740,
"s": 4044,
"text": "Cassandra is the leading open-source NoSQL distributed database management system(DBMS). In contrast to traditional SQL DBMS like Oracle or SQL Server, NoSQL databases follow a different storage model. While in SQL systems data is organised in tables and columns that are driven from fixed schemas, in Cassandra a fixed schema is not enforced, a dynamic number of columns within the same table(or column-family as a table is often called within Cassandra) is allowed as well as being able to handle and store unstructured data. In addition to the above, the language which is used to interact with Cassandra is a variant (and subset) of the traditional SQL, called Cassandra Query Language(CQL)."
},
{
"code": null,
"e": 5228,
"s": 4740,
"text": "Cassandra is used by 90% of Fortune 100 companies. The fact that is rapidly growing can be explained by its set of rich features that are particularly beneficial for large amounts of data. Its distributed architecture ensures ultra fast write performance, and fast retrievals for data querying, no single point of failure which results in 100% high availability and significant reduction in time to market due to the simplicity of deploying, managing and maintaining a Cassandra Cluster."
},
{
"code": null,
"e": 5522,
"s": 5228,
"text": "Cassandra is open source which means it’s free to use. Depending on the OS you are using, you can download Cassandra and its dependencies locally, configure and install them. Kubernetes users can also use Docker images, but all of this process can be tiresome, especially for first-time users."
},
{
"code": null,
"e": 5883,
"s": 5522,
"text": "The best way to get started with Cassandra, is through a managed Cassandra database which is available through the web. Datastax Astra is a serverless database-as-a-Service powered by Apache Cassandra which can be launched with just a few clicks, has a generous free tier, and is available in major cloud providers (Amazon Web Services, Azure or Google Cloud)."
},
{
"code": null,
"e": 6101,
"s": 5883,
"text": "The official Astra guide has all the information you need to create an Astra service; you need to register for an account and then select a few more details, such as choosing a cloud provider and naming your database."
},
{
"code": null,
"e": 6469,
"s": 6101,
"text": "Using React, Angular or Vue as a frontend? astrapy is a handy Cassandra Python library that creates a schemaless, JSON document oriented API atop Datastax Astra’s REST API. In this example we are going to authenticate to Astra using a token(instead of client secret), generate a dummy JSON document and issue a PUT REST call to insert the JSON in an Astra collection."
},
{
"code": null,
"e": 6743,
"s": 6469,
"text": "Before navigating through the code make sure you have astrapy and simplejson libraries installed. You can check that by executing pip freeze. If you don’t have them install them from the requirements.txt file in the root of the project with pip install -r requirements.txt."
},
{
"code": null,
"e": 6970,
"s": 6743,
"text": "First in the code, we will get an Astra HTTP client. Before doing so, we need to generate an application token and export five environment variables in total. Navigate to Datastax Astra homepage and click on the database name:"
},
{
"code": null,
"e": 7024,
"s": 6970,
"text": "Then, just below the database name, click on Connect:"
},
{
"code": null,
"e": 7078,
"s": 7024,
"text": "This time, remain on the Connect using an API option:"
},
{
"code": null,
"e": 7171,
"s": 7078,
"text": "Note 3 of the 5 environment variables that you need to export in the right part of the page:"
},
{
"code": null,
"e": 7183,
"s": 7171,
"text": "ASTRA_DB_ID"
},
{
"code": null,
"e": 7199,
"s": 7183,
"text": "ASTRA_DB_REGION"
},
{
"code": null,
"e": 7217,
"s": 7199,
"text": "ASTRA_DB_KEYSPACE"
},
{
"code": null,
"e": 7345,
"s": 7217,
"text": "For the ASTRA_DB_APPLICATION_TOKEN environment variable, let’s generate the connection credentials. Click where it says “here”:"
},
{
"code": null,
"e": 7430,
"s": 7345,
"text": "A new page will popup, select the role(select R/W User) and click on Generate Token:"
},
{
"code": null,
"e": 7487,
"s": 7430,
"text": "Once you do, you will get a window with all the details:"
},
{
"code": null,
"e": 7742,
"s": 7487,
"text": "Make sure to keep the other(Client Id, Client Secret) information in a place where you can reference them as we will use them later. Export the ASTRA_DB_APPLICATION_TOKEN environment variable, which is equal to the token that was generated in this step.."
},
{
"code": null,
"e": 7882,
"s": 7742,
"text": "Fill in any name you like for the fifth and final environment variable ASTRA_DB_COLLECTION. In my case this variable is equal to demo_book."
},
{
"code": null,
"e": 8110,
"s": 7882,
"text": "Once you have exported the five environment variables according to the OS you are using, you are ready to start execution of the Python script. The first part will authenticate against Datastax Astra using token authentication:"
},
{
"code": null,
"e": 8251,
"s": 8110,
"text": "Once we have the HTTP client object, that is passed to the next method in which we create and insert a JSON document to an Astra collection:"
},
{
"code": null,
"e": 8328,
"s": 8251,
"text": "To execute the Python script type python json_document_api.py and hit enter."
},
{
"code": null,
"e": 8478,
"s": 8328,
"text": "Finally we can confirm that the document has been inserted successfully by issuing a curl command to retrieve it through the command line as follows:"
},
{
"code": null,
"e": 8555,
"s": 8478,
"text": "This command will return all documents that have been inserted, in our case:"
},
{
"code": null,
"e": 8999,
"s": 8555,
"text": "The Cassandra Python cassandra-driver makes it easy to authenticate and insert tabular data in Datastax Astra.Up to this point we have made sure to install Python and to have an Astra serverless instance that we can work with using a schemless, JSON Document — oriented API. Let’s continue by actually interacting with our Astra database using the cassandra-driver as an schema — driven alternative to the Document API in the Astra Python SDK."
},
{
"code": null,
"e": 9205,
"s": 8999,
"text": "Before starting to code, we need to get the prerequisites for configuring the connection from Python to Astra. From the Astra dashboard page, click on the database name from the left hand side of the page:"
},
{
"code": null,
"e": 9259,
"s": 9205,
"text": "Then, just below the database name, click on Connect:"
},
{
"code": null,
"e": 9296,
"s": 9259,
"text": "Choose Python from the drivers list:"
},
{
"code": null,
"e": 9653,
"s": 9296,
"text": "Now you will see a detailed guide of the steps you need to follow pop up on the right side of the page. First, we will make sure to download the bundle and store it in our local storage. We will reference this later in our code. On the right hand side of the page, click on the Download Bundle button and then on click on Secure Connect Bundle popup button"
},
{
"code": null,
"e": 10016,
"s": 9653,
"text": "This will download the bundle in the default downloads directory configured from your browser. This is usually located in your home directory, with the name of the bundle following a specific naming format of secure-connect-<database-name>.zip, for example in our case it is named secure-connect-cassandra-pythondemo.zip. Note the location of the downloaded zip."
},
{
"code": null,
"e": 10190,
"s": 10016,
"text": "In this section we are going to be generating a fictional time series dataset in Python and insert the data in our Astra database using the Datastax Python ODBC/JDBC driver."
},
{
"code": null,
"e": 10363,
"s": 10190,
"text": "First, we are going to create the Astra table that will hold our data. Navigate to the Astra dashboard page, click on the database name from the left hand side of the page:"
},
{
"code": null,
"e": 10415,
"s": 10363,
"text": "Click on the Cassandra Query Language(CQL) Console:"
},
{
"code": null,
"e": 10516,
"s": 10415,
"text": "Copy the intro/demo_readings.sql from the Github repo and paste it on the CQL Console and hit Enter:"
},
{
"code": null,
"e": 10869,
"s": 10516,
"text": "This completes the creation of the Astra table. As you can see in the above DDL script, this timeseries dataset consists of floating value metric(value) that is captured in continuous intervals(value_ts) for a fictional pair of hardware(device_id and timeseries_id), while the timestamp of when the record was captured is also included(publication_ts)."
},
{
"code": null,
"e": 11010,
"s": 10869,
"text": "Following the creation of the Cassandra table, let’s navigate to Python. First, make sure to git clone the project in your local filesystem:"
},
{
"code": null,
"e": 11075,
"s": 11010,
"text": "git clone [email protected]:andyadamides/python-cassandra-intro.git"
},
{
"code": null,
"e": 11149,
"s": 11075,
"text": "Note: If you don’t have git installed, follow this Github guide to do so."
},
{
"code": null,
"e": 11359,
"s": 11149,
"text": "The program consists of one Python script called main.py. The entrypoint is located in the final two lines of the script. The Python interpreter knows by design to start execution from this part of the script:"
},
{
"code": null,
"e": 11396,
"s": 11359,
"text": "if __name__ == “__main__”: main()"
},
{
"code": null,
"e": 11550,
"s": 11396,
"text": "The main() method performs two high level tasks, it establishes the connection with the Astra database and then it inserts data that have been generated:"
},
{
"code": null,
"e": 11648,
"s": 11550,
"text": "def main():“””The main routine.””” session = getDBSession() generateDataEntrypoint(session)"
},
{
"code": null,
"e": 11741,
"s": 11648,
"text": "Establishing the connection to the Astra database, takes place in the getDBSession() method:"
},
{
"code": null,
"e": 11989,
"s": 11741,
"text": "At this step make sure to fill in the correct details for connecting to Astra. In particular make sure to export the three environment variables that the Python codes expects in order to securely and successfully establish the connection to Astra:"
},
{
"code": null,
"e": 12017,
"s": 11989,
"text": "ASTRA_PATH_TO_SECURE_BUNDLE"
},
{
"code": null,
"e": 12033,
"s": 12017,
"text": "ASTRA_CLIENT_ID"
},
{
"code": null,
"e": 12053,
"s": 12033,
"text": "ASTRA_CLIENT_SECRET"
},
{
"code": null,
"e": 12136,
"s": 12053,
"text": "Note: ASTRA_CLIENT_ID and ASTRA_CLIENT_SECRET were generated in the above section."
},
{
"code": null,
"e": 12308,
"s": 12136,
"text": "Locate the downloaded bundle zip from the previous step, and copy it in a directory that can be configured as part of the ASTRA_PATH_TO_SECURE_BUNDLE environment variable:"
},
{
"code": null,
"e": 12324,
"s": 12308,
"text": "cloud_config= {"
},
{
"code": null,
"e": 12395,
"s": 12324,
"text": "‘secure_connect_bundle’: os.environ.get(‘ASTRA_PATH_TO_SECURE_BUNDLE’)"
},
{
"code": null,
"e": 12397,
"s": 12395,
"text": "}"
},
{
"code": null,
"e": 12695,
"s": 12397,
"text": "For example, if you put the secure bundle zip in the root of the Python project the value of ASTRA_PATH_TO_SECURE_BUNDLE environment variable would need to be equal to ‘../secure-connect-cassandra-pythondemo.zip’ and the root directory of the project would include the following files and folders:"
},
{
"code": null,
"e": 12811,
"s": 12695,
"text": "Similarly set ASTRA_CLIENT_ID and ASTRA_CLIENT_SECRET environment variables with the values from the previous step."
},
{
"code": null,
"e": 13039,
"s": 12811,
"text": "Once connection is established, we proceed by generating and inserting data in the generateDataEntrypoint(session) method by passing the Astra session object that was generated in the getDBSession() method in the previous step."
},
{
"code": null,
"e": 13293,
"s": 13039,
"text": "Note: Having hardcoded secrets is not recommended as a best practice; make sure to not use this in production and design your applications with security first mindset. We will not be covering best practices for sourcing secrets securely in this article."
},
{
"code": null,
"e": 13477,
"s": 13293,
"text": "As we are generating fictional data, we are making use of the numpy and random Python libraries to help create a list of ids based on an arbitrary range and then randomly pick one id:"
},
{
"code": null,
"e": 13756,
"s": 13477,
"text": "We are also surrounding our generation script with two loops and we run as many times as we configure based on two static variables. For example, the following script will generate 2 timeseries with 10 rows each(based on the timeseries_to_generate and number_of_rows variables):"
},
{
"code": null,
"e": 13861,
"s": 13756,
"text": "Inserting the data to Astra takes place in the generateInsertData(t_id, number_of_rows, session) method:"
},
{
"code": null,
"e": 14188,
"s": 13861,
"text": "First, we are preparing dummy data with the readings and device_ids variables. For these variables we are creating two more numpy arbitrary lists in the same way we did with timeseries ids previously. We are also introducing a new Python module called datetime in which we use for creating the value_ts and t_pub_ts variables."
},
{
"code": null,
"e": 14641,
"s": 14188,
"text": "Following the initialisation of the above variables, we are preparing the insert statement to Astra with the insert_query variable. A PreparedStatement is particularly useful for queries that are executed multiple times in an application, which fits our use-case. As you can see we are going to call insert_query within the following for loop as many times as the number_of_rows variable is, inserting data to the table we created in the previous step:"
},
{
"code": null,
"e": 14744,
"s": 14641,
"text": "session.execute(insert_query, [device_id, t_id, value_ts, t_pub_ts, round(random.choice(readings),2)])"
},
{
"code": null,
"e": 15058,
"s": 14744,
"text": "The session.execute(insert_query, data) function call is effectively using the Astra database session that we created in the above step. Its first argument is the insert_query prepared statement, and the second argument is an array-like object that contains the actual data to be inserted into the database table."
},
{
"code": null,
"e": 15116,
"s": 15058,
"text": "Executing the Python script and checking results in Astra"
},
{
"code": null,
"e": 15162,
"s": 15116,
"text": "Let’s go ahead and execute the Python script."
},
{
"code": null,
"e": 15425,
"s": 15162,
"text": "Note: Make sure to git clone the repo as well as to follow all the prerequisites as listed at the beginning of this article(installing Python, setting up Astra, setting up the Astra bundle and client id/secret in Python) before attempting to execute this script."
},
{
"code": null,
"e": 15630,
"s": 15425,
"text": "Open a command prompt and navigate to the location of the Python script file. Make sure to configure the number of data to be generated(timeseries_to_generate and number_of_rows variables). Then, execute:"
},
{
"code": null,
"e": 15645,
"s": 15630,
"text": "python main.py"
},
{
"code": null,
"e": 15739,
"s": 15645,
"text": "Based on the configurations you put together you will get an output similar to the following:"
},
{
"code": null,
"e": 15914,
"s": 15739,
"text": "Processing:130483SuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessProcessing:176990SuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccessSuccess"
},
{
"code": null,
"e": 16091,
"s": 15914,
"text": "The above indicates the execution of the Python program was successful. To check that data has been inserted in Astra, let’s move to the Astra console and execute a CQL script."
},
{
"code": null,
"e": 16146,
"s": 16091,
"text": "In the Astra console, navigate to the CQL Console tab:"
},
{
"code": null,
"e": 16190,
"s": 16146,
"text": "Type the following CQL query and hit enter:"
},
{
"code": null,
"e": 16240,
"s": 16190,
"text": "select * from cassandra_pythondemo.demo_readings;"
},
{
"code": null,
"e": 16277,
"s": 16240,
"text": "This gives the following result set:"
},
{
"code": null,
"e": 16400,
"s": 16277,
"text": "The insertion script in Python worked like a charm and we have successfully inserted data in the Astra Cassandra database."
},
{
"code": null,
"e": 16992,
"s": 16400,
"text": "We have now successfully built a Python script that connects to Astra, a serverless Database-as-a-Service powered by Apache Cassandra. We have shown how to navigate the Astra website to create new Cassandra tables, execute queries through the CQL Console, how to generate data in Python using multiple Python libraries such as numpy and datetime and how to configure the connection to Astra with Python cassandra-driver, and insert data with prepared statements. We have also used the astrapy Cassandra Python library to interact with the Astra Document API to insert and retrieve JSON data."
},
{
"code": null,
"e": 17004,
"s": 16992,
"text": "Learn More:"
},
{
"code": null,
"e": 17012,
"s": 17004,
"text": "AstraPy"
},
{
"code": null,
"e": 17036,
"s": 17012,
"text": "Python Driver for Astra"
}
] |
How to catch EOFError Exception in Python? | An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file.
The given code is rewritten as follows to catch the EOFError and find its type.
#eofError.py
try:
while True:
data = raw_input('prompt:')
print 'READ:', data
except EOFError as e:
print e
Then if we run the script at the terminal
$ echo hello | python eofError.py
prompt:READ: hello
prompt:EOF when reading a line | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file."
},
{
"code": null,
"e": 1365,
"s": 1285,
"text": "The given code is rewritten as follows to catch the EOFError and find its type."
},
{
"code": null,
"e": 1549,
"s": 1365,
"text": "#eofError.py\ntry:\nwhile True:\ndata = raw_input('prompt:')\nprint 'READ:', data\nexcept EOFError as e:\nprint e\nThen if we run the script at the terminal\n$ echo hello | python eofError.py"
},
{
"code": null,
"e": 1599,
"s": 1549,
"text": "prompt:READ: hello\nprompt:EOF when reading a line"
}
] |
How to use jQuery.serializeArray() method to serialize data? | The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
Assuming we have following PHP content in serialize.php file −
<?php
if( $_REQUEST["name"] ) {
$name = $_REQUEST['name'];
echo "Welcome ". $name;
$age = $_REQUEST['age'];
echo "<br />Your age : ". $age;
$sex = $_REQUEST['sex'];
echo "<br />Your gender : ". $sex;
}
?>
The following is an example showing the usage of this method −
Live Demo
<html>
<head>
<title>The jQuery Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#driver").click(function(event){
$.post(
"/jquery/serialize.php",
$("#testform").serializeArray(),
function(data) {
$('#stage1').html(data);
}
);
var fields = $("#testform").serializeArray();
$("#stage2").empty();
jQuery.each(fields, function(i, field){
$("#stage2").append(field.value + " ");
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<br />
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<form id = "testform">
<table>
<tr>
<td><p>Name:</p></td>
<td><input type = "text" name = "name" size = "40" /></td>
</tr>
<tr>
<td><p>Age:</p></td>
<td><input type = "text" name = "age" size = "40" /></td>
</tr>
<tr>
<td><p>Sex:</p></td>
<td> <select name = "sex">
<option value = "Male" selected>Male</option>
<option value = "Female" selected>Female</option>
</select></td>
</tr>
<tr>
<td colspan = "2">
<input type = "button" id = "driver" value = "Load Data" />
</td>
</tr>
</table>
</form>
</body>
</html> | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with."
},
{
"code": null,
"e": 1278,
"s": 1215,
"text": "Assuming we have following PHP content in serialize.php file −"
},
{
"code": null,
"e": 1502,
"s": 1278,
"text": "<?php\nif( $_REQUEST[\"name\"] ) {\n\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n $age = $_REQUEST['age'];\n echo \"<br />Your age : \". $age;\n $sex = $_REQUEST['sex'];\n echo \"<br />Your gender : \". $sex;\n}\n?>"
},
{
"code": null,
"e": 1565,
"s": 1502,
"text": "The following is an example showing the usage of this method −"
},
{
"code": null,
"e": 1575,
"s": 1565,
"text": "Live Demo"
},
{
"code": null,
"e": 3707,
"s": 1575,
"text": "<html>\n\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"#driver\").click(function(event){\n \n $.post(\n \"/jquery/serialize.php\",\n $(\"#testform\").serializeArray(),\n function(data) {\n $('#stage1').html(data);\n }\n );\n \n var fields = $(\"#testform\").serializeArray();\n $(\"#stage2\").empty();\n \n jQuery.each(fields, function(i, field){\n $(\"#stage2\").append(field.value + \" \");\n });\n \n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n \n <br />\n \n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n \n <form id = \"testform\">\n \n <table>\n \n <tr>\n <td><p>Name:</p></td>\n <td><input type = \"text\" name = \"name\" size = \"40\" /></td>\n </tr>\n \n <tr>\n <td><p>Age:</p></td>\n <td><input type = \"text\" name = \"age\" size = \"40\" /></td>\n </tr>\n \n <tr>\n <td><p>Sex:</p></td>\n <td> <select name = \"sex\">\n <option value = \"Male\" selected>Male</option>\n <option value = \"Female\" selected>Female</option>\n </select></td>\n </tr>\n \n <tr>\n <td colspan = \"2\">\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </td>\n </tr> \n \n </table>\n \n </form>\n \n </body>\n</html>"
}
] |
JSF - h:outputScript | The h:outputScript tag renders an HTML element of the type "script" with type "text/javascript". This tag is used to add an external javascript file to JSF page.
<h:outputScript library = "js" name = "help.js" />
<script type = "text/javascript"
src = "/helloworld/javax.faces.resource/help.js.jsf?ln = js"></script>
Let us create a test JSF application to test the above tag.
function showMessage(){
alert("Hello World!");
}
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
<h:outputScript library = "js" name = "help.js" />
</h:head>
<h:body>
<h2>h:outputScript example</h2>
<hr />
<h:form>
<h:commandButton onclick = "showMessage();" />
</h:form>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2114,
"s": 1952,
"text": "The h:outputScript tag renders an HTML element of the type \"script\" with type \"text/javascript\". This tag is used to add an external javascript file to JSF page."
},
{
"code": null,
"e": 2166,
"s": 2114,
"text": "<h:outputScript library = \"js\" name = \"help.js\" /> "
},
{
"code": null,
"e": 2277,
"s": 2166,
"text": "<script type = \"text/javascript\" \n src = \"/helloworld/javax.faces.resource/help.js.jsf?ln = js\"></script> \n"
},
{
"code": null,
"e": 2337,
"s": 2277,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 2390,
"s": 2337,
"text": "function showMessage(){\n alert(\"Hello World!\");\t\n}"
},
{
"code": null,
"e": 4959,
"s": 2390,
"text": "<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/maven-v4_0_0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url>\n \n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>jstl</artifactId>\n <version>1.2</version>\n </dependency>\n </dependencies>\n \n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n \n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>copy-resources</id>\n <phase>validate</phase>\n <goals>\n <goal>copy-resources</goal>\n </goals>\n \n <configuration>\n <outputDirectory>${basedir}/target/helloworld/resources\n </outputDirectory>\n <resources> \n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources> \n </configuration> \n </execution>\n </executions>\n </plugin>\n \n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 5570,
"s": 4959,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n <h:outputScript library = \"js\" name = \"help.js\" /> \n </h:head>\n \n <h:body>\n <h2>h:outputScript example</h2>\n <hr />\n <h:form>\n <h:commandButton onclick = \"showMessage();\" />\n </h:form> \t\t\n \n </h:body>\n</html> "
},
{
"code": null,
"e": 5786,
"s": 5570,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 5821,
"s": 5786,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5836,
"s": 5821,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5843,
"s": 5836,
"text": " Print"
},
{
"code": null,
"e": 5854,
"s": 5843,
"text": " Add Notes"
}
] |
How to use range-based for() loop with std::map? | Here we will see how to use the range based for loop for std::map type objects. In C++, we know that there are map type objects. That can store key value pairs. The map basically stores the pair objects. This pair object is used to store one key and corresponding value. These keys and values are implemented using templates, so we can use any type of data.
To use the range based for loop, we can define for loop that can iterate through each pair of the map. Let us see the code to get the better idea.
#include<iostream>
#include<map>
using namespace std;
main() {
map<char, string> my_map;
my_map.insert(pair<char, string>('A', "Apple"));
my_map.insert(pair<char, string>('B', "Ball"));
my_map.insert(pair<char, string>('C', "Cat"));
my_map.insert(pair<char, string>('D', "Dog"));
my_map.insert(pair<char, string>('E', "Eagle"));
my_map.insert(pair<char, string>('F', "Flag"));
my_map.insert(pair<char, string>('G', "Ghost"));
my_map.insert(pair<char, string>('H', "Hill"));
my_map.insert(pair<char, string>('I', "India"));
my_map.insert(pair<char, string>('J', "Jug"));
for(auto& key_val : my_map) {
cout << "The " << key_val.first << " is pointing to: " << key_val.second << endl;
}
}
The A is pointing to: Apple
The B is pointing to: Ball
The C is pointing to: Cat
The D is pointing to: Dog
The E is pointing to: Eagle
The F is pointing to: Flag
The G is pointing to: Ghost
The H is pointing to: Hill
The I is pointing to: India
The J is pointing to: Jug | [
{
"code": null,
"e": 1420,
"s": 1062,
"text": "Here we will see how to use the range based for loop for std::map type objects. In C++, we know that there are map type objects. That can store key value pairs. The map basically stores the pair objects. This pair object is used to store one key and corresponding value. These keys and values are implemented using templates, so we can use any type of data."
},
{
"code": null,
"e": 1567,
"s": 1420,
"text": "To use the range based for loop, we can define for loop that can iterate through each pair of the map. Let us see the code to get the better idea."
},
{
"code": null,
"e": 2298,
"s": 1567,
"text": "#include<iostream>\n#include<map>\nusing namespace std;\nmain() {\n map<char, string> my_map;\n my_map.insert(pair<char, string>('A', \"Apple\"));\n my_map.insert(pair<char, string>('B', \"Ball\"));\n my_map.insert(pair<char, string>('C', \"Cat\"));\n my_map.insert(pair<char, string>('D', \"Dog\"));\n my_map.insert(pair<char, string>('E', \"Eagle\"));\n my_map.insert(pair<char, string>('F', \"Flag\"));\n my_map.insert(pair<char, string>('G', \"Ghost\"));\n my_map.insert(pair<char, string>('H', \"Hill\"));\n my_map.insert(pair<char, string>('I', \"India\"));\n my_map.insert(pair<char, string>('J', \"Jug\"));\n for(auto& key_val : my_map) {\n cout << \"The \" << key_val.first << \" is pointing to: \" << key_val.second << endl;\n }\n}"
},
{
"code": null,
"e": 2569,
"s": 2298,
"text": "The A is pointing to: Apple\nThe B is pointing to: Ball\nThe C is pointing to: Cat\nThe D is pointing to: Dog\nThe E is pointing to: Eagle\nThe F is pointing to: Flag\nThe G is pointing to: Ghost\nThe H is pointing to: Hill\nThe I is pointing to: India\nThe J is pointing to: Jug"
}
] |
How to update two columns in a MySQL database? | You can update two columns using SET command separated with comma(,). The syntax is as follows −
UPDATE yourTableName SET yourColumnName1 = ’yourValue1’, yourColumnName2 = ’yourValue2’ where yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table StudentInformations
-> (
-> StudentId int not null auto_increment,
-> StudentFirstName varchar(20),
-> StudentLastName varchar(20),
-> Primary Key(StudentId)
-> );
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('John','Smith');
Query OK, 1 row affected (0.16 sec)
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('Carol','Taylor');
Query OK, 1 row affected (0.17 sec)
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('Mike','Jones');
Query OK, 1 row affected (0.13 sec)
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('Sam','Williams');
Query OK, 1 row affected (0.16 sec)
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('Bob','Davis');
Query OK, 1 row affected (0.14 sec)
mysql> insert into StudentInformations(StudentFirstName,StudentLastName)
values('David','Miller');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from StudentInformations;
The following is the output.
+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1 | John | Smith |
| 2 | Carol | Taylor |
| 3 | Mike | Jones |
| 4 | Sam | Williams |
| 5 | Bob | Davis |
| 6 | David | Miller |
+-----------+------------------+-----------------+
6 rows in set (0.00 sec)
Here is the query to update two columns in MySQL database. We are updating the records of student with id 3 −
mysql> update StudentInformations set StudentFirstName = 'Robert',
StudentLastName = 'Brown' where
-> StudentId = 3;
Query OK, 1 row affected (0.12 sec)
Rows matched − 1 Changed − 1 Warnings − 0
Check the updated value in the table using select statement. The query is as follows −
mysql> select *from StudentInformations;
The following is the output −
+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1 | John | Smith |
| 2 | Carol | Taylor |
| 3 | Robert | Brown |
| 4 | Sam | Williams |
| 5 | Bob | Davis |
| 6 | David | Miller |
+-----------+------------------+-----------------+
6 rows in set (0.00 sec)
Now, you can see above, the StudentId 3 records i.e. StudentFirstName and StudentLastName values have been changed successfully. | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "You can update two columns using SET command separated with comma(,). The syntax is as follows −"
},
{
"code": null,
"e": 1268,
"s": 1159,
"text": "UPDATE yourTableName SET yourColumnName1 = ’yourValue1’, yourColumnName2 = ’yourValue2’ where yourCondition;"
},
{
"code": null,
"e": 1367,
"s": 1268,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1606,
"s": 1367,
"text": "mysql> create table StudentInformations\n -> (\n -> StudentId int not null auto_increment,\n -> StudentFirstName varchar(20),\n -> StudentLastName varchar(20),\n -> Primary Key(StudentId)\n -> );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1687,
"s": 1606,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2495,
"s": 1687,
"text": "mysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('John','Smith');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('Carol','Taylor');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('Mike','Jones');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('Sam','Williams');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('Bob','Davis');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into StudentInformations(StudentFirstName,StudentLastName)\nvalues('David','Miller');\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2580,
"s": 2495,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2621,
"s": 2580,
"text": "mysql> select *from StudentInformations;"
},
{
"code": null,
"e": 2650,
"s": 2621,
"text": "The following is the output."
},
{
"code": null,
"e": 3185,
"s": 2650,
"text": "+-----------+------------------+-----------------+\n| StudentId | StudentFirstName | StudentLastName |\n+-----------+------------------+-----------------+\n| 1 | John | Smith |\n| 2 | Carol | Taylor |\n| 3 | Mike | Jones |\n| 4 | Sam | Williams |\n| 5 | Bob | Davis |\n| 6 | David | Miller |\n+-----------+------------------+-----------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3295,
"s": 3185,
"text": "Here is the query to update two columns in MySQL database. We are updating the records of student with id 3 −"
},
{
"code": null,
"e": 3493,
"s": 3295,
"text": "mysql> update StudentInformations set StudentFirstName = 'Robert',\nStudentLastName = 'Brown' where\n -> StudentId = 3;\nQuery OK, 1 row affected (0.12 sec)\nRows matched − 1 Changed − 1 Warnings − 0"
},
{
"code": null,
"e": 3580,
"s": 3493,
"text": "Check the updated value in the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 3621,
"s": 3580,
"text": "mysql> select *from StudentInformations;"
},
{
"code": null,
"e": 3651,
"s": 3621,
"text": "The following is the output −"
},
{
"code": null,
"e": 4186,
"s": 3651,
"text": "+-----------+------------------+-----------------+\n| StudentId | StudentFirstName | StudentLastName |\n+-----------+------------------+-----------------+\n| 1 | John | Smith |\n| 2 | Carol | Taylor |\n| 3 | Robert | Brown |\n| 4 | Sam | Williams |\n| 5 | Bob | Davis |\n| 6 | David | Miller |\n+-----------+------------------+-----------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4315,
"s": 4186,
"text": "Now, you can see above, the StudentId 3 records i.e. StudentFirstName and StudentLastName values have been changed successfully."
}
] |
Tryit Editor v3.7 - Show Java | public class CreateFileDir {
public static void main(String[] args) {
try {
File myObj = new File("C:\\Users\\MyName\\filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred."); | [] |
How to use OpenCV with GPU on Colab? | by C K | Towards Data Science | OpenCV’s ‘Deep Neural Network’ (dnn) module is a convenient tool for computer vision, it is very easy to apply some techniques such as Yolo and OpenPose. However, the major drawback of OpenCV was the lack of GPU support, resulting in slow inference. Luckily since OpenCV 4.2, NVIDIA GPU/CUDA is supported.
It still required some works to use GPU, you can check Pyimagesearch’s article here, they demonstrate how to set up a Ubuntu machine.
If you do not have a machine with GPU like me, you can consider using Google Colab, which is a free service with powerful NVIDIA GPU. It is also a lot easier to set up, most of the requirements are already satisfied. In this article, I will share how I set up the Colab environment for OpenCV’s dnn with GPU in just a few lines of code. You can also check here, I made slight changes based on the answer.
The code to assign the dnnto GPU is simple:
import cv2net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
However, if you run this cell directly on Colab, you will see this error:
So we need to do something.
If you check the version of the pre-installed OpenCV on Colab, you will see this:
We need to install cv2 ourselves.
First, run this cell:
%cd /content!git clone https://github.com/opencv/opencv!git clone https://github.com/opencv/opencv_contrib!mkdir /content/build%cd /content/build!cmake -DOPENCV_EXTRA_MODULES_PATH=/content/opencv_contrib/modules -DBUILD_SHARED_LIBS=OFF -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DWITH_OPENEXR=OFF -DWITH_CUDA=ON -DWITH_CUBLAS=ON -DWITH_CUDNN=ON -DOPENCV_DNN_CUDA=ON /content/opencv!make -j8 install
you will see something like this:
It is going to take a while, after completion you can check the version of OpenCV.
Let is it! Now you should be able to set the dnn to CUDA without error.
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
But the first step takes a lot of time, and you need to do it every time you start the notebook. This is time-consuming and not ideal.
One thing you can do here is to save the result of the first step to your Google Drive (you have to mount it ).
!mkdir "/content/gdrive/My Drive/cv2_gpu"!cp /content/build/lib/python3/cv2.cpython-36m-x86_64-linux-gnu.so "/content/gdrive/My Drive/cv2_gpu"
Then copy it to your working directory next time you start the notebook.
!cp "/content/gdrive/My Drive/cv2_gpu/cv2.cpython-36m-x86_64-linux-gnu.so" .
and check the version to make sure it is done.
If you do not want to mount your Google Drive, you can upload it to the cloud somewhere and download it using !wget to your working dir.
That is it. Thanks for reading. Have fun with the GPU. | [
{
"code": null,
"e": 477,
"s": 171,
"text": "OpenCV’s ‘Deep Neural Network’ (dnn) module is a convenient tool for computer vision, it is very easy to apply some techniques such as Yolo and OpenPose. However, the major drawback of OpenCV was the lack of GPU support, resulting in slow inference. Luckily since OpenCV 4.2, NVIDIA GPU/CUDA is supported."
},
{
"code": null,
"e": 611,
"s": 477,
"text": "It still required some works to use GPU, you can check Pyimagesearch’s article here, they demonstrate how to set up a Ubuntu machine."
},
{
"code": null,
"e": 1016,
"s": 611,
"text": "If you do not have a machine with GPU like me, you can consider using Google Colab, which is a free service with powerful NVIDIA GPU. It is also a lot easier to set up, most of the requirements are already satisfied. In this article, I will share how I set up the Colab environment for OpenCV’s dnn with GPU in just a few lines of code. You can also check here, I made slight changes based on the answer."
},
{
"code": null,
"e": 1060,
"s": 1016,
"text": "The code to assign the dnnto GPU is simple:"
},
{
"code": null,
"e": 1223,
"s": 1060,
"text": "import cv2net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)"
},
{
"code": null,
"e": 1297,
"s": 1223,
"text": "However, if you run this cell directly on Colab, you will see this error:"
},
{
"code": null,
"e": 1325,
"s": 1297,
"text": "So we need to do something."
},
{
"code": null,
"e": 1407,
"s": 1325,
"text": "If you check the version of the pre-installed OpenCV on Colab, you will see this:"
},
{
"code": null,
"e": 1441,
"s": 1407,
"text": "We need to install cv2 ourselves."
},
{
"code": null,
"e": 1463,
"s": 1441,
"text": "First, run this cell:"
},
{
"code": null,
"e": 1885,
"s": 1463,
"text": "%cd /content!git clone https://github.com/opencv/opencv!git clone https://github.com/opencv/opencv_contrib!mkdir /content/build%cd /content/build!cmake -DOPENCV_EXTRA_MODULES_PATH=/content/opencv_contrib/modules -DBUILD_SHARED_LIBS=OFF -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DWITH_OPENEXR=OFF -DWITH_CUDA=ON -DWITH_CUBLAS=ON -DWITH_CUDNN=ON -DOPENCV_DNN_CUDA=ON /content/opencv!make -j8 install"
},
{
"code": null,
"e": 1919,
"s": 1885,
"text": "you will see something like this:"
},
{
"code": null,
"e": 2002,
"s": 1919,
"text": "It is going to take a while, after completion you can check the version of OpenCV."
},
{
"code": null,
"e": 2074,
"s": 2002,
"text": "Let is it! Now you should be able to set the dnn to CUDA without error."
},
{
"code": null,
"e": 2173,
"s": 2074,
"text": "net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)"
},
{
"code": null,
"e": 2308,
"s": 2173,
"text": "But the first step takes a lot of time, and you need to do it every time you start the notebook. This is time-consuming and not ideal."
},
{
"code": null,
"e": 2420,
"s": 2308,
"text": "One thing you can do here is to save the result of the first step to your Google Drive (you have to mount it )."
},
{
"code": null,
"e": 2567,
"s": 2420,
"text": "!mkdir \"/content/gdrive/My Drive/cv2_gpu\"!cp /content/build/lib/python3/cv2.cpython-36m-x86_64-linux-gnu.so \"/content/gdrive/My Drive/cv2_gpu\""
},
{
"code": null,
"e": 2640,
"s": 2567,
"text": "Then copy it to your working directory next time you start the notebook."
},
{
"code": null,
"e": 2717,
"s": 2640,
"text": "!cp \"/content/gdrive/My Drive/cv2_gpu/cv2.cpython-36m-x86_64-linux-gnu.so\" ."
},
{
"code": null,
"e": 2764,
"s": 2717,
"text": "and check the version to make sure it is done."
},
{
"code": null,
"e": 2901,
"s": 2764,
"text": "If you do not want to mount your Google Drive, you can upload it to the cloud somewhere and download it using !wget to your working dir."
}
] |
Working with XlsxWriter module - Python - GeeksforGeeks | 22 Nov, 2021
XlsxWriter is a Python module that provides various methods to work with Excel using Python. It can be used to read, write, applying formulas. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others.
This tutorial aims at providing knowledge about the XlsxWriter module from basics to advance with the help well explained examples and concepts.
Before diving deep into the module let’s start by installing it. To install it type the below command in the terminal.
pip install XlsxWriter
You should see the message as successfully installed. Now after the installation let’s dive deep into the module.
After the installation let’s start by writing a simple code and then we will understand the code.
Example:
Python3
# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook('sample.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Use the worksheet object to write # data via the write() method. worksheet.write('A1', 'Hello..') worksheet.write('B1', 'Geeks') worksheet.write('C1', 'For') worksheet.write('D1', 'Geeks') # Finally, close the Excel file # via the close() method. workbook.close()
Output:
In the above example, we have called the function Workbook() which is used for creating an empty workbook. The Excel file will be created with the name of sample.xlsx. Then the add_worksheet() method is used to add a spreadsheet to the workbook and this spreadsheet is saved under the object name worksheet. Then the write() method is used to write the data to the spreadsheet. The first parameter is used to pass the cell name. The cell name can also be passed by the index name such as A1 is indexed as (0, 0), B1 is (0, 1), A2 is (1, 0), B2 is (1, 1).
Note: Rows and Columns are Zero indexed in XlsxWriter.
Now let’s see how to add data to a particular row or column. See the below example.
Example:
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() # Start from the first cell. # Rows and columns are zero indexed. row = 0column = 0 content = ["Welcome", "to", "Geeks", "for", "Geeks"] # iterating through content list for item in content : # write operation perform worksheet.write(row, column, item) # incrementing the value of row by one # with each iterations. row += 1 workbook.close()
Output:
You might have seen that we are playing with the index number to write in a particular row. Similarly, we can use a similar way to write to a particular column.
The XlsxWriter module also provides the write_row() and write_column() methods to write in a particular row or column.
Example:
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = ["Welcome", "to", "Geeks", "for", "Geeks"] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) workbook.close()
Output:
Refer to the below article to get detailed information about writing to Excel using the XlsxWriter module.
Create and write on excel file using xlsxwriter module
XlsxWriter module provides the write_formula() and write_array_formula() methods to directly write the formulas in Excel.
write_formula() method is used to directly write the formula to a worksheet cell
write_array_formula() method is used to write an array formula to a worksheet cell. Array formula in Excel is that formula that performs on a set of values.
Syntax:
write_formula(row, col, formula[, cell_format[, value]])
write_array_formula(first_row, first_col, last_row, last_col, formula[, cell_format[, value]])
Example 1: Using the write_formula() method
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) # Using the array formula to find the# sum and the product of the given cellsworksheet.write_formula('A4', '{=SUM(A2, A3)}')worksheet.write_formula('D1', '{=PRODUCT(B1, C1)}') workbook.close()
Output:
Example 2: Using the write_array_formula() method
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 4, 5] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) # Using the array formula to find the# sum and the product of the given cellsworksheet.write_array_formula('A7', '{=SUM(A1:A6)}')worksheet.write_array_formula('G1', '{=PRODUCT(B1:F1)}') workbook.close()
Output:
XlsxWriter provides a class Chart that acts as a base class for implementing charts. The chart object is created using the add_chart() method. This method also specifies the type of the chart. After creating the chart, the chart is added to the specified cell using the insert_chart() method or it can be set using the set_chart() method.
Syntax:
add_chart(options)
insert_chart(row, col, chart[, options])
set_chart(chart)
Example 1:
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 5, 3, 2, 2] # Writing to row and column respectivelyworksheet.write_column(0, 0, content) # Creating the chart object of type barchart = workbook.add_chart({'type': 'column'}) # Add a series to the chartchart.add_series({'values': '=Sheet1!$A$1:$A$7'}) # Insert the chart into the worksheetworksheet.insert_chart('C1', chart) workbook.close()
Output:
Example 2: Adding the line chart with diamond points
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 5, 3, 2, 2] # Writing to row and column respectivelyworksheet.write_column(0, 0, content) # Creating the chart object of type barchart = workbook.add_chart({'type': 'line'}) # Add a series to the chartchart.add_series({'values': '=Sheet1!$A$1:$A$7', 'marker': {'type': 'diamond'},}) # Insert the chart into the worksheetworksheet.insert_chart('C1', chart) workbook.close()
Output:
Refer to the below articles to get a detailed information about plotting charts using XlsxWriter module.
Plotting charts in excel sheet with Data Tools using XlsxWriter module | Set – 1
Plotting charts in excel sheet with data tools using XlsxWriter module | Set – 2
Plotting Different types of style charts in excel sheet using XlsxWriter module
Plotting Line charts in excel sheet using XlsxWriter module
Plotting column charts in excel sheet using XlsxWriter module
Plotting bar charts in excel sheet using XlsxWriter module
Plotting scatter charts in excel sheet using XlsxWriter module
Plotting Pie charts in excel sheet using XlsxWriter module
Plotting Doughnut charts in excel sheet using XlsxWriter module
Plotting Area charts in excel sheet using XlsxWriter module
Plotting Radar charts in excel sheet using XlsxWriter module
Plotting Stock charts in excel sheet using XlsxWriter module
Plotting an Excel chart with Gradient fills using XlsxWriter module
Plotting Combined charts in excel sheet using XlsxWriter module
Adding a Chartsheet in an excel sheet using XlsxWriter module
Tables can be added using the add_table() method. The data parameter of the table is used to specify the data for the cells of the table.. The header_row parameter is used to turn off or on the header row to the table.
Syntax:
add_table(first_row, first_col, last_row, last_col, options)
Example:
Python3
# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() # Data for the tabledata = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], ] # Creating the Tableworksheet.add_table('B2:D5', {'data': data}) workbook.close()
Output:
Pandas write Excel files using the XlsxWriter ot Openpyxl module. This can be used to read, filter, and re-arrange either small or large datasets and output them in a range of formats including Excel. The ExcelWriter() method of the pandas library creates a Excel writer object using XlsxWriter. Then the to_excel() method is used to write the dataframe to the excel.
Example 1:
Python3
# import pandas as pdimport pandas as pd # Create a Pandas dataframe from some data.df = pd.DataFrame({'Data': ['Geeks', 'For', 'geeks', 'is', 'portal', 'for', 'geeks']}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # Write a dataframe to the worksheet.df.to_excel(writer, sheet_name='Sheet1') # Close the Pandas Excel writer# object and output the Excel file.writer.save()
Output:
Example 2: Writing to multiple dataframes.
Python3
# import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})df4 = pd.DataFrame({'Data': [41, 42, 43, 44]}) # Create a Pandas Excel writer object# using XlsxWriter as the engine.writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # write and Positioning the dataframes in the worksheet.# Default position, cell A1.df1.to_excel(writer, sheet_name='Sheet1')df2.to_excel(writer, sheet_name='Sheet1', startcol=3)df3.to_excel(writer, sheet_name='Sheet1', startrow=6) # It is also possible to write the# dataframe without the header and index.df4.to_excel(writer, sheet_name='Sheet1', startrow=7, startcol=4, header=False, index=False) # Close the Pandas Excel writer object# and output the Excel file.writer.save()
Output:
Example 3: Converting a Pandas dataframe with datetimes to an Excel file with a default datetime and date format using Pandas and XlsxWriter.
Python3
# import pandas library as pdimport pandas as pd # from datetime module import# datetime and date methodfrom datetime import datetime, date # Create a Pandas dataframe from some datetime data.# datetime(year,month,date,hour,minute,second)# date(year,month,date)dataframe = pd.DataFrame({ 'Date and time': [datetime(2018, 1, 11, 11, 30, 55), datetime(2018, 2, 12, 1, 20, 33), datetime(2018, 3, 13, 11, 10), datetime(2018, 4, 14, 16, 45, 35), datetime(2018, 5, 15, 12, 10, 15)], 'Dates only': [date(2018, 6, 21), date(2018, 7, 22), date(2018, 8, 23), date(2018, 9, 24), date(2018, 10, 25)], }) # Create a Pandas Excel writer# object using XlsxWriter as the engine.# Also set the default datetime and date formats. # mmmm dd yyyy => month date year# month - full name, date - 2 digit, year - 4 digit # mmm d yyyy hh:mm:ss => month date year hour: minute: second# month - first 3 letters , date - 1 or 2 digit , year - 4 digit.writer_object = pd.ExcelWriter("sample.xlsx", engine='xlsxwriter', datetime_format='mmm d yyyy hh:mm:ss', date_format='mmmm dd yyyy') # Write a dataframe to the worksheet.dataframe.to_excel(writer_object, sheet_name='Sheet1') # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # set width of the B and C columnworksheet_object.set_column('B:C', 20) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()
Output:
Example 4: Converting a Pandas dataframe to an Excel file with a user defined header format using Pandas and XlsxWriter.
Python3
# import pandas lib as pdimport pandas as pd data1 = ["Math", "Physics", "Computer", "Hindi", "English", "chemistry"] data2 = [95, 78, 80, 80, 60, 95]data3 = [90, 67, 78, 70, 63, 90] # Create a Pandas dataframe from some data.dataframe = pd.DataFrame( {'Subject': data1, 'Mid Term Exam Scores Out of 100': data2, 'End Term Exam Scores Out of 100': data3}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer_object = pd.ExcelWriter("sample.xlsx", engine='xlsxwriter') # Write a dataframe to the worksheet.# we turn off the default header# and skip one row because we want# to insert a user defined header there.dataframe.to_excel(writer_object, sheet_name='Sheet1', startrow=1, header=False) # Create xlsxwriter workbook object .workbook_object = writer_object.book # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create a format object for header.header_format_object = workbook_object.add_format({ 'bold': True, 'italic': True, 'text_wrap': True, 'valign': 'top', 'font_color': 'green', 'border': 2}) # Write the column headers with the defined format.for col_number, value in enumerate(dataframe.columns.values): worksheet_object.write(0, col_number + 1, value, header_format_object) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()
Output:
Till now we have seen different methods for adding the data to the Excel files using the Pandas and the XlsxWriter module. Now after the data is inserted we can simply create the charts using the add_chart() method as we have seen above.
Example:
Python3
# import pandas library as pdimport pandas as pd # Create a Pandas dataframe from some data.dataframe = pd.DataFrame({ 'Subject': ["Math", "Physics", "Computer", "Hindi", "English", "chemistry"], 'Mid Exam Score': [90, 78, 60, 80, 60, 90], 'End Exam Score': [45, 39, 30, 40, 30, 60]}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer_object = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # Write a dataframe to the worksheet.dataframe.to_excel(writer_object, sheet_name='Sheet1') # Create xlsxwriter workbook object .workbook_object = writer_object.book # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # set width of the B and C columnworksheet_object.set_column('B:C', 20) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a column chart object .chart_object = workbook_object.add_chart({'type': 'column'}) # Add a data series to a chart# using add_series method. # Configure the first series.# syntax to define ranges is :# [sheetname, first_row, first_col, last_row, last_col].chart_object.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 3, 6, 3], 'values': ['Sheet1', 1, 2, 6, 2],}) # Configure a second series.chart_object.add_series({ 'name': ['Sheet1', 0, 1], 'categories': ['Sheet1', 1, 3, 6, 3], 'values': ['Sheet1', 1, 1, 6, 1],}) # Add a chart title.chart_object.set_title({'name': 'Exam Score Distribution'}) # Add x-axis labelchart_object.set_x_axis({'name': 'Subjects'}) # Add y-axis labelchart_object.set_y_axis({'name': 'Marks'}) # add chart to the worksheet with given# offset values at the top-left corner of# a chart is anchored to cell E2worksheet_object.insert_chart('B10', chart_object, {'x_offset': 20, 'y_offset': 5}) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()
Output:
Refer to the below articles to get detailed information about working with Xlsxwriter and Pandas.
Working with Pandas and XlsxWriter | Set – 1
Working with Pandas and XlsxWriter | Set – 2
Working with Pandas and XlsxWriter | Set – 3
kalrap615
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 24174,
"s": 23901,
"text": "XlsxWriter is a Python module that provides various methods to work with Excel using Python. It can be used to read, write, applying formulas. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others."
},
{
"code": null,
"e": 24319,
"s": 24174,
"text": "This tutorial aims at providing knowledge about the XlsxWriter module from basics to advance with the help well explained examples and concepts."
},
{
"code": null,
"e": 24438,
"s": 24319,
"text": "Before diving deep into the module let’s start by installing it. To install it type the below command in the terminal."
},
{
"code": null,
"e": 24461,
"s": 24438,
"text": "pip install XlsxWriter"
},
{
"code": null,
"e": 24575,
"s": 24461,
"text": "You should see the message as successfully installed. Now after the installation let’s dive deep into the module."
},
{
"code": null,
"e": 24673,
"s": 24575,
"text": "After the installation let’s start by writing a simple code and then we will understand the code."
},
{
"code": null,
"e": 24682,
"s": 24673,
"text": "Example:"
},
{
"code": null,
"e": 24690,
"s": 24682,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook('sample.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Use the worksheet object to write # data via the write() method. worksheet.write('A1', 'Hello..') worksheet.write('B1', 'Geeks') worksheet.write('C1', 'For') worksheet.write('D1', 'Geeks') # Finally, close the Excel file # via the close() method. workbook.close() ",
"e": 25278,
"s": 24690,
"text": null
},
{
"code": null,
"e": 25286,
"s": 25278,
"text": "Output:"
},
{
"code": null,
"e": 25842,
"s": 25286,
"text": "In the above example, we have called the function Workbook() which is used for creating an empty workbook. The Excel file will be created with the name of sample.xlsx. Then the add_worksheet() method is used to add a spreadsheet to the workbook and this spreadsheet is saved under the object name worksheet. Then the write() method is used to write the data to the spreadsheet. The first parameter is used to pass the cell name. The cell name can also be passed by the index name such as A1 is indexed as (0, 0), B1 is (0, 1), A2 is (1, 0), B2 is (1, 1). "
},
{
"code": null,
"e": 25897,
"s": 25842,
"text": "Note: Rows and Columns are Zero indexed in XlsxWriter."
},
{
"code": null,
"e": 25981,
"s": 25897,
"text": "Now let’s see how to add data to a particular row or column. See the below example."
},
{
"code": null,
"e": 25990,
"s": 25981,
"text": "Example:"
},
{
"code": null,
"e": 25998,
"s": 25990,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() # Start from the first cell. # Rows and columns are zero indexed. row = 0column = 0 content = [\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"] # iterating through content list for item in content : # write operation perform worksheet.write(row, column, item) # incrementing the value of row by one # with each iterations. row += 1 workbook.close()",
"e": 26500,
"s": 25998,
"text": null
},
{
"code": null,
"e": 26508,
"s": 26500,
"text": "Output:"
},
{
"code": null,
"e": 26669,
"s": 26508,
"text": "You might have seen that we are playing with the index number to write in a particular row. Similarly, we can use a similar way to write to a particular column."
},
{
"code": null,
"e": 26788,
"s": 26669,
"text": "The XlsxWriter module also provides the write_row() and write_column() methods to write in a particular row or column."
},
{
"code": null,
"e": 26797,
"s": 26788,
"text": "Example:"
},
{
"code": null,
"e": 26805,
"s": 26797,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) workbook.close()",
"e": 27122,
"s": 26805,
"text": null
},
{
"code": null,
"e": 27130,
"s": 27122,
"text": "Output:"
},
{
"code": null,
"e": 27237,
"s": 27130,
"text": "Refer to the below article to get detailed information about writing to Excel using the XlsxWriter module."
},
{
"code": null,
"e": 27292,
"s": 27237,
"text": "Create and write on excel file using xlsxwriter module"
},
{
"code": null,
"e": 27416,
"s": 27292,
"text": "XlsxWriter module provides the write_formula() and write_array_formula() methods to directly write the formulas in Excel. "
},
{
"code": null,
"e": 27497,
"s": 27416,
"text": "write_formula() method is used to directly write the formula to a worksheet cell"
},
{
"code": null,
"e": 27654,
"s": 27497,
"text": "write_array_formula() method is used to write an array formula to a worksheet cell. Array formula in Excel is that formula that performs on a set of values."
},
{
"code": null,
"e": 27662,
"s": 27654,
"text": "Syntax:"
},
{
"code": null,
"e": 27719,
"s": 27662,
"text": "write_formula(row, col, formula[, cell_format[, value]])"
},
{
"code": null,
"e": 27814,
"s": 27719,
"text": "write_array_formula(first_row, first_col, last_row, last_col, formula[, cell_format[, value]])"
},
{
"code": null,
"e": 27858,
"s": 27814,
"text": "Example 1: Using the write_formula() method"
},
{
"code": null,
"e": 27866,
"s": 27858,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) # Using the array formula to find the# sum and the product of the given cellsworksheet.write_formula('A4', '{=SUM(A2, A3)}')worksheet.write_formula('D1', '{=PRODUCT(B1, C1)}') workbook.close()",
"e": 28324,
"s": 27866,
"text": null
},
{
"code": null,
"e": 28332,
"s": 28324,
"text": "Output:"
},
{
"code": null,
"e": 28382,
"s": 28332,
"text": "Example 2: Using the write_array_formula() method"
},
{
"code": null,
"e": 28390,
"s": 28382,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 4, 5] # Writing to row and column respectivelyworksheet.write_row(0, 1, content)worksheet.write_column(1, 0, content) # Using the array formula to find the# sum and the product of the given cellsworksheet.write_array_formula('A7', '{=SUM(A1:A6)}')worksheet.write_array_formula('G1', '{=PRODUCT(B1:F1)}') workbook.close()",
"e": 28867,
"s": 28390,
"text": null
},
{
"code": null,
"e": 28875,
"s": 28867,
"text": "Output:"
},
{
"code": null,
"e": 29214,
"s": 28875,
"text": "XlsxWriter provides a class Chart that acts as a base class for implementing charts. The chart object is created using the add_chart() method. This method also specifies the type of the chart. After creating the chart, the chart is added to the specified cell using the insert_chart() method or it can be set using the set_chart() method."
},
{
"code": null,
"e": 29222,
"s": 29214,
"text": "Syntax:"
},
{
"code": null,
"e": 29241,
"s": 29222,
"text": "add_chart(options)"
},
{
"code": null,
"e": 29282,
"s": 29241,
"text": "insert_chart(row, col, chart[, options])"
},
{
"code": null,
"e": 29299,
"s": 29282,
"text": "set_chart(chart)"
},
{
"code": null,
"e": 29310,
"s": 29299,
"text": "Example 1:"
},
{
"code": null,
"e": 29318,
"s": 29310,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 5, 3, 2, 2] # Writing to row and column respectivelyworksheet.write_column(0, 0, content) # Creating the chart object of type barchart = workbook.add_chart({'type': 'column'}) # Add a series to the chartchart.add_series({'values': '=Sheet1!$A$1:$A$7'}) # Insert the chart into the worksheetworksheet.insert_chart('C1', chart) workbook.close()",
"e": 29819,
"s": 29318,
"text": null
},
{
"code": null,
"e": 29827,
"s": 29819,
"text": "Output:"
},
{
"code": null,
"e": 29880,
"s": 29827,
"text": "Example 2: Adding the line chart with diamond points"
},
{
"code": null,
"e": 29888,
"s": 29880,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() content = [1, 2, 3, 5, 3, 2, 2] # Writing to row and column respectivelyworksheet.write_column(0, 0, content) # Creating the chart object of type barchart = workbook.add_chart({'type': 'line'}) # Add a series to the chartchart.add_series({'values': '=Sheet1!$A$1:$A$7', 'marker': {'type': 'diamond'},}) # Insert the chart into the worksheetworksheet.insert_chart('C1', chart) workbook.close()",
"e": 30435,
"s": 29888,
"text": null
},
{
"code": null,
"e": 30443,
"s": 30435,
"text": "Output:"
},
{
"code": null,
"e": 30548,
"s": 30443,
"text": "Refer to the below articles to get a detailed information about plotting charts using XlsxWriter module."
},
{
"code": null,
"e": 30629,
"s": 30548,
"text": "Plotting charts in excel sheet with Data Tools using XlsxWriter module | Set – 1"
},
{
"code": null,
"e": 30710,
"s": 30629,
"text": "Plotting charts in excel sheet with data tools using XlsxWriter module | Set – 2"
},
{
"code": null,
"e": 30790,
"s": 30710,
"text": "Plotting Different types of style charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 30850,
"s": 30790,
"text": "Plotting Line charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 30912,
"s": 30850,
"text": "Plotting column charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 30971,
"s": 30912,
"text": "Plotting bar charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31034,
"s": 30971,
"text": "Plotting scatter charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31093,
"s": 31034,
"text": "Plotting Pie charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31157,
"s": 31093,
"text": "Plotting Doughnut charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31217,
"s": 31157,
"text": "Plotting Area charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31278,
"s": 31217,
"text": "Plotting Radar charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31339,
"s": 31278,
"text": "Plotting Stock charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31407,
"s": 31339,
"text": "Plotting an Excel chart with Gradient fills using XlsxWriter module"
},
{
"code": null,
"e": 31471,
"s": 31407,
"text": "Plotting Combined charts in excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31533,
"s": 31471,
"text": "Adding a Chartsheet in an excel sheet using XlsxWriter module"
},
{
"code": null,
"e": 31752,
"s": 31533,
"text": "Tables can be added using the add_table() method. The data parameter of the table is used to specify the data for the cells of the table.. The header_row parameter is used to turn off or on the header row to the table."
},
{
"code": null,
"e": 31760,
"s": 31752,
"text": "Syntax:"
},
{
"code": null,
"e": 31821,
"s": 31760,
"text": "add_table(first_row, first_col, last_row, last_col, options)"
},
{
"code": null,
"e": 31830,
"s": 31821,
"text": "Example:"
},
{
"code": null,
"e": 31838,
"s": 31830,
"text": "Python3"
},
{
"code": "# import xlsxwriter module import xlsxwriter workbook = xlsxwriter.Workbook('sample.xlsx') worksheet = workbook.add_worksheet() # Data for the tabledata = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], ] # Creating the Tableworksheet.add_table('B2:D5', {'data': data}) workbook.close()",
"e": 32145,
"s": 31838,
"text": null
},
{
"code": null,
"e": 32153,
"s": 32145,
"text": "Output:"
},
{
"code": null,
"e": 32521,
"s": 32153,
"text": "Pandas write Excel files using the XlsxWriter ot Openpyxl module. This can be used to read, filter, and re-arrange either small or large datasets and output them in a range of formats including Excel. The ExcelWriter() method of the pandas library creates a Excel writer object using XlsxWriter. Then the to_excel() method is used to write the dataframe to the excel."
},
{
"code": null,
"e": 32533,
"s": 32521,
"text": "Example 1: "
},
{
"code": null,
"e": 32541,
"s": 32533,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # Create a Pandas dataframe from some data.df = pd.DataFrame({'Data': ['Geeks', 'For', 'geeks', 'is', 'portal', 'for', 'geeks']}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # Write a dataframe to the worksheet.df.to_excel(writer, sheet_name='Sheet1') # Close the Pandas Excel writer# object and output the Excel file.writer.save()",
"e": 33054,
"s": 32541,
"text": null
},
{
"code": null,
"e": 33062,
"s": 33054,
"text": "Output:"
},
{
"code": null,
"e": 33105,
"s": 33062,
"text": "Example 2: Writing to multiple dataframes."
},
{
"code": null,
"e": 33113,
"s": 33105,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})df4 = pd.DataFrame({'Data': [41, 42, 43, 44]}) # Create a Pandas Excel writer object# using XlsxWriter as the engine.writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # write and Positioning the dataframes in the worksheet.# Default position, cell A1.df1.to_excel(writer, sheet_name='Sheet1')df2.to_excel(writer, sheet_name='Sheet1', startcol=3)df3.to_excel(writer, sheet_name='Sheet1', startrow=6) # It is also possible to write the# dataframe without the header and index.df4.to_excel(writer, sheet_name='Sheet1', startrow=7, startcol=4, header=False, index=False) # Close the Pandas Excel writer object# and output the Excel file.writer.save()",
"e": 34050,
"s": 33113,
"text": null
},
{
"code": null,
"e": 34058,
"s": 34050,
"text": "Output:"
},
{
"code": null,
"e": 34200,
"s": 34058,
"text": "Example 3: Converting a Pandas dataframe with datetimes to an Excel file with a default datetime and date format using Pandas and XlsxWriter."
},
{
"code": null,
"e": 34208,
"s": 34200,
"text": "Python3"
},
{
"code": "# import pandas library as pdimport pandas as pd # from datetime module import# datetime and date methodfrom datetime import datetime, date # Create a Pandas dataframe from some datetime data.# datetime(year,month,date,hour,minute,second)# date(year,month,date)dataframe = pd.DataFrame({ 'Date and time': [datetime(2018, 1, 11, 11, 30, 55), datetime(2018, 2, 12, 1, 20, 33), datetime(2018, 3, 13, 11, 10), datetime(2018, 4, 14, 16, 45, 35), datetime(2018, 5, 15, 12, 10, 15)], 'Dates only': [date(2018, 6, 21), date(2018, 7, 22), date(2018, 8, 23), date(2018, 9, 24), date(2018, 10, 25)], }) # Create a Pandas Excel writer# object using XlsxWriter as the engine.# Also set the default datetime and date formats. # mmmm dd yyyy => month date year# month - full name, date - 2 digit, year - 4 digit # mmm d yyyy hh:mm:ss => month date year hour: minute: second# month - first 3 letters , date - 1 or 2 digit , year - 4 digit.writer_object = pd.ExcelWriter(\"sample.xlsx\", engine='xlsxwriter', datetime_format='mmm d yyyy hh:mm:ss', date_format='mmmm dd yyyy') # Write a dataframe to the worksheet.dataframe.to_excel(writer_object, sheet_name='Sheet1') # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # set width of the B and C columnworksheet_object.set_column('B:C', 20) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()",
"e": 35865,
"s": 34208,
"text": null
},
{
"code": null,
"e": 35873,
"s": 35865,
"text": "Output:"
},
{
"code": null,
"e": 35994,
"s": 35873,
"text": "Example 4: Converting a Pandas dataframe to an Excel file with a user defined header format using Pandas and XlsxWriter."
},
{
"code": null,
"e": 36002,
"s": 35994,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd data1 = [\"Math\", \"Physics\", \"Computer\", \"Hindi\", \"English\", \"chemistry\"] data2 = [95, 78, 80, 80, 60, 95]data3 = [90, 67, 78, 70, 63, 90] # Create a Pandas dataframe from some data.dataframe = pd.DataFrame( {'Subject': data1, 'Mid Term Exam Scores Out of 100': data2, 'End Term Exam Scores Out of 100': data3}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer_object = pd.ExcelWriter(\"sample.xlsx\", engine='xlsxwriter') # Write a dataframe to the worksheet.# we turn off the default header# and skip one row because we want# to insert a user defined header there.dataframe.to_excel(writer_object, sheet_name='Sheet1', startrow=1, header=False) # Create xlsxwriter workbook object .workbook_object = writer_object.book # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create a format object for header.header_format_object = workbook_object.add_format({ 'bold': True, 'italic': True, 'text_wrap': True, 'valign': 'top', 'font_color': 'green', 'border': 2}) # Write the column headers with the defined format.for col_number, value in enumerate(dataframe.columns.values): worksheet_object.write(0, col_number + 1, value, header_format_object) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()",
"e": 37565,
"s": 36002,
"text": null
},
{
"code": null,
"e": 37573,
"s": 37565,
"text": "Output:"
},
{
"code": null,
"e": 37811,
"s": 37573,
"text": "Till now we have seen different methods for adding the data to the Excel files using the Pandas and the XlsxWriter module. Now after the data is inserted we can simply create the charts using the add_chart() method as we have seen above."
},
{
"code": null,
"e": 37820,
"s": 37811,
"text": "Example:"
},
{
"code": null,
"e": 37828,
"s": 37820,
"text": "Python3"
},
{
"code": "# import pandas library as pdimport pandas as pd # Create a Pandas dataframe from some data.dataframe = pd.DataFrame({ 'Subject': [\"Math\", \"Physics\", \"Computer\", \"Hindi\", \"English\", \"chemistry\"], 'Mid Exam Score': [90, 78, 60, 80, 60, 90], 'End Exam Score': [45, 39, 30, 40, 30, 60]}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer_object = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter') # Write a dataframe to the worksheet.dataframe.to_excel(writer_object, sheet_name='Sheet1') # Create xlsxwriter workbook object .workbook_object = writer_object.book # Create xlsxwriter worksheet objectworksheet_object = writer_object.sheets['Sheet1'] # set width of the B and C columnworksheet_object.set_column('B:C', 20) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a column chart object .chart_object = workbook_object.add_chart({'type': 'column'}) # Add a data series to a chart# using add_series method. # Configure the first series.# syntax to define ranges is :# [sheetname, first_row, first_col, last_row, last_col].chart_object.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 3, 6, 3], 'values': ['Sheet1', 1, 2, 6, 2],}) # Configure a second series.chart_object.add_series({ 'name': ['Sheet1', 0, 1], 'categories': ['Sheet1', 1, 3, 6, 3], 'values': ['Sheet1', 1, 1, 6, 1],}) # Add a chart title.chart_object.set_title({'name': 'Exam Score Distribution'}) # Add x-axis labelchart_object.set_x_axis({'name': 'Subjects'}) # Add y-axis labelchart_object.set_y_axis({'name': 'Marks'}) # add chart to the worksheet with given# offset values at the top-left corner of# a chart is anchored to cell E2worksheet_object.insert_chart('B10', chart_object, {'x_offset': 20, 'y_offset': 5}) # Close the Pandas Excel writer# object and output the Excel file.writer_object.save()",
"e": 39832,
"s": 37828,
"text": null
},
{
"code": null,
"e": 39840,
"s": 39832,
"text": "Output:"
},
{
"code": null,
"e": 39938,
"s": 39840,
"text": "Refer to the below articles to get detailed information about working with Xlsxwriter and Pandas."
},
{
"code": null,
"e": 39983,
"s": 39938,
"text": "Working with Pandas and XlsxWriter | Set – 1"
},
{
"code": null,
"e": 40028,
"s": 39983,
"text": "Working with Pandas and XlsxWriter | Set – 2"
},
{
"code": null,
"e": 40073,
"s": 40028,
"text": "Working with Pandas and XlsxWriter | Set – 3"
},
{
"code": null,
"e": 40083,
"s": 40073,
"text": "kalrap615"
},
{
"code": null,
"e": 40090,
"s": 40083,
"text": "Python"
},
{
"code": null,
"e": 40188,
"s": 40090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40197,
"s": 40188,
"text": "Comments"
},
{
"code": null,
"e": 40210,
"s": 40197,
"text": "Old Comments"
},
{
"code": null,
"e": 40242,
"s": 40210,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 40298,
"s": 40242,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 40340,
"s": 40298,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 40382,
"s": 40340,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 40418,
"s": 40382,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 40440,
"s": 40418,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 40479,
"s": 40440,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 40506,
"s": 40479,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 40537,
"s": 40506,
"text": "Python | os.path.join() method"
}
] |
Boolean.CompareTo(Boolean) Method in C# | The Boolean.CompareTo(Boolean) method in C# is used to compare this instance to a specified Boolean object and returns an integer that indicates their relationship to one another.
Following is the syntax −
public int CompareTo (bool val);
Above, Val is a Boolean object to compare to the current instance.
Let us now see an example to implement the Boolean.CompareTo(Boolean) method −
using System;
public class Demo {
public static void Main(){
bool b1, b2;
b1 = false;
b2 = false;
int res = b2.CompareTo(b1);
if (res > 0)
Console.Write("b1 > b2");
else if (res < 0)
Console.Write("b1 < b2");
else
Console.Write("b1 = b2");
}
}
This will produce the following output −
b1 = b2 | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "The Boolean.CompareTo(Boolean) method in C# is used to compare this instance to a specified Boolean object and returns an integer that indicates their relationship to one another."
},
{
"code": null,
"e": 1268,
"s": 1242,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1301,
"s": 1268,
"text": "public int CompareTo (bool val);"
},
{
"code": null,
"e": 1368,
"s": 1301,
"text": "Above, Val is a Boolean object to compare to the current instance."
},
{
"code": null,
"e": 1447,
"s": 1368,
"text": "Let us now see an example to implement the Boolean.CompareTo(Boolean) method −"
},
{
"code": null,
"e": 1766,
"s": 1447,
"text": "using System;\npublic class Demo {\n public static void Main(){\n bool b1, b2;\n b1 = false;\n b2 = false;\n int res = b2.CompareTo(b1);\n if (res > 0)\n Console.Write(\"b1 > b2\");\n else if (res < 0)\n Console.Write(\"b1 < b2\");\n else\n Console.Write(\"b1 = b2\");\n }\n}"
},
{
"code": null,
"e": 1807,
"s": 1766,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1815,
"s": 1807,
"text": "b1 = b2"
}
] |
Add a shadow to an element with Bootstrap 4 | To add a shadow to an element in Bootstrap, use the .shadow class in Bootstrap 4.
You can try to run the following code to add shadow to an element −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h1>Learning</h1>
<div class = "shadow-lg p-4 mb-4 bg-light">Try programming examples</div>
<div class = "shadow-sm p-4 mb-4 bg-light">Try programming examples</div>
<div class =" shadow-none p-4 mb-4 bg-light">Play Quiz and check your knowledge</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To add a shadow to an element in Bootstrap, use the .shadow class in Bootstrap 4."
},
{
"code": null,
"e": 1212,
"s": 1144,
"text": "You can try to run the following code to add shadow to an element −"
},
{
"code": null,
"e": 1222,
"s": 1212,
"text": "Live Demo"
},
{
"code": null,
"e": 1975,
"s": 1222,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h1>Learning</h1>\n <div class = \"shadow-lg p-4 mb-4 bg-light\">Try programming examples</div>\n <div class = \"shadow-sm p-4 mb-4 bg-light\">Try programming examples</div>\n <div class =\" shadow-none p-4 mb-4 bg-light\">Play Quiz and check your knowledge</div>\n </div>\n </body>\n</html>"
}
] |
WPF - RoutedCommands | RoutedCommands enable input handling at a more semantic level. These are actually simple instructions as New, Open, Copy, Cut, and Save. These commands are very useful and they can be accessed from a Menu or from a keyboard shortcut. It disables the controls if the command becomes unavailable. The following example defines the commands for Menu items.
Let’s create a new WPF project with the name WPFCommandsInput.
Let’s create a new WPF project with the name WPFCommandsInput.
Drag a menu control to a stack panel and set the following properties and commands as shown in the following XAML file.
Drag a menu control to a stack panel and set the following properties and commands as shown in the following XAML file.
<Window x:Class = "WPFContextMenu.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFContextMenu"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525">
<Grid>
<StackPanel x:Name = "stack" Background = "Transparent">
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header = "New" Command = "New" />
<MenuItem Header = "Open" Command = "Open" />
<MenuItem Header = "Save" Command = "Save" />
</ContextMenu>
</StackPanel.ContextMenu>
<Menu>
<MenuItem Header = "File" >
<MenuItem Header = "New" Command = "New" />
<MenuItem Header = "Open" Command = "Open" />
<MenuItem Header = "Save" Command = "Save" />
</MenuItem>
</Menu>
</StackPanel>
</Grid>
</Window>
Here is the C# code in which different commands are handled.
using System.Windows;
using System.Windows.Input;
namespace WPFContextMenu {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
CommandBindings.Add(new CommandBinding(ApplicationCommands.New, NewExecuted, CanNew));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, OpenExecuted, CanOpen));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, SaveExecuted, CanSave));
}
private void NewExecuted(object sender, ExecutedRoutedEventArgs e) {
MessageBox.Show("You want to create new file.");
}
private void CanNew(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
private void OpenExecuted(object sender, ExecutedRoutedEventArgs e) {
MessageBox.Show("You want to open existing file.");
}
private void CanOpen(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) {
MessageBox.Show("You want to save a file.");
}
private void CanSave(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
}
}
When the above code is compiled and executed, it will produce the following window −
Now you can access this menu items, either from the menu or from the shortcut keys commands. From either option, it will execute the commands.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2374,
"s": 2020,
"text": "RoutedCommands enable input handling at a more semantic level. These are actually simple instructions as New, Open, Copy, Cut, and Save. These commands are very useful and they can be accessed from a Menu or from a keyboard shortcut. It disables the controls if the command becomes unavailable. The following example defines the commands for Menu items."
},
{
"code": null,
"e": 2437,
"s": 2374,
"text": "Let’s create a new WPF project with the name WPFCommandsInput."
},
{
"code": null,
"e": 2500,
"s": 2437,
"text": "Let’s create a new WPF project with the name WPFCommandsInput."
},
{
"code": null,
"e": 2620,
"s": 2500,
"text": "Drag a menu control to a stack panel and set the following properties and commands as shown in the following XAML file."
},
{
"code": null,
"e": 2740,
"s": 2620,
"text": "Drag a menu control to a stack panel and set the following properties and commands as shown in the following XAML file."
},
{
"code": null,
"e": 3914,
"s": 2740,
"text": "<Window x:Class = \"WPFContextMenu.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFContextMenu\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"525\">\n\t\n <Grid> \n <StackPanel x:Name = \"stack\" Background = \"Transparent\"> \n\t\t\n <StackPanel.ContextMenu> \n <ContextMenu> \n <MenuItem Header = \"New\" Command = \"New\" /> \n <MenuItem Header = \"Open\" Command = \"Open\" /> \n <MenuItem Header = \"Save\" Command = \"Save\" /> \n </ContextMenu> \n </StackPanel.ContextMenu>\n\t\t\t\n <Menu> \n <MenuItem Header = \"File\" > \n <MenuItem Header = \"New\" Command = \"New\" /> \n <MenuItem Header = \"Open\" Command = \"Open\" /> \n <MenuItem Header = \"Save\" Command = \"Save\" /> \n </MenuItem> \n </Menu> \n\t\t\t\n </StackPanel> \n </Grid> \n\t\n</Window> "
},
{
"code": null,
"e": 3975,
"s": 3914,
"text": "Here is the C# code in which different commands are handled."
},
{
"code": null,
"e": 5364,
"s": 3975,
"text": "using System.Windows; \nusing System.Windows.Input; \n \nnamespace WPFContextMenu { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n CommandBindings.Add(new CommandBinding(ApplicationCommands.New, NewExecuted, CanNew)); \n CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, OpenExecuted, CanOpen)); \n CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, SaveExecuted, CanSave)); \n } \n\t\t\n private void NewExecuted(object sender, ExecutedRoutedEventArgs e) { \n MessageBox.Show(\"You want to create new file.\"); \n } \n\t\t\n private void CanNew(object sender, CanExecuteRoutedEventArgs e) { \n e.CanExecute = true; \n } \n\t\t\n private void OpenExecuted(object sender, ExecutedRoutedEventArgs e) { \n MessageBox.Show(\"You want to open existing file.\"); \n } \n\t\t\n private void CanOpen(object sender, CanExecuteRoutedEventArgs e) { \n e.CanExecute = true; \n } \n\t\t\n private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { \n MessageBox.Show(\"You want to save a file.\"); \n } \n private void CanSave(object sender, CanExecuteRoutedEventArgs e) { \n e.CanExecute = true; \n } \n } \n\t\n}\t"
},
{
"code": null,
"e": 5449,
"s": 5364,
"text": "When the above code is compiled and executed, it will produce the following window −"
},
{
"code": null,
"e": 5592,
"s": 5449,
"text": "Now you can access this menu items, either from the menu or from the shortcut keys commands. From either option, it will execute the commands."
},
{
"code": null,
"e": 5627,
"s": 5592,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5641,
"s": 5627,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5676,
"s": 5641,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5699,
"s": 5676,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 5706,
"s": 5699,
"text": " Print"
},
{
"code": null,
"e": 5717,
"s": 5706,
"text": " Add Notes"
}
] |
MongoDB - Delete Document | In this chapter, we will learn how to delete a document using MongoDB.
MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
deletion criteria − (Optional) deletion criteria according to documents will be removed.
deletion criteria − (Optional) deletion criteria according to documents will be removed.
justOne − (Optional) if set to true or 1, then remove only one document.
justOne − (Optional) if set to true or 1, then remove only one document.
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Consider the mycol collection has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }
If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2624,
"s": 2553,
"text": "In this chapter, we will learn how to delete a document using MongoDB."
},
{
"code": null,
"e": 2793,
"s": 2624,
"text": "MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag."
},
{
"code": null,
"e": 2882,
"s": 2793,
"text": "deletion criteria − (Optional) deletion criteria according to documents will be removed."
},
{
"code": null,
"e": 2971,
"s": 2882,
"text": "deletion criteria − (Optional) deletion criteria according to documents will be removed."
},
{
"code": null,
"e": 3044,
"s": 2971,
"text": "justOne − (Optional) if set to true or 1, then remove only one document."
},
{
"code": null,
"e": 3117,
"s": 3044,
"text": "justOne − (Optional) if set to true or 1, then remove only one document."
},
{
"code": null,
"e": 3165,
"s": 3117,
"text": "Basic syntax of remove() method is as follows −"
},
{
"code": null,
"e": 3214,
"s": 3165,
"text": ">db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)\n"
},
{
"code": null,
"e": 3268,
"s": 3214,
"text": "Consider the mycol collection has the following data."
},
{
"code": null,
"e": 3492,
"s": 3268,
"text": "{_id : ObjectId(\"507f191e810c19729de860e1\"), title: \"MongoDB Overview\"},\n{_id : ObjectId(\"507f191e810c19729de860e2\"), title: \"NoSQL Overview\"},\n{_id : ObjectId(\"507f191e810c19729de860e3\"), title: \"Tutorials Point Overview\"}"
},
{
"code": null,
"e": 3575,
"s": 3492,
"text": "Following example will remove all the documents whose title is 'MongoDB Overview'."
},
{
"code": null,
"e": 3832,
"s": 3575,
"text": ">db.mycol.remove({'title':'MongoDB Overview'})\nWriteResult({\"nRemoved\" : 1})\n> db.mycol.find()\n{\"_id\" : ObjectId(\"507f191e810c19729de860e2\"), \"title\" : \"NoSQL Overview\" }\n{\"_id\" : ObjectId(\"507f191e810c19729de860e3\"), \"title\" : \"Tutorials Point Overview\" }"
},
{
"code": null,
"e": 3955,
"s": 3832,
"text": "If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method."
},
{
"code": null,
"e": 4003,
"s": 3955,
"text": ">db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)"
},
{
"code": null,
"e": 4151,
"s": 4003,
"text": "If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command."
},
{
"code": null,
"e": 4225,
"s": 4151,
"text": "> db.mycol.remove({})\nWriteResult({ \"nRemoved\" : 2 })\n> db.mycol.find()\n>"
},
{
"code": null,
"e": 4258,
"s": 4225,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4277,
"s": 4258,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4312,
"s": 4277,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4340,
"s": 4312,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4375,
"s": 4340,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4398,
"s": 4375,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4433,
"s": 4398,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4450,
"s": 4433,
"text": " University Code"
},
{
"code": null,
"e": 4483,
"s": 4450,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4502,
"s": 4483,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 4537,
"s": 4502,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4557,
"s": 4537,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4564,
"s": 4557,
"text": " Print"
},
{
"code": null,
"e": 4575,
"s": 4564,
"text": " Add Notes"
}
] |
What is the difference between a++ and ++a in JavaScript? | ++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand.
a++ returns the value of a before incrementing. It is a post-increment operator since ++ comes after the operand.
You can try to run the following code to learn the difference between i++ and ++i −
<html>
<body>
<script>
var a =10;
var b =20;
//pre-increment operator
a = ++a;
document.write("++a = "+a);
//post-increment operator
b = b++;
document.write("<br> b++ = "+b);
</script>
</body>
</html> | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand."
},
{
"code": null,
"e": 1301,
"s": 1187,
"text": "a++ returns the value of a before incrementing. It is a post-increment operator since ++ comes after the operand."
},
{
"code": null,
"e": 1385,
"s": 1301,
"text": "You can try to run the following code to learn the difference between i++ and ++i −"
},
{
"code": null,
"e": 1698,
"s": 1385,
"text": "<html>\n <body> \n <script>\n var a =10;\n var b =20;\n //pre-increment operator\n a = ++a;\n document.write(\"++a = \"+a); \n //post-increment operator\n b = b++;\n document.write(\"<br> b++ = \"+b);\n </script>\n </body>\n</html>"
}
] |
Difference between Stop and Wait protocol and Sliding Window protocol - GeeksforGeeks | 22 Apr, 2020
Both Stop and Wait protocol and Sliding Window protocol are the techniques to the solution of flow control handling. The main difference between Stop-and-wait protocol and Sliding window protocol is that in Stop-and-Wait Protocol, the sender sends one frame and wait for acknowledgment from the receiver whereas in sliding window protocol, the sender sends more than one frame to the receiver and re-transmits the frame(s) which is/are damaged or suspected.
Difference between Stop and Wait protocol and Sliding Window protocol:
1/(1+2*a)
N/(1+2*a)
ethansifferman
Computer Networks
Difference Between
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread | [
{
"code": null,
"e": 24249,
"s": 24221,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24707,
"s": 24249,
"text": "Both Stop and Wait protocol and Sliding Window protocol are the techniques to the solution of flow control handling. The main difference between Stop-and-wait protocol and Sliding window protocol is that in Stop-and-Wait Protocol, the sender sends one frame and wait for acknowledgment from the receiver whereas in sliding window protocol, the sender sends more than one frame to the receiver and re-transmits the frame(s) which is/are damaged or suspected."
},
{
"code": null,
"e": 24778,
"s": 24707,
"text": "Difference between Stop and Wait protocol and Sliding Window protocol:"
},
{
"code": null,
"e": 24788,
"s": 24778,
"text": "1/(1+2*a)"
},
{
"code": null,
"e": 24798,
"s": 24788,
"text": "N/(1+2*a)"
},
{
"code": null,
"e": 24813,
"s": 24798,
"text": "ethansifferman"
},
{
"code": null,
"e": 24831,
"s": 24813,
"text": "Computer Networks"
},
{
"code": null,
"e": 24850,
"s": 24831,
"text": "Difference Between"
},
{
"code": null,
"e": 24858,
"s": 24850,
"text": "GATE CS"
},
{
"code": null,
"e": 24876,
"s": 24858,
"text": "Computer Networks"
},
{
"code": null,
"e": 24974,
"s": 24876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24983,
"s": 24974,
"text": "Comments"
},
{
"code": null,
"e": 24996,
"s": 24983,
"text": "Old Comments"
},
{
"code": null,
"e": 25034,
"s": 24996,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25064,
"s": 25034,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 25096,
"s": 25064,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25135,
"s": 25096,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 25161,
"s": 25135,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 25192,
"s": 25161,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 25232,
"s": 25192,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 25264,
"s": 25232,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25325,
"s": 25264,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
SAP Scripts - Standard Text | You can use standard texts in SAP to display the database stored value on the output document and this can be done using Transaction Code: SO10
Let us say you want to print terms and conditions on every invoice and you want each invoice to contain these legal terms and conditions directly. You can create a Standard text and use that in the Invoice.
Step 1 − Run Transaction SO10
You have different text options. This can be checked using the find option.
Step 2 − Select Standard text and click Enter by clicking the green tick mark.
Step 3 − To select any Text, click on Execute. You will see a list of all standard texts.
Step 4 − Select any of the following from the list. Here we have selected FI_CASH_SI and click the Display option.
You can see the following text appear by default.
Step 5 − You have to add this to your script.
Signed
Enclosures
Prepared Approved Confirmed
Receipts Expenditures
&uline(130)&
&rfcash-anzsb(Z)& &Rfcash-anzhb(Z)&
Step 6 − Select the form that you want to change. Select and click the change option at the bottom. Then click on Go to → Change Editor.
Step 7 − Enter the text name, object Id, language, etc.
In a similar way, you can insert text symbols, system symbols, documentation, hypertext using the insert option at the top of the screen.
Using SO10 Transaction, you can also create your own standard text and give it a name and later can use it in a script.
You can write something and save it as standard text.
You can directly include this in your form. Open the form and click the Change button. Click Go to → Change Editor.
Using control commands, you can insert standard text created previously in your script.
System symbols are system maintained and their value is provided by the system. Some examples of system symbols are time, date, hours, minutes, seconds, page, etc.
You can maintain standard symbols using Transaction SM30. Examples of standard symbols are thank you, sincerely, etc. They are stored in table TTDG.
They are placeholders for database fields and also act as global program symbols in your Print program.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2667,
"s": 2523,
"text": "You can use standard texts in SAP to display the database stored value on the output document and this can be done using Transaction Code: SO10"
},
{
"code": null,
"e": 2874,
"s": 2667,
"text": "Let us say you want to print terms and conditions on every invoice and you want each invoice to contain these legal terms and conditions directly. You can create a Standard text and use that in the Invoice."
},
{
"code": null,
"e": 2904,
"s": 2874,
"text": "Step 1 − Run Transaction SO10"
},
{
"code": null,
"e": 2980,
"s": 2904,
"text": "You have different text options. This can be checked using the find option."
},
{
"code": null,
"e": 3059,
"s": 2980,
"text": "Step 2 − Select Standard text and click Enter by clicking the green tick mark."
},
{
"code": null,
"e": 3149,
"s": 3059,
"text": "Step 3 − To select any Text, click on Execute. You will see a list of all standard texts."
},
{
"code": null,
"e": 3264,
"s": 3149,
"text": "Step 4 − Select any of the following from the list. Here we have selected FI_CASH_SI and click the Display option."
},
{
"code": null,
"e": 3314,
"s": 3264,
"text": "You can see the following text appear by default."
},
{
"code": null,
"e": 3360,
"s": 3314,
"text": "Step 5 − You have to add this to your script."
},
{
"code": null,
"e": 3564,
"s": 3360,
"text": " Signed \nEnclosures\nPrepared Approved Confirmed\nReceipts Expenditures \n&uline(130)& \n\n&rfcash-anzsb(Z)& &Rfcash-anzhb(Z)& \n"
},
{
"code": null,
"e": 3701,
"s": 3564,
"text": "Step 6 − Select the form that you want to change. Select and click the change option at the bottom. Then click on Go to → Change Editor."
},
{
"code": null,
"e": 3757,
"s": 3701,
"text": "Step 7 − Enter the text name, object Id, language, etc."
},
{
"code": null,
"e": 3895,
"s": 3757,
"text": "In a similar way, you can insert text symbols, system symbols, documentation, hypertext using the insert option at the top of the screen."
},
{
"code": null,
"e": 4015,
"s": 3895,
"text": "Using SO10 Transaction, you can also create your own standard text and give it a name and later can use it in a script."
},
{
"code": null,
"e": 4069,
"s": 4015,
"text": "You can write something and save it as standard text."
},
{
"code": null,
"e": 4185,
"s": 4069,
"text": "You can directly include this in your form. Open the form and click the Change button. Click Go to → Change Editor."
},
{
"code": null,
"e": 4273,
"s": 4185,
"text": "Using control commands, you can insert standard text created previously in your script."
},
{
"code": null,
"e": 4437,
"s": 4273,
"text": "System symbols are system maintained and their value is provided by the system. Some examples of system symbols are time, date, hours, minutes, seconds, page, etc."
},
{
"code": null,
"e": 4586,
"s": 4437,
"text": "You can maintain standard symbols using Transaction SM30. Examples of standard symbols are thank you, sincerely, etc. They are stored in table TTDG."
},
{
"code": null,
"e": 4690,
"s": 4586,
"text": "They are placeholders for database fields and also act as global program symbols in your Print program."
},
{
"code": null,
"e": 4723,
"s": 4690,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4737,
"s": 4723,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 4770,
"s": 4737,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4782,
"s": 4770,
"text": " Neha Gupta"
},
{
"code": null,
"e": 4817,
"s": 4782,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4832,
"s": 4817,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4865,
"s": 4832,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4880,
"s": 4865,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4915,
"s": 4880,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4927,
"s": 4915,
"text": " Neha Malik"
},
{
"code": null,
"e": 4962,
"s": 4927,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4974,
"s": 4962,
"text": " Neha Malik"
},
{
"code": null,
"e": 4981,
"s": 4974,
"text": " Print"
},
{
"code": null,
"e": 4992,
"s": 4981,
"text": " Add Notes"
}
] |
JavaScript - How to create nested unordered list based on nesting of array? | Suppose, we have a nested array of arrays like this −
const arr = [
'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6' ];
We are required to write a JavaScript program that should map any such nested array of arrays of literals to nested unordered lists of HTML.
The only thing to take care of here is that the nesting of the ul has to be just identical to the nesting of the array.
The code for this will be −
JavaScript Code −
const arr = [
'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'],
'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'
];
const prepareUL = (root, arr) => {
let ul = document.createElement('ul');
let li;
root.appendChild(ul);
arr.forEach(function(item) {
if (Array.isArray(item)) {
prepareUL(li, item);
return;
};
li = document.createElement('li');
li.appendChild(document.createTextNode(item));
ul.appendChild(li);
});
}
const div = document.getElementById('myList');
prepareUL(div, arr);
HTML Code −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="myList"></div>
</body>
</html>
And the output will be − | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "Suppose, we have a nested array of arrays like this −"
},
{
"code": null,
"e": 1271,
"s": 1116,
"text": "const arr = [\n 'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6' ];"
},
{
"code": null,
"e": 1412,
"s": 1271,
"text": "We are required to write a JavaScript program that should map any such nested array of arrays of literals to nested unordered lists of HTML."
},
{
"code": null,
"e": 1532,
"s": 1412,
"text": "The only thing to take care of here is that the nesting of the ul has to be just identical to the nesting of the array."
},
{
"code": null,
"e": 1560,
"s": 1532,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1578,
"s": 1560,
"text": "JavaScript Code −"
},
{
"code": null,
"e": 2167,
"s": 1578,
"text": "const arr = [\n 'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'],\n 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'\n];\nconst prepareUL = (root, arr) => {\n let ul = document.createElement('ul');\n let li;\n root.appendChild(ul);\n arr.forEach(function(item) {\n if (Array.isArray(item)) {\n prepareUL(li, item);\n return;\n };\n li = document.createElement('li');\n li.appendChild(document.createTextNode(item));\n ul.appendChild(li);\n });\n}\nconst div = document.getElementById('myList');\nprepareUL(div, arr);"
},
{
"code": null,
"e": 2179,
"s": 2167,
"text": "HTML Code −"
},
{
"code": null,
"e": 2361,
"s": 2179,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width\">\n<title>JS Bin</title>\n</head>\n<body>\n<div id=\"myList\"></div>\n</body>\n</html>"
},
{
"code": null,
"e": 2386,
"s": 2361,
"text": "And the output will be −"
}
] |
Difference Between Keyword and Identifier | In this post, we will understand the difference between a keyword and an identifier.
They define a specific kind of entity.
They define a specific kind of entity.
It always starts with a lower case letter.
It always starts with a lower case letter.
They are pre-defined words that are reserved to work with programs.
They are pre-defined words that are reserved to work with programs.
They can’t be used anywhere else.
They can’t be used anywhere else.
It can only contain alphabetical characters.
It can only contain alphabetical characters.
It helps identify specific property which exists within a language.
It helps identify specific property which exists within a language.
There are special symbols or punctuations used.
There are special symbols or punctuations used.
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
All of them are not variables.
All of them are not variables.
They are used to name a variable, a function, a class, a structure, a union.
They are used to name a variable, a function, a class, a structure, a union.
It is created to give a unique name to an entity.
It is created to give a unique name to an entity.
They can consist of alphabets, digits, and underscores.
They can consist of alphabets, digits, and underscores.
There is no punctuation or special symbol, except the underscore.
There is no punctuation or special symbol, except the underscore.
It can be upper case or lower case.
It can be upper case or lower case.
It helps locate the name of the entity which is defined along with a keyword.
It helps locate the name of the entity which is defined along with a keyword.
enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July} | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "In this post, we will understand the difference between a keyword and an identifier."
},
{
"code": null,
"e": 1186,
"s": 1147,
"text": "They define a specific kind of entity."
},
{
"code": null,
"e": 1225,
"s": 1186,
"text": "They define a specific kind of entity."
},
{
"code": null,
"e": 1268,
"s": 1225,
"text": "It always starts with a lower case letter."
},
{
"code": null,
"e": 1311,
"s": 1268,
"text": "It always starts with a lower case letter."
},
{
"code": null,
"e": 1379,
"s": 1311,
"text": "They are pre-defined words that are reserved to work with programs."
},
{
"code": null,
"e": 1447,
"s": 1379,
"text": "They are pre-defined words that are reserved to work with programs."
},
{
"code": null,
"e": 1481,
"s": 1447,
"text": "They can’t be used anywhere else."
},
{
"code": null,
"e": 1515,
"s": 1481,
"text": "They can’t be used anywhere else."
},
{
"code": null,
"e": 1560,
"s": 1515,
"text": "It can only contain alphabetical characters."
},
{
"code": null,
"e": 1605,
"s": 1560,
"text": "It can only contain alphabetical characters."
},
{
"code": null,
"e": 1673,
"s": 1605,
"text": "It helps identify specific property which exists within a language."
},
{
"code": null,
"e": 1741,
"s": 1673,
"text": "It helps identify specific property which exists within a language."
},
{
"code": null,
"e": 1789,
"s": 1741,
"text": "There are special symbols or punctuations used."
},
{
"code": null,
"e": 1837,
"s": 1789,
"text": "There are special symbols or punctuations used."
},
{
"code": null,
"e": 2035,
"s": 1837,
"text": "auto break case char const continue\ndefault do double else enum extern\nfloat for goto if int long\nregister return short signed sizeof static\nstruct switch typedef union unsigned void\nvolatile while"
},
{
"code": null,
"e": 2066,
"s": 2035,
"text": "All of them are not variables."
},
{
"code": null,
"e": 2097,
"s": 2066,
"text": "All of them are not variables."
},
{
"code": null,
"e": 2174,
"s": 2097,
"text": "They are used to name a variable, a function, a class, a structure, a union."
},
{
"code": null,
"e": 2251,
"s": 2174,
"text": "They are used to name a variable, a function, a class, a structure, a union."
},
{
"code": null,
"e": 2301,
"s": 2251,
"text": "It is created to give a unique name to an entity."
},
{
"code": null,
"e": 2351,
"s": 2301,
"text": "It is created to give a unique name to an entity."
},
{
"code": null,
"e": 2407,
"s": 2351,
"text": "They can consist of alphabets, digits, and underscores."
},
{
"code": null,
"e": 2463,
"s": 2407,
"text": "They can consist of alphabets, digits, and underscores."
},
{
"code": null,
"e": 2529,
"s": 2463,
"text": "There is no punctuation or special symbol, except the underscore."
},
{
"code": null,
"e": 2595,
"s": 2529,
"text": "There is no punctuation or special symbol, except the underscore."
},
{
"code": null,
"e": 2631,
"s": 2595,
"text": "It can be upper case or lower case."
},
{
"code": null,
"e": 2667,
"s": 2631,
"text": "It can be upper case or lower case."
},
{
"code": null,
"e": 2745,
"s": 2667,
"text": "It helps locate the name of the entity which is defined along with a keyword."
},
{
"code": null,
"e": 2823,
"s": 2745,
"text": "It helps locate the name of the entity which is defined along with a keyword."
},
{
"code": null,
"e": 2885,
"s": 2823,
"text": "enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July}"
}
] |
java.time.YearMonth.format() Method Example | The java.time.YearMonth.format(DateTimeFormatter formatter) method formats this year using the specified formatter.
Following is the declaration for java.time.YearMonth.format(DateTimeFormatter formatter) method.
public String format(DateTimeFormatter formatter)
formatter − the formatter to use, not null.
the formatted date string, not null.
DateTimeException − if an error occurs during printing.
The following example shows the usage of java.time.YearMonth.format(DateTimeFormatter formatter) method.
package com.tutorialspoint;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class YearMonthDemo {
public static void main(String[] args) {
YearMonth date = YearMonth.of(2017,12);
System.out.println(date);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy");
System.out.println(formatter.format(date));
}
}
Let us compile and run the above program, this will produce the following result −
2017-12
12/17
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2031,
"s": 1915,
"text": "The java.time.YearMonth.format(DateTimeFormatter formatter) method formats this year using the specified formatter."
},
{
"code": null,
"e": 2128,
"s": 2031,
"text": "Following is the declaration for java.time.YearMonth.format(DateTimeFormatter formatter) method."
},
{
"code": null,
"e": 2179,
"s": 2128,
"text": "public String format(DateTimeFormatter formatter)\n"
},
{
"code": null,
"e": 2223,
"s": 2179,
"text": "formatter − the formatter to use, not null."
},
{
"code": null,
"e": 2260,
"s": 2223,
"text": "the formatted date string, not null."
},
{
"code": null,
"e": 2316,
"s": 2260,
"text": "DateTimeException − if an error occurs during printing."
},
{
"code": null,
"e": 2421,
"s": 2316,
"text": "The following example shows the usage of java.time.YearMonth.format(DateTimeFormatter formatter) method."
},
{
"code": null,
"e": 2809,
"s": 2421,
"text": "package com.tutorialspoint;\n\nimport java.time.YearMonth;\nimport java.time.format.DateTimeFormatter;\n\npublic class YearMonthDemo {\n public static void main(String[] args) {\n\n YearMonth date = YearMonth.of(2017,12);\n System.out.println(date); \n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"MM/yy\");\n System.out.println(formatter.format(date)); \n }\n}"
},
{
"code": null,
"e": 2892,
"s": 2809,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2907,
"s": 2892,
"text": "2017-12\n12/17\n"
},
{
"code": null,
"e": 2914,
"s": 2907,
"text": " Print"
},
{
"code": null,
"e": 2925,
"s": 2914,
"text": " Add Notes"
}
] |
Striped Table with Bootstrap | To add a striped table in Bootstrap, use the .table-striped class. You can try to run the following code to implement the .table-striped class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Table</title>
<meta name = "viewport" content = "width=device-width, initial-scale = 1">
<link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class = "table table-striped">
<caption>Footballer Rank</caption>
<thead>
<tr>
<th>Footballer</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amit</td>
<td>3</td>
</tr>
<tr>
<td>Kevin</td>
<td>2</td>
</tr>
</tbody>
</table>
</body>
</html> | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "To add a striped table in Bootstrap, use the .table-striped class. You can try to run the following code to implement the .table-striped class −"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Live Demo"
},
{
"code": null,
"e": 2173,
"s": 1217,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <table class = \"table table-striped\">\n <caption>Footballer Rank</caption>\n <thead>\n <tr>\n <th>Footballer</th>\n <th>Rank</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Amit</td>\n <td>3</td>\n </tr>\n <tr>\n <td>Kevin</td>\n <td>2</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>"
}
] |
Java.io.PrintWriter class in Java | Set 1 - GeeksforGeeks | 24 Jan, 2017
This class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform’s own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().Constructor and Description
PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with the specified file.
PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
PrintWriter(OutputStream out) : Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
PrintWriter(OutputStream out, boolean autoFlush) : Creates a new PrintWriter from an existing OutputStream.
PrintWriter(String fileName) : Creates a new PrintWriter, without automatic line flushing, with the specified file name.
PrintWriter(String fileName, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing.
PrintWriter(Writer out, boolean autoFlush) : Creates a new PrintWriter.
Methods:
PrintWriter append(char c) : Appends the specified character to this writerSyntax :public PrintWriter append(char c)
Parameters:
c - The 16-bit character to append
Returns:
This writer
Syntax :public PrintWriter append(char c)
Parameters:
c - The 16-bit character to append
Returns:
This writer
PrintWriter append(CharSequence csq, int start, int end): Appends the specified character sequence to this writer.Syntax :public PrintWriter append(CharSequence csq,
int start,
int end)
Parameters:
csq - The character sequence from which a subsequence will be appended.
start - The index of the first character in the subsequence
end - The index of the character following the last character in the subsequence
Returns:This writer
Throws:
IndexOutOfBoundsException
Syntax :public PrintWriter append(CharSequence csq,
int start,
int end)
Parameters:
csq - The character sequence from which a subsequence will be appended.
start - The index of the first character in the subsequence
end - The index of the character following the last character in the subsequence
Returns:This writer
Throws:
IndexOutOfBoundsException
PrintWriter append(CharSequence csq) : Appends a subsequence of the specified character sequence to this writer.Syntax :public PrintWriter append(CharSequence csq)
Parameters:
csq - The character sequence to append.
Returns: This writer
Syntax :public PrintWriter append(CharSequence csq)
Parameters:
csq - The character sequence to append.
Returns: This writer
boolean checkError(): Flushes the stream and checks its error state.Syntax :public boolean checkError()
Returns: true if and only if this stream
has encountered an IOException other than InterruptedIOException,
or the setError method has been invoked
Syntax :public boolean checkError()
Returns: true if and only if this stream
has encountered an IOException other than InterruptedIOException,
or the setError method has been invoked
protected void clearError() : Clears the internal error state of this stream.Syntax :protected void clearError()
Syntax :protected void clearError()
void close() : Closes the stream and releases any system resources associated with it.Syntax :public void close()
Specified by:close in class Writer
Syntax :public void close()
Specified by:close in class Writer
void flush(): Flushes the stream.Syntax :public void flush()
Specified by:flush in interface Flushable
Specified by:flush in class Writer
Syntax :public void flush()
Specified by:flush in interface Flushable
Specified by:flush in class Writer
PrintWriter format(Locale l, String format, Object... args): Writes a formatted string to this writer using the specified format string and arguments.Syntax :public PrintWriter format(Locale l,
String format,
Object... args)
Parameters:
l - The locale to apply during formatting. If l is null,
then no localization is applied.
format - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
The number of arguments is variable and may be zero.
Returns: This writer
Throws:
IllegalFormatException
NullPointerException
Syntax :public PrintWriter format(Locale l,
String format,
Object... args)
Parameters:
l - The locale to apply during formatting. If l is null,
then no localization is applied.
format - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
The number of arguments is variable and may be zero.
Returns: This writer
Throws:
IllegalFormatException
NullPointerException
PrintWriter format(String format, Object... args): Writes a formatted string to this writer using the specified format string and arguments.Syntax :public PrintWriter format(String format,
Object... args)
Parameters:
format - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
The number of arguments is variable and may be zero.
Returns: This writer
Throws:
IllegalFormatException
NullPointerException
Syntax :public PrintWriter format(String format,
Object... args)
Parameters:
format - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
The number of arguments is variable and may be zero.
Returns: This writer
Throws:
IllegalFormatException
NullPointerException
void print(boolean b): Prints a boolean value.Syntax :public void print(boolean b)
Syntax :public void print(boolean b)
void print(char c): Prints a character.Syntax :public void print(char c)
Syntax :public void print(char c)
void print(char[] s): Prints an array of characters.Syntax :public void print(char[] s)
Syntax :public void print(char[] s)
void print(double d) :Prints a double-precision floating-point number.Syntax :public void print(double b)
Syntax :public void print(double b)
void print(float f): Prints a floating-point number.Syntax :public void print(float f)
Syntax :public void print(float f)
void print(int i): Prints an integer.Syntax :public void print(int i)
Syntax :public void print(int i)
void print(long l): Prints a long integer.Syntax :public void print(long l)
Syntax :public void print(long l)
void print(Object obj) :Prints an object.Syntax :public void print(Object obj)
Syntax :public void print(Object obj)
void print(String s): Prints a string.Syntax :public void print(String s)
Syntax :public void print(String s)
Program:
import java.io.*;import java.util.Locale;//Java program to demonstrate PrintWriterclass PrintWriterDemo { public static void main(String[] args) { String s="GeeksforGeeks"; // create a new writer PrintWriter out = new PrintWriter(System.out); char c[]={'G','E','E','K'}; //illustrating print(boolean b) method out.print(true); //illustrating print(int i) method out.print(1); //illustrating print(float f) method out.print(4.533f); //illustrating print(String s) method out.print("GeeksforGeeks"); out.println(); //illustrating print(Object Obj) method out.print(out); out.println(); //illustrating append(CharSequence csq) method out.append("Geek"); out.println(); //illustrating checkError() method out.println(out.checkError()); //illustrating format() method out.format(Locale.UK, "This is my %s program", s); //illustrating flush method out.flush(); //illustrating close method out.close(); }}
Output:
true14.533GeeksforGeeks
java.io.PrintWriter@1540e19d
Geek
false
This is my GeeksforGeeks program
Next Article: Java.io.PrintWriter class in Java | Set 2
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-I/O
Java
Java
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
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 23953,
"s": 23925,
"text": "\n24 Jan, 2017"
},
{
"code": null,
"e": 24512,
"s": 23953,
"text": "This class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform’s own notion of line separator rather than the newline character."
},
{
"code": null,
"e": 24716,
"s": 24512,
"text": "Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().Constructor and Description"
},
{
"code": null,
"e": 24826,
"s": 24716,
"text": "PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with the specified file."
},
{
"code": null,
"e": 24960,
"s": 24826,
"text": "PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file and charset."
},
{
"code": null,
"e": 25083,
"s": 24960,
"text": "PrintWriter(OutputStream out) : Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream."
},
{
"code": null,
"e": 25191,
"s": 25083,
"text": "PrintWriter(OutputStream out, boolean autoFlush) : Creates a new PrintWriter from an existing OutputStream."
},
{
"code": null,
"e": 25312,
"s": 25191,
"text": "PrintWriter(String fileName) : Creates a new PrintWriter, without automatic line flushing, with the specified file name."
},
{
"code": null,
"e": 25457,
"s": 25312,
"text": "PrintWriter(String fileName, String csn) : Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset."
},
{
"code": null,
"e": 25542,
"s": 25457,
"text": "PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing."
},
{
"code": null,
"e": 25614,
"s": 25542,
"text": "PrintWriter(Writer out, boolean autoFlush) : Creates a new PrintWriter."
},
{
"code": null,
"e": 25623,
"s": 25614,
"text": "Methods:"
},
{
"code": null,
"e": 25808,
"s": 25623,
"text": "PrintWriter append(char c) : Appends the specified character to this writerSyntax :public PrintWriter append(char c)\nParameters:\nc - The 16-bit character to append\nReturns:\nThis writer"
},
{
"code": null,
"e": 25918,
"s": 25808,
"text": "Syntax :public PrintWriter append(char c)\nParameters:\nc - The 16-bit character to append\nReturns:\nThis writer"
},
{
"code": null,
"e": 26431,
"s": 25918,
"text": "PrintWriter append(CharSequence csq, int start, int end): Appends the specified character sequence to this writer.Syntax :public PrintWriter append(CharSequence csq,\n int start,\n int end)\nParameters:\n csq - The character sequence from which a subsequence will be appended.\n start - The index of the first character in the subsequence\n end - The index of the character following the last character in the subsequence\nReturns:This writer\nThrows:\n IndexOutOfBoundsException"
},
{
"code": null,
"e": 26830,
"s": 26431,
"text": "Syntax :public PrintWriter append(CharSequence csq,\n int start,\n int end)\nParameters:\n csq - The character sequence from which a subsequence will be appended.\n start - The index of the first character in the subsequence\n end - The index of the character following the last character in the subsequence\nReturns:This writer\nThrows:\n IndexOutOfBoundsException"
},
{
"code": null,
"e": 27076,
"s": 26830,
"text": "PrintWriter append(CharSequence csq) : Appends a subsequence of the specified character sequence to this writer.Syntax :public PrintWriter append(CharSequence csq)\nParameters:\n csq - The character sequence to append.\nReturns: This writer\n"
},
{
"code": null,
"e": 27210,
"s": 27076,
"text": "Syntax :public PrintWriter append(CharSequence csq)\nParameters:\n csq - The character sequence to append.\nReturns: This writer\n"
},
{
"code": null,
"e": 27463,
"s": 27210,
"text": "boolean checkError(): Flushes the stream and checks its error state.Syntax :public boolean checkError()\nReturns: true if and only if this stream \nhas encountered an IOException other than InterruptedIOException, \nor the setError method has been invoked"
},
{
"code": null,
"e": 27648,
"s": 27463,
"text": "Syntax :public boolean checkError()\nReturns: true if and only if this stream \nhas encountered an IOException other than InterruptedIOException, \nor the setError method has been invoked"
},
{
"code": null,
"e": 27762,
"s": 27648,
"text": "protected void clearError() : Clears the internal error state of this stream.Syntax :protected void clearError()\n"
},
{
"code": null,
"e": 27799,
"s": 27762,
"text": "Syntax :protected void clearError()\n"
},
{
"code": null,
"e": 27948,
"s": 27799,
"text": "void close() : Closes the stream and releases any system resources associated with it.Syntax :public void close()\nSpecified by:close in class Writer"
},
{
"code": null,
"e": 28011,
"s": 27948,
"text": "Syntax :public void close()\nSpecified by:close in class Writer"
},
{
"code": null,
"e": 28150,
"s": 28011,
"text": "void flush(): Flushes the stream.Syntax :public void flush()\nSpecified by:flush in interface Flushable\nSpecified by:flush in class Writer\n"
},
{
"code": null,
"e": 28256,
"s": 28150,
"text": "Syntax :public void flush()\nSpecified by:flush in interface Flushable\nSpecified by:flush in class Writer\n"
},
{
"code": null,
"e": 28904,
"s": 28256,
"text": "PrintWriter format(Locale l, String format, Object... args): Writes a formatted string to this writer using the specified format string and arguments.Syntax :public PrintWriter format(Locale l,\n String format,\n Object... args)\nParameters:\n l - The locale to apply during formatting. If l is null,\n then no localization is applied.\n format - A format string as described in Format string syntax\n args - Arguments referenced by the format specifiers in the format string. \nThe number of arguments is variable and may be zero.\nReturns: This writer\nThrows:\n IllegalFormatException\n NullPointerException"
},
{
"code": null,
"e": 29402,
"s": 28904,
"text": "Syntax :public PrintWriter format(Locale l,\n String format,\n Object... args)\nParameters:\n l - The locale to apply during formatting. If l is null,\n then no localization is applied.\n format - A format string as described in Format string syntax\n args - Arguments referenced by the format specifiers in the format string. \nThe number of arguments is variable and may be zero.\nReturns: This writer\nThrows:\n IllegalFormatException\n NullPointerException"
},
{
"code": null,
"e": 29924,
"s": 29402,
"text": "PrintWriter format(String format, Object... args): Writes a formatted string to this writer using the specified format string and arguments.Syntax :public PrintWriter format(String format,\n Object... args)\nParameters:\n format - A format string as described in Format string syntax\n args - Arguments referenced by the format specifiers in the format string. \nThe number of arguments is variable and may be zero.\nReturns: This writer\nThrows:\n IllegalFormatException\n NullPointerException "
},
{
"code": null,
"e": 30306,
"s": 29924,
"text": "Syntax :public PrintWriter format(String format,\n Object... args)\nParameters:\n format - A format string as described in Format string syntax\n args - Arguments referenced by the format specifiers in the format string. \nThe number of arguments is variable and may be zero.\nReturns: This writer\nThrows:\n IllegalFormatException\n NullPointerException "
},
{
"code": null,
"e": 30389,
"s": 30306,
"text": "void print(boolean b): Prints a boolean value.Syntax :public void print(boolean b)"
},
{
"code": null,
"e": 30426,
"s": 30389,
"text": "Syntax :public void print(boolean b)"
},
{
"code": null,
"e": 30499,
"s": 30426,
"text": "void print(char c): Prints a character.Syntax :public void print(char c)"
},
{
"code": null,
"e": 30533,
"s": 30499,
"text": "Syntax :public void print(char c)"
},
{
"code": null,
"e": 30622,
"s": 30533,
"text": "void print(char[] s): Prints an array of characters.Syntax :public void print(char[] s)\n"
},
{
"code": null,
"e": 30659,
"s": 30622,
"text": "Syntax :public void print(char[] s)\n"
},
{
"code": null,
"e": 30766,
"s": 30659,
"text": "void print(double d) :Prints a double-precision floating-point number.Syntax :public void print(double b)\n"
},
{
"code": null,
"e": 30803,
"s": 30766,
"text": "Syntax :public void print(double b)\n"
},
{
"code": null,
"e": 30890,
"s": 30803,
"text": "void print(float f): Prints a floating-point number.Syntax :public void print(float f)"
},
{
"code": null,
"e": 30925,
"s": 30890,
"text": "Syntax :public void print(float f)"
},
{
"code": null,
"e": 30995,
"s": 30925,
"text": "void print(int i): Prints an integer.Syntax :public void print(int i)"
},
{
"code": null,
"e": 31028,
"s": 30995,
"text": "Syntax :public void print(int i)"
},
{
"code": null,
"e": 31104,
"s": 31028,
"text": "void print(long l): Prints a long integer.Syntax :public void print(long l)"
},
{
"code": null,
"e": 31138,
"s": 31104,
"text": "Syntax :public void print(long l)"
},
{
"code": null,
"e": 31217,
"s": 31138,
"text": "void print(Object obj) :Prints an object.Syntax :public void print(Object obj)"
},
{
"code": null,
"e": 31255,
"s": 31217,
"text": "Syntax :public void print(Object obj)"
},
{
"code": null,
"e": 31329,
"s": 31255,
"text": "void print(String s): Prints a string.Syntax :public void print(String s)"
},
{
"code": null,
"e": 31365,
"s": 31329,
"text": "Syntax :public void print(String s)"
},
{
"code": null,
"e": 31374,
"s": 31365,
"text": "Program:"
},
{
"code": "import java.io.*;import java.util.Locale;//Java program to demonstrate PrintWriterclass PrintWriterDemo { public static void main(String[] args) { String s=\"GeeksforGeeks\"; // create a new writer PrintWriter out = new PrintWriter(System.out); char c[]={'G','E','E','K'}; //illustrating print(boolean b) method out.print(true); //illustrating print(int i) method out.print(1); //illustrating print(float f) method out.print(4.533f); //illustrating print(String s) method out.print(\"GeeksforGeeks\"); out.println(); //illustrating print(Object Obj) method out.print(out); out.println(); //illustrating append(CharSequence csq) method out.append(\"Geek\"); out.println(); //illustrating checkError() method out.println(out.checkError()); //illustrating format() method out.format(Locale.UK, \"This is my %s program\", s); //illustrating flush method out.flush(); //illustrating close method out.close(); }}",
"e": 32580,
"s": 31374,
"text": null
},
{
"code": null,
"e": 32725,
"s": 32580,
"text": "Output:\n true14.533GeeksforGeeks\n java.io.PrintWriter@1540e19d\n Geek\n false\n This is my GeeksforGeeks program"
},
{
"code": null,
"e": 32781,
"s": 32725,
"text": "Next Article: Java.io.PrintWriter class in Java | Set 2"
},
{
"code": null,
"e": 33083,
"s": 32781,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33208,
"s": 33083,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33217,
"s": 33208,
"text": "Java-I/O"
},
{
"code": null,
"e": 33222,
"s": 33217,
"text": "Java"
},
{
"code": null,
"e": 33227,
"s": 33222,
"text": "Java"
},
{
"code": null,
"e": 33325,
"s": 33227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33334,
"s": 33325,
"text": "Comments"
},
{
"code": null,
"e": 33347,
"s": 33334,
"text": "Old Comments"
},
{
"code": null,
"e": 33398,
"s": 33347,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33428,
"s": 33398,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 33459,
"s": 33428,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33478,
"s": 33459,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33510,
"s": 33478,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 33528,
"s": 33510,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 33548,
"s": 33528,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 33580,
"s": 33548,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33604,
"s": 33580,
"text": "Singleton Class in Java"
}
] |
Django URL patterns | Python - GeeksforGeeks | 19 Jul, 2019
In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration)
Let the project name be myProject. The Python module to be used as URLConf is the value of ROOT_URLCONF in myProject/settings.py. By default this is set to 'myProject.urls'. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view.
Including other URLConf modulesIt is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows:
from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')),]
This tells Django to search for URL patterns in the file books/urls.py.
URL patterns
Here’s a sample code for books/urls.py:
from django.urls import pathfrom . import views urlpatterns = [ path('books/<int:pk>/', views.book_detail), path('books/<str:genre>/', views.books_by_genre), path('books/', views.book_index), ]
For example,
A URL request to /books/crime/ will match with the second URL pattern. As a result, Django will call the function views.books_by_genre(request, genre = "crime").
Similarly a URL request /books/25/ will match the first URL pattern and Django will call the function views.book_detail(request, pk =25).
Here, int and str are path convertors and capture an integer and string value respectively.
Path convertors:The following path convertor types are available in Django
int – Matches zero or any positive integer.
str – Matches any non-empty string, excluding the path separator(‘/’).
slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.
path – Matches any non-empty string including the path separator(‘/’)
uuid – Matches a UUID(universal unique identifier).
Python Django
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
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": 24198,
"s": 24170,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 24462,
"s": 24198,
"text": "In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration)"
},
{
"code": null,
"e": 24978,
"s": 24462,
"text": "Let the project name be myProject. The Python module to be used as URLConf is the value of ROOT_URLCONF in myProject/settings.py. By default this is set to 'myProject.urls'. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view."
},
{
"code": null,
"e": 25153,
"s": 24978,
"text": "Including other URLConf modulesIt is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows:"
},
{
"code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')),]",
"e": 25313,
"s": 25153,
"text": null
},
{
"code": null,
"e": 25385,
"s": 25313,
"text": "This tells Django to search for URL patterns in the file books/urls.py."
},
{
"code": null,
"e": 25398,
"s": 25385,
"text": "URL patterns"
},
{
"code": null,
"e": 25438,
"s": 25398,
"text": "Here’s a sample code for books/urls.py:"
},
{
"code": "from django.urls import pathfrom . import views urlpatterns = [ path('books/<int:pk>/', views.book_detail), path('books/<str:genre>/', views.books_by_genre), path('books/', views.book_index), ]",
"e": 25642,
"s": 25438,
"text": null
},
{
"code": null,
"e": 25655,
"s": 25642,
"text": "For example,"
},
{
"code": null,
"e": 25817,
"s": 25655,
"text": "A URL request to /books/crime/ will match with the second URL pattern. As a result, Django will call the function views.books_by_genre(request, genre = \"crime\")."
},
{
"code": null,
"e": 25955,
"s": 25817,
"text": "Similarly a URL request /books/25/ will match the first URL pattern and Django will call the function views.book_detail(request, pk =25)."
},
{
"code": null,
"e": 26047,
"s": 25955,
"text": "Here, int and str are path convertors and capture an integer and string value respectively."
},
{
"code": null,
"e": 26122,
"s": 26047,
"text": "Path convertors:The following path convertor types are available in Django"
},
{
"code": null,
"e": 26166,
"s": 26122,
"text": "int – Matches zero or any positive integer."
},
{
"code": null,
"e": 26237,
"s": 26166,
"text": "str – Matches any non-empty string, excluding the path separator(‘/’)."
},
{
"code": null,
"e": 26340,
"s": 26237,
"text": "slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score."
},
{
"code": null,
"e": 26410,
"s": 26340,
"text": "path – Matches any non-empty string including the path separator(‘/’)"
},
{
"code": null,
"e": 26462,
"s": 26410,
"text": "uuid – Matches a UUID(universal unique identifier)."
},
{
"code": null,
"e": 26476,
"s": 26462,
"text": "Python Django"
},
{
"code": null,
"e": 26483,
"s": 26476,
"text": "Python"
},
{
"code": null,
"e": 26500,
"s": 26483,
"text": "Web Technologies"
},
{
"code": null,
"e": 26598,
"s": 26500,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26616,
"s": 26598,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26651,
"s": 26616,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26673,
"s": 26651,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26705,
"s": 26673,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26735,
"s": 26705,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26777,
"s": 26735,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26810,
"s": 26777,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26853,
"s": 26810,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26915,
"s": 26853,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Compound Finite Automata (FA) - GeeksforGeeks | 27 May, 2019
Prerequisite – Finite Automata (FA)Compound FA is the resultant DFA formed after performing operation (∪, ∩, -) on given DFAs D1 and D2.
D1 = (Q1, ∑, δ, q1, F1) and D2 = (Q2, ∑, δ, q2, F2)
Where,Q1 and Q2: Set of finite states of DFA D1 and D2 respectively.∑: Input alphabet contain finite number of input symbols.δ: Transition function (δ:Qx∑->Q)q1 and q2: Initial state of D1 and D2 respectively.F1 and F2: Set of final states of DFA D1 and D2 respectively.
Properties of Compound Finite Automata (FA):
Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2.Initial state of compound FA is combination of initial states of D1 and D2.Final state of compound FA depends on the operation performed.
Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2.
Initial state of compound FA is combination of initial states of D1 and D2.
Final state of compound FA depends on the operation performed.
Example:
D1 = no. of a's divisible by 2
D2 = no. of b's divisible by 3
D1 ({q1, B}, {a, b}, δ, q1, {q1}),
D1 ({q2, A, C}, {a, b}, δ, q2, {q2})
Construct the minimal FA for:
(D1∪D2),
(D1∩D2),
(D1-D2),
(D2-D1)
Explanation:
DFA D1:
DFA D2:
1. Union (D1∪D2):Any string w which is either belong’s to the language of D1 or the language of D2 is accepted by resultant compound automata.Final state: If final state of D1 or final state of D2 contain in any of the states of compound FA.
2. Intersection (D1∩D2):Any string w which belong’s to both the language of D1 and the language of D2 is accepted by resultant compound automata.Final state: If both final state of D1 and final state of D2 contain in any of the states of compound FA.
3. Difference (D1 – D2):Any string w which is accepted by D1, not by D2.Final state: If final state of D1 and non-final state of D2 contain in any of the states of compound FA.
4. Difference (D2 – D1):Any string w which is accepted by D2, not by D1.Final state: If final state of D2 and non-final state of D1 contain in any of the states of compound FA.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Differences between IPv4 and IPv6
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation | [
{
"code": null,
"e": 24352,
"s": 24324,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 24489,
"s": 24352,
"text": "Prerequisite – Finite Automata (FA)Compound FA is the resultant DFA formed after performing operation (∪, ∩, -) on given DFAs D1 and D2."
},
{
"code": null,
"e": 24542,
"s": 24489,
"text": "D1 = (Q1, ∑, δ, q1, F1) and D2 = (Q2, ∑, δ, q2, F2) "
},
{
"code": null,
"e": 24813,
"s": 24542,
"text": "Where,Q1 and Q2: Set of finite states of DFA D1 and D2 respectively.∑: Input alphabet contain finite number of input symbols.δ: Transition function (δ:Qx∑->Q)q1 and q2: Initial state of D1 and D2 respectively.F1 and F2: Set of final states of DFA D1 and D2 respectively."
},
{
"code": null,
"e": 24858,
"s": 24813,
"text": "Properties of Compound Finite Automata (FA):"
},
{
"code": null,
"e": 25124,
"s": 24858,
"text": "Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2.Initial state of compound FA is combination of initial states of D1 and D2.Final state of compound FA depends on the operation performed."
},
{
"code": null,
"e": 25253,
"s": 25124,
"text": "Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2."
},
{
"code": null,
"e": 25329,
"s": 25253,
"text": "Initial state of compound FA is combination of initial states of D1 and D2."
},
{
"code": null,
"e": 25392,
"s": 25329,
"text": "Final state of compound FA depends on the operation performed."
},
{
"code": null,
"e": 25401,
"s": 25392,
"text": "Example:"
},
{
"code": null,
"e": 25538,
"s": 25401,
"text": "D1 = no. of a's divisible by 2\nD2 = no. of b's divisible by 3\n\nD1 ({q1, B}, {a, b}, δ, q1, {q1}), \nD1 ({q2, A, C}, {a, b}, δ, q2, {q2}) "
},
{
"code": null,
"e": 25568,
"s": 25538,
"text": "Construct the minimal FA for:"
},
{
"code": null,
"e": 25606,
"s": 25568,
"text": "(D1∪D2), \n(D1∩D2), \n(D1-D2),\n(D2-D1) "
},
{
"code": null,
"e": 25619,
"s": 25606,
"text": "Explanation:"
},
{
"code": null,
"e": 25627,
"s": 25619,
"text": "DFA D1:"
},
{
"code": null,
"e": 25635,
"s": 25627,
"text": "DFA D2:"
},
{
"code": null,
"e": 25877,
"s": 25635,
"text": "1. Union (D1∪D2):Any string w which is either belong’s to the language of D1 or the language of D2 is accepted by resultant compound automata.Final state: If final state of D1 or final state of D2 contain in any of the states of compound FA."
},
{
"code": null,
"e": 26128,
"s": 25877,
"text": "2. Intersection (D1∩D2):Any string w which belong’s to both the language of D1 and the language of D2 is accepted by resultant compound automata.Final state: If both final state of D1 and final state of D2 contain in any of the states of compound FA."
},
{
"code": null,
"e": 26305,
"s": 26128,
"text": "3. Difference (D1 – D2):Any string w which is accepted by D1, not by D2.Final state: If final state of D1 and non-final state of D2 contain in any of the states of compound FA."
},
{
"code": null,
"e": 26482,
"s": 26305,
"text": "4. Difference (D2 – D1):Any string w which is accepted by D2, not by D1.Final state: If final state of D2 and non-final state of D1 contain in any of the states of compound FA."
},
{
"code": null,
"e": 26490,
"s": 26482,
"text": "GATE CS"
},
{
"code": null,
"e": 26523,
"s": 26490,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 26621,
"s": 26523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26674,
"s": 26621,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26695,
"s": 26674,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 26736,
"s": 26695,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 26776,
"s": 26736,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 26810,
"s": 26776,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 26869,
"s": 26810,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 26900,
"s": 26869,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 26932,
"s": 26900,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 26983,
"s": 26932,
"text": "Difference between Mealy machine and Moore machine"
}
] |
__call__ in Python - GeeksforGeeks | 27 Feb, 2020
Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).
object() is shorthand for object.__call__()
Example 1:
class Example: def __init__(self): print("Instance Created") # Defining __call__ method def __call__(self): print("Instance is called via special method") # Instance createde = Example() # __call__ method will be callede()
Output :
Instance Created
Instance is called via special method
Example 2:
class Product: def __init__(self): print("Instance Created") # Defining __call__ method def __call__(self, a, b): print(a * b) # Instance createdans = Product() # __call__ method will be calledans(10, 20)
Output :
Instance Created
200
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24038,
"s": 24010,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24382,
"s": 24038,
"text": "Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...)."
},
{
"code": null,
"e": 24426,
"s": 24382,
"text": "object() is shorthand for object.__call__()"
},
{
"code": null,
"e": 24437,
"s": 24426,
"text": "Example 1:"
},
{
"code": "class Example: def __init__(self): print(\"Instance Created\") # Defining __call__ method def __call__(self): print(\"Instance is called via special method\") # Instance createde = Example() # __call__ method will be callede()",
"e": 24691,
"s": 24437,
"text": null
},
{
"code": null,
"e": 24700,
"s": 24691,
"text": "Output :"
},
{
"code": null,
"e": 24756,
"s": 24700,
"text": "Instance Created\nInstance is called via special method\n"
},
{
"code": null,
"e": 24767,
"s": 24756,
"text": "Example 2:"
},
{
"code": "class Product: def __init__(self): print(\"Instance Created\") # Defining __call__ method def __call__(self, a, b): print(a * b) # Instance createdans = Product() # __call__ method will be calledans(10, 20)",
"e": 24999,
"s": 24767,
"text": null
},
{
"code": null,
"e": 25008,
"s": 24999,
"text": "Output :"
},
{
"code": null,
"e": 25030,
"s": 25008,
"text": "Instance Created\n200\n"
},
{
"code": null,
"e": 25047,
"s": 25030,
"text": "Python-Functions"
},
{
"code": null,
"e": 25054,
"s": 25047,
"text": "Python"
},
{
"code": null,
"e": 25152,
"s": 25054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25161,
"s": 25152,
"text": "Comments"
},
{
"code": null,
"e": 25174,
"s": 25161,
"text": "Old Comments"
},
{
"code": null,
"e": 25192,
"s": 25174,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25227,
"s": 25192,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25249,
"s": 25227,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25281,
"s": 25249,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25311,
"s": 25281,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25353,
"s": 25311,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25396,
"s": 25353,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25422,
"s": 25396,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25466,
"s": 25422,
"text": "Reading and Writing to text files in Python"
}
] |
Install custom Python Libraries from private PyPI on Databricks | by David Suarez | Towards Data Science | This method opens up the door for sharing code and libraries across data teams while keeping versioning. Moreover, it gives the possibility to apply hybrid coding approaches on Databricks where you can combine libraries written on local machine (properly tested and released using CI/CD pipelines) and Notebooks using those libraries.
Note: this tutorial is focused on Azure. If you happen to be working on a different cloud provider but you are still interested in this topic, keep reading. You will most likely be able to easily translate the concept to other environments as well.
Databricks provides a very simple way of installing public Libraries on Clusters, so you can install them with just a few clicks. Unfortunately, when it comes to self-made custom Libraries, the process is not as easy.
In this case, the most popular solution that I have seen so far is packaging the code into a Python Wheel and upload it to a Blob Storage, so you can install it as a DBFS Library. The second solution found is installing a Library directly from a Git Repository, so you have to provide Git URL and authentication method. Although both solutions do the trick, we are missing something very important here: versioning.
When writing your own libraries, sometimes you’ll be writing code that is so tailored to a specific solution that the reuse possibilities are not too high. In other occasions, you might create a code package with classes and utility functions that you would like to share with your co-workers so they don’t have to reinvent the wheel. In both cases, if you keep working on your library, you will be introducing changes that could mess up solutions that are even running in production.
The only way to prevent that from happening and keep everybody happy, is by introducing library versioning. This way, each solution or environment can use a different fixed version of the library and nothing will break when changes are introduced.
Coming back to self-made Libraries in Databricks, none of the previous presented approaches come with a robust solution for this issue. You can either upload and maintain Python Wheels with different version names on Blob Storage, or release branches on the Git Repo. Even if that does the trick, it will be hard to trace back the changes of each version, and you will have to build and maintain the mechanism yourself, and even harder, align with all the users of your library. In other words, these are clunky workarounds for an already solved problem.
PyPI repositories have been around for years, and the most popular Python libraries out there are published on a public PyPI repo. In the same way, you can have your own PyPI repository and benefit from the versioning capabilities as well — and you may want this repository to be private so your organization libraries are not publicly available to everyone.
On Azure DevOps, it’s super easy to have your own private PyPI repository. You just need to create an Artifact Feed, which under the hood has package repositories for the most common programming languages. After that, you can publish your Python Wheels there and benefit from all the features of it. For example: the ability of keeping track from what commit of your Git Repo each version was released.
So now that I have explained some of the benefits of using a Private PyPI repository for keeping our custom Libraries’ versions, let’s see how can we integrate it on Databricks Clusters so you are able to install your custom Libraries.
In summary, you need your custom Python Package published in an Azure Artifact Feed, and a KeyVault registered as a secret scope in a Databricks Workspace.
If you are a bit lost and don’t know how to get there yet, here’s a list with all prerequisites with some helpful links:
Azure DevOps project.
Git Repo in Azure Repos (how to create a Git repo here).
Python code in the Git Repo with a setup.py to generate a Python Wheel (how to generate a Python Wheel here).
Artifact Feed (how to create an Artifact Feed here).
Azure Pipeline YAML file in the Git Repo to generate and publish the Python Wheel to the Artifact Feed (code here).
Register and run Azure Pipeline from YAML file (how to do it here).
Azure Databricks Workspace.
Azure Key Vault.
Azure Key Vault registered in Databricks Workspace as a Secret Scope (how to do it here).
For this article I’ve made a demo setup, and it might be good for you to see it for just in case you see any reference.
The Python package that I use for the demo (called “demopackage”) is very simple. It contains just a couple of functions that generates Dataframes with PySpark and Pandas. As you can see in the picture, it’s also been published to my Artifact Feed called “datalabartifacts”.
On Azure, I just have a Resource Group with Databricks and Key Vault. Furthermore, the Key Vault has been registered in Databricks as a Secret Scope with the same name.
The goal of this process is to allow the underlying VMs of the Spark Clusters in Databricks to integrate your Private PyPI repository existing in Artifact Feed and to be able to install Python Libraries from it.
Because our Artifact Feed is private (and we want to keep it private), we need to provide a way for our VMs to authenticate against the Arifact Feed.
Unfortunately, after doing a lot of research, the securest way of doing so that I’ve found is using an Azure DevOps Personal Access Tokens (PAT). This PAT is personal and issued per DevOps user, so the Spark VMs will use this token to impersonate as the user to do the authentication. This means that in the Artifact Feed registry you will see that the issuer user is the one downloading packages. Moreover, the PAT expires after one year, so be aware you will need to renew it before it expires.
The advice here is to create a Service Account (fake user in DevOps) with restricted access and only used for generating this PAT, and renew it before the expiration day.
In any case, you can generate a Personal Access Token from Azure DevOps by clicking on User Settings → Personal access tokens → New Token. Give it a name, specify the expiration time, and the permissions of the PAT (only Read on Packaging is required). Once you are done, copy the generated token.
The generated token can be used to retrieve packages from the Artifact Feed. If this gets exfiltrated outside of your organisation, this can be a big problem. It means that hackers can steal the software packages available in the Artifact Feeds.
Nobody wants that to happen, so we need to store the token in a safe place so we can use it without exposing it as plain text. For that, we need to create a new Secret in Azure Key Vault to store it.
Go to your Key Vault, click on Secrets → Generate/Import, and create a secret by giving it a name and using the PAT token generated in the previous step as value.
Note: the Key Vault used needs to be the one registered in the Databricks Workspace as Secret Scope.
It’s finally time to jump into Databricks Workspace!
Go to Compute→ select Cluster → Cofiguration, and proceed to edit it. Under Advanced Options, add the following Environment Variable:
PYPI_TOKEN={{secrets/YourSecretScopeName/pypitoken}}
This way, we are setting a value from a Secret on the Secret Scope that is connected to our Key Vault.
Note: Don’t forget to replace the Secret Scope and Secret names by your own.
Let’s move back to Azure DevOps for a second and get the URL of the private PyPI repository.
To do this, click on Artifacts → select your Artifact Feed→ Connect to feed → pip, and then copy the URL.
Before introducing the magic sauce, let me first explain the trick.
When you install a Library on a Databricks Cluster using the UI, Databricks instructs all the nodes to install the Library individually, so they pull the package and proceed with the installation.
This means that if we want to install packages from private PyPI repositories in Databricks Clusters, every node needs to be able to 1) find the private PyPI repo, and 2) authenticate successfully against it.
In order to do that, we have to tell each cluster node Pip installation what is the URL of the private PyPI repo, and how to authenticate, in this case by using the token authentication. The place to do that is the /etc/pip.conf file where we have to add new a extra-index-url.
In practice, we can achieve this in Databricks by making use of Init Scripts. These are Shell scripts that run on each node during cluster initialization.
The Init Script on itself would look like this (note that you have to replace the PyPI URL by your own):
#!/bin/bashif [[ $PYPI_TOKEN ]]; then use $PYPI_TOKEN fiecho $PYPI_TOKENprintf "[global]\n" > /etc/pip.confprintf "extra-index-url =\n" >> /etc/pip.confprintf "\thttps://[email protected]/organization/DataLab/_packaging/datalabartifacts/pypi/simple/\n" >> /etc/pip.conf
As you can see, we are setting references of the previously created Cluster Environment Variable PYPI_TOKEN into the /etc/pip.conf file, meaning no plain text is shown at all since the value will resolve at runtime.
Note: In case you try to display its value on Logs using echo command, you will only see [REDACTED] since Databricks hide all values coming from Secret Scopes.
Because it can be a bit tricky to upload the script manually to Databricks, it’s better to generate it easily from a Notebook by running the following code on a cell (don’t forget to replace the PyPI URL by your own):
script = r"""#!/bin/bashif [[ $PYPI_TOKEN ]]; then use $PYPI_TOKENfiecho $PYPI_TOKENprintf "[global]\n" > /etc/pip.confprintf "extra-index-url =\n" >> /etc/pip.confprintf "\thttps://[email protected]/organization/DataLab/_packaging/datalabartifacts/pypi/simple/\n" >> /etc/pip.conf"""dbutils.fs.put("/databricks/scripts/init-scripts/set-private-pip-repositories.sh", script, True)
Note: in this way we are creating a Cluster-scoped init script, better option than Global Init Script in this case, since the absence of the Env Variable would make other clusters’ initialization fail.
Now we want our cluster to run this Init Script during initialization process. For that we go to Compute → select Cluster → Configuration, and edit the same cluster again. This time, we will add the Init Script DBFS path under Advanced Options.
At this point in time, you can already start the cluster. It will run the Init Script and therefor your Private PyPI repository of your Artifact Feed will be totally accessible.
Just as usual, go to Compute → select your Cluster → Libraries → Install New Library.
Here you have to specify the name of your published package in the Artifact Feed, together with the specific version you want to install (unfortunately, it seems to be mandatory).
After a while you will see that the installation has succeeded! 🥳
Note: be aware that now Pip is searching for packages in more than one PyPI repository. Because of this, you could have Library name collisions if there is another Library with the same name in another repository. If you don’t use unique Library names, it’s not guaranteed that you will install the Library you actually want..
Finally, you can just open a new Databricks Notebook, import your library and enjoy the results! 🚀
Once you have reached this point, I think you can already imagine how nice this can be. This opens up the door for sharing code and libraries across data teams while keeping versioning.
Furthermore, it gives the possibility of thinking of hybrid coding approaches on Databricks where you can combine libraries written on local machine (properly tested and released using CI/CD pipelines) and Notebooks using those libraries.
I haven’t seen this method published anywhere else on the internet, so that’s why I decided to publish it here. I hope this is as helpful to you as it was for me a many of my colleagues. Good luck! | [
{
"code": null,
"e": 506,
"s": 171,
"text": "This method opens up the door for sharing code and libraries across data teams while keeping versioning. Moreover, it gives the possibility to apply hybrid coding approaches on Databricks where you can combine libraries written on local machine (properly tested and released using CI/CD pipelines) and Notebooks using those libraries."
},
{
"code": null,
"e": 755,
"s": 506,
"text": "Note: this tutorial is focused on Azure. If you happen to be working on a different cloud provider but you are still interested in this topic, keep reading. You will most likely be able to easily translate the concept to other environments as well."
},
{
"code": null,
"e": 973,
"s": 755,
"text": "Databricks provides a very simple way of installing public Libraries on Clusters, so you can install them with just a few clicks. Unfortunately, when it comes to self-made custom Libraries, the process is not as easy."
},
{
"code": null,
"e": 1389,
"s": 973,
"text": "In this case, the most popular solution that I have seen so far is packaging the code into a Python Wheel and upload it to a Blob Storage, so you can install it as a DBFS Library. The second solution found is installing a Library directly from a Git Repository, so you have to provide Git URL and authentication method. Although both solutions do the trick, we are missing something very important here: versioning."
},
{
"code": null,
"e": 1874,
"s": 1389,
"text": "When writing your own libraries, sometimes you’ll be writing code that is so tailored to a specific solution that the reuse possibilities are not too high. In other occasions, you might create a code package with classes and utility functions that you would like to share with your co-workers so they don’t have to reinvent the wheel. In both cases, if you keep working on your library, you will be introducing changes that could mess up solutions that are even running in production."
},
{
"code": null,
"e": 2122,
"s": 1874,
"text": "The only way to prevent that from happening and keep everybody happy, is by introducing library versioning. This way, each solution or environment can use a different fixed version of the library and nothing will break when changes are introduced."
},
{
"code": null,
"e": 2677,
"s": 2122,
"text": "Coming back to self-made Libraries in Databricks, none of the previous presented approaches come with a robust solution for this issue. You can either upload and maintain Python Wheels with different version names on Blob Storage, or release branches on the Git Repo. Even if that does the trick, it will be hard to trace back the changes of each version, and you will have to build and maintain the mechanism yourself, and even harder, align with all the users of your library. In other words, these are clunky workarounds for an already solved problem."
},
{
"code": null,
"e": 3036,
"s": 2677,
"text": "PyPI repositories have been around for years, and the most popular Python libraries out there are published on a public PyPI repo. In the same way, you can have your own PyPI repository and benefit from the versioning capabilities as well — and you may want this repository to be private so your organization libraries are not publicly available to everyone."
},
{
"code": null,
"e": 3439,
"s": 3036,
"text": "On Azure DevOps, it’s super easy to have your own private PyPI repository. You just need to create an Artifact Feed, which under the hood has package repositories for the most common programming languages. After that, you can publish your Python Wheels there and benefit from all the features of it. For example: the ability of keeping track from what commit of your Git Repo each version was released."
},
{
"code": null,
"e": 3675,
"s": 3439,
"text": "So now that I have explained some of the benefits of using a Private PyPI repository for keeping our custom Libraries’ versions, let’s see how can we integrate it on Databricks Clusters so you are able to install your custom Libraries."
},
{
"code": null,
"e": 3831,
"s": 3675,
"text": "In summary, you need your custom Python Package published in an Azure Artifact Feed, and a KeyVault registered as a secret scope in a Databricks Workspace."
},
{
"code": null,
"e": 3952,
"s": 3831,
"text": "If you are a bit lost and don’t know how to get there yet, here’s a list with all prerequisites with some helpful links:"
},
{
"code": null,
"e": 3974,
"s": 3952,
"text": "Azure DevOps project."
},
{
"code": null,
"e": 4031,
"s": 3974,
"text": "Git Repo in Azure Repos (how to create a Git repo here)."
},
{
"code": null,
"e": 4141,
"s": 4031,
"text": "Python code in the Git Repo with a setup.py to generate a Python Wheel (how to generate a Python Wheel here)."
},
{
"code": null,
"e": 4194,
"s": 4141,
"text": "Artifact Feed (how to create an Artifact Feed here)."
},
{
"code": null,
"e": 4310,
"s": 4194,
"text": "Azure Pipeline YAML file in the Git Repo to generate and publish the Python Wheel to the Artifact Feed (code here)."
},
{
"code": null,
"e": 4378,
"s": 4310,
"text": "Register and run Azure Pipeline from YAML file (how to do it here)."
},
{
"code": null,
"e": 4406,
"s": 4378,
"text": "Azure Databricks Workspace."
},
{
"code": null,
"e": 4423,
"s": 4406,
"text": "Azure Key Vault."
},
{
"code": null,
"e": 4513,
"s": 4423,
"text": "Azure Key Vault registered in Databricks Workspace as a Secret Scope (how to do it here)."
},
{
"code": null,
"e": 4633,
"s": 4513,
"text": "For this article I’ve made a demo setup, and it might be good for you to see it for just in case you see any reference."
},
{
"code": null,
"e": 4908,
"s": 4633,
"text": "The Python package that I use for the demo (called “demopackage”) is very simple. It contains just a couple of functions that generates Dataframes with PySpark and Pandas. As you can see in the picture, it’s also been published to my Artifact Feed called “datalabartifacts”."
},
{
"code": null,
"e": 5077,
"s": 4908,
"text": "On Azure, I just have a Resource Group with Databricks and Key Vault. Furthermore, the Key Vault has been registered in Databricks as a Secret Scope with the same name."
},
{
"code": null,
"e": 5289,
"s": 5077,
"text": "The goal of this process is to allow the underlying VMs of the Spark Clusters in Databricks to integrate your Private PyPI repository existing in Artifact Feed and to be able to install Python Libraries from it."
},
{
"code": null,
"e": 5439,
"s": 5289,
"text": "Because our Artifact Feed is private (and we want to keep it private), we need to provide a way for our VMs to authenticate against the Arifact Feed."
},
{
"code": null,
"e": 5936,
"s": 5439,
"text": "Unfortunately, after doing a lot of research, the securest way of doing so that I’ve found is using an Azure DevOps Personal Access Tokens (PAT). This PAT is personal and issued per DevOps user, so the Spark VMs will use this token to impersonate as the user to do the authentication. This means that in the Artifact Feed registry you will see that the issuer user is the one downloading packages. Moreover, the PAT expires after one year, so be aware you will need to renew it before it expires."
},
{
"code": null,
"e": 6107,
"s": 5936,
"text": "The advice here is to create a Service Account (fake user in DevOps) with restricted access and only used for generating this PAT, and renew it before the expiration day."
},
{
"code": null,
"e": 6405,
"s": 6107,
"text": "In any case, you can generate a Personal Access Token from Azure DevOps by clicking on User Settings → Personal access tokens → New Token. Give it a name, specify the expiration time, and the permissions of the PAT (only Read on Packaging is required). Once you are done, copy the generated token."
},
{
"code": null,
"e": 6651,
"s": 6405,
"text": "The generated token can be used to retrieve packages from the Artifact Feed. If this gets exfiltrated outside of your organisation, this can be a big problem. It means that hackers can steal the software packages available in the Artifact Feeds."
},
{
"code": null,
"e": 6851,
"s": 6651,
"text": "Nobody wants that to happen, so we need to store the token in a safe place so we can use it without exposing it as plain text. For that, we need to create a new Secret in Azure Key Vault to store it."
},
{
"code": null,
"e": 7014,
"s": 6851,
"text": "Go to your Key Vault, click on Secrets → Generate/Import, and create a secret by giving it a name and using the PAT token generated in the previous step as value."
},
{
"code": null,
"e": 7115,
"s": 7014,
"text": "Note: the Key Vault used needs to be the one registered in the Databricks Workspace as Secret Scope."
},
{
"code": null,
"e": 7168,
"s": 7115,
"text": "It’s finally time to jump into Databricks Workspace!"
},
{
"code": null,
"e": 7302,
"s": 7168,
"text": "Go to Compute→ select Cluster → Cofiguration, and proceed to edit it. Under Advanced Options, add the following Environment Variable:"
},
{
"code": null,
"e": 7355,
"s": 7302,
"text": "PYPI_TOKEN={{secrets/YourSecretScopeName/pypitoken}}"
},
{
"code": null,
"e": 7458,
"s": 7355,
"text": "This way, we are setting a value from a Secret on the Secret Scope that is connected to our Key Vault."
},
{
"code": null,
"e": 7535,
"s": 7458,
"text": "Note: Don’t forget to replace the Secret Scope and Secret names by your own."
},
{
"code": null,
"e": 7628,
"s": 7535,
"text": "Let’s move back to Azure DevOps for a second and get the URL of the private PyPI repository."
},
{
"code": null,
"e": 7734,
"s": 7628,
"text": "To do this, click on Artifacts → select your Artifact Feed→ Connect to feed → pip, and then copy the URL."
},
{
"code": null,
"e": 7802,
"s": 7734,
"text": "Before introducing the magic sauce, let me first explain the trick."
},
{
"code": null,
"e": 7999,
"s": 7802,
"text": "When you install a Library on a Databricks Cluster using the UI, Databricks instructs all the nodes to install the Library individually, so they pull the package and proceed with the installation."
},
{
"code": null,
"e": 8208,
"s": 7999,
"text": "This means that if we want to install packages from private PyPI repositories in Databricks Clusters, every node needs to be able to 1) find the private PyPI repo, and 2) authenticate successfully against it."
},
{
"code": null,
"e": 8486,
"s": 8208,
"text": "In order to do that, we have to tell each cluster node Pip installation what is the URL of the private PyPI repo, and how to authenticate, in this case by using the token authentication. The place to do that is the /etc/pip.conf file where we have to add new a extra-index-url."
},
{
"code": null,
"e": 8641,
"s": 8486,
"text": "In practice, we can achieve this in Databricks by making use of Init Scripts. These are Shell scripts that run on each node during cluster initialization."
},
{
"code": null,
"e": 8746,
"s": 8641,
"text": "The Init Script on itself would look like this (note that you have to replace the PyPI URL by your own):"
},
{
"code": null,
"e": 9031,
"s": 8746,
"text": "#!/bin/bashif [[ $PYPI_TOKEN ]]; then use $PYPI_TOKEN fiecho $PYPI_TOKENprintf \"[global]\\n\" > /etc/pip.confprintf \"extra-index-url =\\n\" >> /etc/pip.confprintf \"\\thttps://[email protected]/organization/DataLab/_packaging/datalabartifacts/pypi/simple/\\n\" >> /etc/pip.conf"
},
{
"code": null,
"e": 9247,
"s": 9031,
"text": "As you can see, we are setting references of the previously created Cluster Environment Variable PYPI_TOKEN into the /etc/pip.conf file, meaning no plain text is shown at all since the value will resolve at runtime."
},
{
"code": null,
"e": 9407,
"s": 9247,
"text": "Note: In case you try to display its value on Logs using echo command, you will only see [REDACTED] since Databricks hide all values coming from Secret Scopes."
},
{
"code": null,
"e": 9625,
"s": 9407,
"text": "Because it can be a bit tricky to upload the script manually to Databricks, it’s better to generate it easily from a Notebook by running the following code on a cell (don’t forget to replace the PyPI URL by your own):"
},
{
"code": null,
"e": 10020,
"s": 9625,
"text": "script = r\"\"\"#!/bin/bashif [[ $PYPI_TOKEN ]]; then use $PYPI_TOKENfiecho $PYPI_TOKENprintf \"[global]\\n\" > /etc/pip.confprintf \"extra-index-url =\\n\" >> /etc/pip.confprintf \"\\thttps://[email protected]/organization/DataLab/_packaging/datalabartifacts/pypi/simple/\\n\" >> /etc/pip.conf\"\"\"dbutils.fs.put(\"/databricks/scripts/init-scripts/set-private-pip-repositories.sh\", script, True)"
},
{
"code": null,
"e": 10222,
"s": 10020,
"text": "Note: in this way we are creating a Cluster-scoped init script, better option than Global Init Script in this case, since the absence of the Env Variable would make other clusters’ initialization fail."
},
{
"code": null,
"e": 10467,
"s": 10222,
"text": "Now we want our cluster to run this Init Script during initialization process. For that we go to Compute → select Cluster → Configuration, and edit the same cluster again. This time, we will add the Init Script DBFS path under Advanced Options."
},
{
"code": null,
"e": 10645,
"s": 10467,
"text": "At this point in time, you can already start the cluster. It will run the Init Script and therefor your Private PyPI repository of your Artifact Feed will be totally accessible."
},
{
"code": null,
"e": 10731,
"s": 10645,
"text": "Just as usual, go to Compute → select your Cluster → Libraries → Install New Library."
},
{
"code": null,
"e": 10911,
"s": 10731,
"text": "Here you have to specify the name of your published package in the Artifact Feed, together with the specific version you want to install (unfortunately, it seems to be mandatory)."
},
{
"code": null,
"e": 10977,
"s": 10911,
"text": "After a while you will see that the installation has succeeded! 🥳"
},
{
"code": null,
"e": 11304,
"s": 10977,
"text": "Note: be aware that now Pip is searching for packages in more than one PyPI repository. Because of this, you could have Library name collisions if there is another Library with the same name in another repository. If you don’t use unique Library names, it’s not guaranteed that you will install the Library you actually want.."
},
{
"code": null,
"e": 11403,
"s": 11304,
"text": "Finally, you can just open a new Databricks Notebook, import your library and enjoy the results! 🚀"
},
{
"code": null,
"e": 11589,
"s": 11403,
"text": "Once you have reached this point, I think you can already imagine how nice this can be. This opens up the door for sharing code and libraries across data teams while keeping versioning."
},
{
"code": null,
"e": 11828,
"s": 11589,
"text": "Furthermore, it gives the possibility of thinking of hybrid coding approaches on Databricks where you can combine libraries written on local machine (properly tested and released using CI/CD pipelines) and Notebooks using those libraries."
}
] |
WML - Inputs | WML provides various options to let a user enter information through WAP application.
First of all, we are going to look at the different options for allowing the user to make straight choices between items. These are usually in the form of menus and submenus, allowing users to drill down to the exact data that they want.
The <select>...</select> WML elements are used to define a selection list and the <option>...</option> tags are used to define an item in a selection list. Items are presented as radiobuttons in some WAP browsers. The <option>...</option> tag pair should be enclosed within the <select>...</select> tags.
This element support the following attributes:
true
false
Following is the example showing usage of these two elements.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select>
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
</select>
</p>
</card>
</wml>
When you will load this program, it will show you the following screen:
Once you highlight and enter on the options, it will display the following screen:
You want to provide option to select multiple options, then set multiple attribute to true as follows:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select multiple="true">
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
</select>
</p>
</card>
</wml>
This will give you a screen to select multiple options as follows:
The <input/> element is used to create input fields and input fields are used to obtain alphanumeric data from users.
This element support the following attributes:
true
false
A = uppercase alphabetic or punctuation characters
a = lowercase alphabetic or punctuation characters
N = numeric characters
X = uppercase characters
x = lowercase characters
M = all characters
m = all characters
*f = Any number of characters. Replace the f with one of the letters above to specify what characters the user can enter
nf = Replace the n with a number from 1 to 9 to specify the number of characters the user can enter. Replace the f with one of the letters above to specify what characters the user can enter
text
password
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Input Fields">
<p> Enter Following Information:<br/>
Name: <input name="name" size="12"/>
Age : <input name="age" size="12" format="*N"/>
Sex : <input name="sex" size="12"/>
</p>
</card>
</wml>
This will provide you the following screen to enter required information:
The <fieldset/> element is used to group various input fields or selectable lists.
This element support the following attributes:
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Grouped Fields">
<p>
<fieldset title="Personal Info">
Name: <input name="name" size="12"/>
Age : <input name="age" size="12" format="*N"/>
Sex : <input name="sex" size="12"/>
</fieldset>
</p>
</card>
</wml>
This will provide you the following screen to enter required information. This result may differ browser to browser.
The <optgroup/> element is used to group various options together inside a selectable list.
This element support the following attributes:
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p>
<select>
<optgroup title="India">
<option value="delhi">Delhi</option>
<option value="mumbai">Mumbai</option>
<option value="hyderabad">Hyderabad</option>
</optgroup>
<optgroup title="USA">
<option value="ohio">Ohio</option>
<option value="maryland">Maryland</option>
<option value="washington">Washingtone</option>
</optgroup>
</select>
</p>
</card>
</wml>
When a user loads above code, then it will give two options to be selected:
When a user selects any of the options, then only it will give final options to be selected. So if user selects India, then it will show you following options to be selected:
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2025,
"s": 1939,
"text": "WML provides various options to let a user enter information through WAP application."
},
{
"code": null,
"e": 2263,
"s": 2025,
"text": "First of all, we are going to look at the different options for allowing the user to make straight choices between items. These are usually in the form of menus and submenus, allowing users to drill down to the exact data that they want."
},
{
"code": null,
"e": 2568,
"s": 2263,
"text": "The <select>...</select> WML elements are used to define a selection list and the <option>...</option> tags are used to define an item in a selection list. Items are presented as radiobuttons in some WAP browsers. The <option>...</option> tag pair should be enclosed within the <select>...</select> tags."
},
{
"code": null,
"e": 2615,
"s": 2568,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 2620,
"s": 2615,
"text": "true"
},
{
"code": null,
"e": 2626,
"s": 2620,
"text": "false"
},
{
"code": null,
"e": 2688,
"s": 2626,
"text": "Following is the example showing usage of these two elements."
},
{
"code": null,
"e": 3041,
"s": 2688,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\">\n<p> Select a Tutorial :\n <select>\n <option value=\"htm\">HTML Tutorial</option>\n <option value=\"xml\">XML Tutorial</option>\n <option value=\"wap\">WAP Tutorial</option>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 3113,
"s": 3041,
"text": "When you will load this program, it will show you the following screen:"
},
{
"code": null,
"e": 3196,
"s": 3113,
"text": "Once you highlight and enter on the options, it will display the following screen:"
},
{
"code": null,
"e": 3299,
"s": 3196,
"text": "You want to provide option to select multiple options, then set multiple attribute to true as follows:"
},
{
"code": null,
"e": 3668,
"s": 3299,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\">\n<p> Select a Tutorial :\n <select multiple=\"true\">\n <option value=\"htm\">HTML Tutorial</option>\n <option value=\"xml\">XML Tutorial</option>\n <option value=\"wap\">WAP Tutorial</option>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 3735,
"s": 3668,
"text": "This will give you a screen to select multiple options as follows:"
},
{
"code": null,
"e": 3853,
"s": 3735,
"text": "The <input/> element is used to create input fields and input fields are used to obtain alphanumeric data from users."
},
{
"code": null,
"e": 3900,
"s": 3853,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 3905,
"s": 3900,
"text": "true"
},
{
"code": null,
"e": 3911,
"s": 3905,
"text": "false"
},
{
"code": null,
"e": 4478,
"s": 3911,
"text": "A = uppercase alphabetic or punctuation characters\n a = lowercase alphabetic or punctuation characters\n N = numeric characters\n X = uppercase characters\n x = lowercase characters\n M = all characters\n m = all characters\n *f = Any number of characters. Replace the f with one of the letters above to specify what characters the user can enter\nnf = Replace the n with a number from 1 to 9 to specify the number of characters the user can enter. Replace the f with one of the letters above to specify what characters the user can enter"
},
{
"code": null,
"e": 4483,
"s": 4478,
"text": "text"
},
{
"code": null,
"e": 4492,
"s": 4483,
"text": "password"
},
{
"code": null,
"e": 4548,
"s": 4492,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 4886,
"s": 4548,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Input Fields\">\n<p> Enter Following Information:<br/> \n Name: <input name=\"name\" size=\"12\"/>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n Sex : <input name=\"sex\" size=\"12\"/> \n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 4960,
"s": 4886,
"text": "This will provide you the following screen to enter required information:"
},
{
"code": null,
"e": 5043,
"s": 4960,
"text": "The <fieldset/> element is used to group various input fields or selectable lists."
},
{
"code": null,
"e": 5090,
"s": 5043,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 5146,
"s": 5090,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 5497,
"s": 5146,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Grouped Fields\">\n<p> \n<fieldset title=\"Personal Info\">\n Name: <input name=\"name\" size=\"12\"/>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n Sex : <input name=\"sex\" size=\"12\"/> \n</fieldset>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 5614,
"s": 5497,
"text": "This will provide you the following screen to enter required information. This result may differ browser to browser."
},
{
"code": null,
"e": 5706,
"s": 5614,
"text": "The <optgroup/> element is used to group various options together inside a selectable list."
},
{
"code": null,
"e": 5753,
"s": 5706,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 5809,
"s": 5753,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 6365,
"s": 5809,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\"> \n<p>\n <select>\n <optgroup title=\"India\">\n <option value=\"delhi\">Delhi</option>\n <option value=\"mumbai\">Mumbai</option>\n <option value=\"hyderabad\">Hyderabad</option>\n </optgroup>\n <optgroup title=\"USA\">\n <option value=\"ohio\">Ohio</option>\n <option value=\"maryland\">Maryland</option>\n <option value=\"washington\">Washingtone</option>\n </optgroup>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 6441,
"s": 6365,
"text": "When a user loads above code, then it will give two options to be selected:"
},
{
"code": null,
"e": 6616,
"s": 6441,
"text": "When a user selects any of the options, then only it will give final options to be selected. So if user selects India, then it will show you following options to be selected:"
},
{
"code": null,
"e": 6623,
"s": 6616,
"text": " Print"
},
{
"code": null,
"e": 6634,
"s": 6623,
"text": " Add Notes"
}
] |
Basics of Python Generators. Understanding the basics of generators... | by Muriel Kosaka | Towards Data Science | Python Generator functions allow you to declare a function that behaves likes an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object. Examples of iterable objects that are used more commonly include lists, dictionaries, and strings.
In this article, we will learn to create and use generators in Python with the help of some examples.
Let’s first look at a simple class-based iterator to produce odd numbers:
class get_odds: def __init__(self, max): self.n=3 self.max=max def __iter__(self): return self def __next__(self): if self.n <= self.max: result = self.n self.n += 2 return result else: raise StopIterationnumbers = get_odds(10)print(next(numbers))print(next(numbers))print(next(numbers))# Output357
As you can see a sequence of odd numbers are generated. To generate this, we created a custom iterator inside the get_odds class. For an object to be an iterator it should implement the __iter__ method which will return the iterator object, the __next__ method will then return the next value in the sequence and possibly might raise the StopIteration exception when there are no values to be returned. As you can see, the process of creating iterators is lengthy, which is why we turn to generators. Again, python generators are a simple way of implementing iterators.
The main difference between a regular function and generator functions is that the state of generator functions are maintained through the use of the keyword yield and works much like using return, but it has some important differences. the difference is that yield saves the state of the function. The next time the function is called, execution continues from where it left off, with the same variable values it had before yielding, whereas the return statement terminates the function completely. Another difference is that generator functions don’t even run a function, it only creates and returns a generator object. Lastly, the code in generator functions only execute when next() is called on the generator object.
Let’s use the previous code and implement the same iterator except using a python generator.
def get_odds_generator(): n=1 n+=2 yield n n+=2 yield n n+=2 yield n numbers=get_odds_generator()print(next(numbers))print(next(numbers))print(next(numbers))# Output357
Above I had first created a generator function that has three yield statements and when we call this function is returns a generator which is an iterator object. We then called the next() method to retrieve elements from this object. The first print statement gives us the value of the first yield which is 3, the second print statement gives us the value of the second yield statement which is 5, and the last print statement gives us the value of the third yield statement which is 7. As you can see, the generator function is much simpler compared to our class-based iterator.
Now let’s try to implement a loop to make this python generator return odd numbers until a certain max number.
def get_odds_generator(max): n=1 while n<=max: yield n n+=2 numbers=get_odds_generator(3)print(next(numbers))print(next(numbers))print(next(numbers))
As you can see from the output, 1 and 3 were generated and after that a StopIteration exception has been raised. The loop condition (n<=max) is False since max is 3 and n is 5, therefore the StopIteration exception was raised.
When comparing this code with our get_odds class, you can see that in our generator we never explicitly defined the __iter__ method, the __next__ method, or raised a StopIteration exception — these are handled implicitly by generators, making programming much easier and simpler to understand!
Iterators and generators are typically used to handle a large stream of data theoretically even an infinite stream of data. These large streams of data cannot be stored in memory at once, to handle this we can use generators to handle only one item at a time. Next, we will build a generator to produce an infinite stream of Fibonacci numbers. Fibonacci numbers are a series of numbers where the next element is the sum of the previous two elements.
def fibonacci_generator(): n1=0 n2=1 while True: yield n1 n1, n2 = n2, n1 + n2sequence= fibonacci_generator()print(next(sequence))print(next(sequence))print(next(sequence))print(next(sequence))print(next(sequence))# Output01123
As you can see from the code above, in defining the fibonacci_generator function, I first created the first two elements of the fibonacci series, then used an infinite while loop and inside it yield the value of n1 and then update the values so that the next term will be the sum of the previous two terms with the line n1,n2=n2,n1+n2. Our print statements gives us the sequence of numbers in the fibonacci sequence. If we had used a for loop and a list to store this infinite series, we would have run out of memory, however with generators we can keep accessing these terms for as long as we want since we are dealing with one item at a time.
From this article, we have covered the basics of python generators. By the way, we can also create generators on the fly using generator expressions, which you can read more about in this article by Richmond Alake. Thank you for reading and all code is available on my Github :) | [
{
"code": null,
"e": 582,
"s": 171,
"text": "Python Generator functions allow you to declare a function that behaves likes an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object. Examples of iterable objects that are used more commonly include lists, dictionaries, and strings."
},
{
"code": null,
"e": 684,
"s": 582,
"text": "In this article, we will learn to create and use generators in Python with the help of some examples."
},
{
"code": null,
"e": 758,
"s": 684,
"text": "Let’s first look at a simple class-based iterator to produce odd numbers:"
},
{
"code": null,
"e": 1145,
"s": 758,
"text": "class get_odds: def __init__(self, max): self.n=3 self.max=max def __iter__(self): return self def __next__(self): if self.n <= self.max: result = self.n self.n += 2 return result else: raise StopIterationnumbers = get_odds(10)print(next(numbers))print(next(numbers))print(next(numbers))# Output357"
},
{
"code": null,
"e": 1715,
"s": 1145,
"text": "As you can see a sequence of odd numbers are generated. To generate this, we created a custom iterator inside the get_odds class. For an object to be an iterator it should implement the __iter__ method which will return the iterator object, the __next__ method will then return the next value in the sequence and possibly might raise the StopIteration exception when there are no values to be returned. As you can see, the process of creating iterators is lengthy, which is why we turn to generators. Again, python generators are a simple way of implementing iterators."
},
{
"code": null,
"e": 2437,
"s": 1715,
"text": "The main difference between a regular function and generator functions is that the state of generator functions are maintained through the use of the keyword yield and works much like using return, but it has some important differences. the difference is that yield saves the state of the function. The next time the function is called, execution continues from where it left off, with the same variable values it had before yielding, whereas the return statement terminates the function completely. Another difference is that generator functions don’t even run a function, it only creates and returns a generator object. Lastly, the code in generator functions only execute when next() is called on the generator object."
},
{
"code": null,
"e": 2530,
"s": 2437,
"text": "Let’s use the previous code and implement the same iterator except using a python generator."
},
{
"code": null,
"e": 2736,
"s": 2530,
"text": "def get_odds_generator(): n=1 n+=2 yield n n+=2 yield n n+=2 yield n numbers=get_odds_generator()print(next(numbers))print(next(numbers))print(next(numbers))# Output357"
},
{
"code": null,
"e": 3316,
"s": 2736,
"text": "Above I had first created a generator function that has three yield statements and when we call this function is returns a generator which is an iterator object. We then called the next() method to retrieve elements from this object. The first print statement gives us the value of the first yield which is 3, the second print statement gives us the value of the second yield statement which is 5, and the last print statement gives us the value of the third yield statement which is 7. As you can see, the generator function is much simpler compared to our class-based iterator."
},
{
"code": null,
"e": 3427,
"s": 3316,
"text": "Now let’s try to implement a loop to make this python generator return odd numbers until a certain max number."
},
{
"code": null,
"e": 3604,
"s": 3427,
"text": "def get_odds_generator(max): n=1 while n<=max: yield n n+=2 numbers=get_odds_generator(3)print(next(numbers))print(next(numbers))print(next(numbers))"
},
{
"code": null,
"e": 3831,
"s": 3604,
"text": "As you can see from the output, 1 and 3 were generated and after that a StopIteration exception has been raised. The loop condition (n<=max) is False since max is 3 and n is 5, therefore the StopIteration exception was raised."
},
{
"code": null,
"e": 4125,
"s": 3831,
"text": "When comparing this code with our get_odds class, you can see that in our generator we never explicitly defined the __iter__ method, the __next__ method, or raised a StopIteration exception — these are handled implicitly by generators, making programming much easier and simpler to understand!"
},
{
"code": null,
"e": 4575,
"s": 4125,
"text": "Iterators and generators are typically used to handle a large stream of data theoretically even an infinite stream of data. These large streams of data cannot be stored in memory at once, to handle this we can use generators to handle only one item at a time. Next, we will build a generator to produce an infinite stream of Fibonacci numbers. Fibonacci numbers are a series of numbers where the next element is the sum of the previous two elements."
},
{
"code": null,
"e": 4826,
"s": 4575,
"text": "def fibonacci_generator(): n1=0 n2=1 while True: yield n1 n1, n2 = n2, n1 + n2sequence= fibonacci_generator()print(next(sequence))print(next(sequence))print(next(sequence))print(next(sequence))print(next(sequence))# Output01123"
},
{
"code": null,
"e": 5471,
"s": 4826,
"text": "As you can see from the code above, in defining the fibonacci_generator function, I first created the first two elements of the fibonacci series, then used an infinite while loop and inside it yield the value of n1 and then update the values so that the next term will be the sum of the previous two terms with the line n1,n2=n2,n1+n2. Our print statements gives us the sequence of numbers in the fibonacci sequence. If we had used a for loop and a list to store this infinite series, we would have run out of memory, however with generators we can keep accessing these terms for as long as we want since we are dealing with one item at a time."
}
] |
Tcl - Environment Setup | If you are willing to set up your environment for Tcl, you need the following two software applications available on your computer −
Text Editor
Tcl Interpreter.
This will be used to type your program. Examples of a few text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.
The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension ".tcl".
Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it.
It is just a small program that enables you to type Tcl commands and have them executed line by line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes fully.
Let's have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose.
#!/usr/bin/tclsh
puts "Hello World!"
Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use.
Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions.
Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps
C:\Tcl> tclsh helloWorld.tcl
We can see the following output.
C:\Tcl> helloWorld
C:\Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs.
Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk.
$ yum install tcl tk
Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −
$ tclsh helloWorld.tcl
We can see the following output −
$ hello world
In case, it's not available in your OS, you can use the following command to download and install Tcl-Tk −
$ sudo apt-get install tcl tk
Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −
$ tclsh helloWorld.tcl
We can see the following output −
$ hello world
Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use.
Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions.
Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' and then execute the program using the following steps −
$ tclsh helloWorld.tcl
We can see the following output −
$ hello world
You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below.
Download the source files.
Download the source files.
Now, use the following commands to extract, compile, and build after switching to the downloaded folder.
Now, use the following commands to extract, compile, and build after switching to the downloaded folder.
$ tar zxf tcl8.6.1-src.tar.gz
$ cd tcl8.6.1
$ cd unix
$ ./configure —prefix=/opt —enable-gcc
$ make
$ sudo make install
Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2334,
"s": 2201,
"text": "If you are willing to set up your environment for Tcl, you need the following two software applications available on your computer −"
},
{
"code": null,
"e": 2346,
"s": 2334,
"text": "Text Editor"
},
{
"code": null,
"e": 2363,
"s": 2346,
"text": "Tcl Interpreter."
},
{
"code": null,
"e": 2514,
"s": 2363,
"text": "This will be used to type your program. Examples of a few text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi."
},
{
"code": null,
"e": 2698,
"s": 2514,
"text": "Name and version of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX."
},
{
"code": null,
"e": 2869,
"s": 2698,
"text": "The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension \".tcl\"."
},
{
"code": null,
"e": 3060,
"s": 2869,
"text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it."
},
{
"code": null,
"e": 3267,
"s": 3060,
"text": "It is just a small program that enables you to type Tcl commands and have them executed line by line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes fully."
},
{
"code": null,
"e": 3382,
"s": 3267,
"text": "Let's have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose."
},
{
"code": null,
"e": 3421,
"s": 3382,
"text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" "
},
{
"code": null,
"e": 3578,
"s": 3421,
"text": "Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use."
},
{
"code": null,
"e": 3687,
"s": 3578,
"text": "Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions."
},
{
"code": null,
"e": 3860,
"s": 3687,
"text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps"
},
{
"code": null,
"e": 3890,
"s": 3860,
"text": "C:\\Tcl> tclsh helloWorld.tcl\n"
},
{
"code": null,
"e": 3923,
"s": 3890,
"text": "We can see the following output."
},
{
"code": null,
"e": 3943,
"s": 3923,
"text": "C:\\Tcl> helloWorld\n"
},
{
"code": null,
"e": 4066,
"s": 3943,
"text": "C:\\Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs."
},
{
"code": null,
"e": 4272,
"s": 4066,
"text": "Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it's not available, you can use the following command to download and install Tcl-Tk."
},
{
"code": null,
"e": 4294,
"s": 4272,
"text": "$ yum install tcl tk\n"
},
{
"code": null,
"e": 4469,
"s": 4294,
"text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −"
},
{
"code": null,
"e": 4493,
"s": 4469,
"text": "$ tclsh helloWorld.tcl\n"
},
{
"code": null,
"e": 4527,
"s": 4493,
"text": "We can see the following output −"
},
{
"code": null,
"e": 4542,
"s": 4527,
"text": "$ hello world\n"
},
{
"code": null,
"e": 4649,
"s": 4542,
"text": "In case, it's not available in your OS, you can use the following command to download and install Tcl-Tk −"
},
{
"code": null,
"e": 4680,
"s": 4649,
"text": "$ sudo apt-get install tcl tk\n"
},
{
"code": null,
"e": 4855,
"s": 4680,
"text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' command and then execute the program using the following steps −"
},
{
"code": null,
"e": 4879,
"s": 4855,
"text": "$ tclsh helloWorld.tcl\n"
},
{
"code": null,
"e": 4913,
"s": 4879,
"text": "We can see the following output −"
},
{
"code": null,
"e": 4928,
"s": 4913,
"text": "$ hello world\n"
},
{
"code": null,
"e": 5084,
"s": 4928,
"text": "Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use."
},
{
"code": null,
"e": 5200,
"s": 5084,
"text": "Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions."
},
{
"code": null,
"e": 5367,
"s": 5200,
"text": "Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using 'cd' and then execute the program using the following steps −"
},
{
"code": null,
"e": 5390,
"s": 5367,
"text": "$ tclsh helloWorld.tcl"
},
{
"code": null,
"e": 5424,
"s": 5390,
"text": "We can see the following output −"
},
{
"code": null,
"e": 5439,
"s": 5424,
"text": "$ hello world\n"
},
{
"code": null,
"e": 5674,
"s": 5439,
"text": "You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below."
},
{
"code": null,
"e": 5701,
"s": 5674,
"text": "Download the source files."
},
{
"code": null,
"e": 5728,
"s": 5701,
"text": "Download the source files."
},
{
"code": null,
"e": 5833,
"s": 5728,
"text": "Now, use the following commands to extract, compile, and build after switching to the downloaded folder."
},
{
"code": null,
"e": 5938,
"s": 5833,
"text": "Now, use the following commands to extract, compile, and build after switching to the downloaded folder."
},
{
"code": null,
"e": 6059,
"s": 5938,
"text": "$ tar zxf tcl8.6.1-src.tar.gz\n$ cd tcl8.6.1\n$ cd unix\n$ ./configure —prefix=/opt —enable-gcc\n$ make\n$ sudo make install\n"
},
{
"code": null,
"e": 6165,
"s": 6059,
"text": "Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above."
},
{
"code": null,
"e": 6172,
"s": 6165,
"text": " Print"
},
{
"code": null,
"e": 6183,
"s": 6172,
"text": " Add Notes"
}
] |
Checking Internet Connectivity using Java - GeeksforGeeks | 30 May, 2018
Checking Internet connectivity using Java can be done using 2 methods:1) by using getRuntime() method of java Runtime class.2) by using methods of java URL and URLConnection classes.
#Java Runtime Class:This class is used to interact with java runtime environment (Java virtual machine) in which the application is running. It provides methods/functions to execute a process or a command, invoke garbage collector, get total and free memory in the JVM etc.
#getRuntime():This method of java runtime class returns the runtime object associated with the current java application.you can learn more about this class here
#Java URL Class:This class provides methods that returns various information like protocol, hostname, file Name, port Number etc of the URL.
#Java URLConnection class:It represents a link between URL and application and can be used to read and write data to the specified resource referred by the URL.
#openConnection():This method of java URLConnection class opens the connection to the specified URL.you can learn more about these classes here and here
NOTE: Provided method should be run on a local machine and not on an online compiler.METHOD 1:Output by this method will be 0 if the internet is connected and it will be 1 if the internet is not connected.
// Java program for Checking Internet connectivityimport java.util.*;import java.io.*; class checking_internet_connectivity { public static void main(String args[]) throws Exception { Process process = java.lang.Runtime.getRuntime().exec("ping www.geeksforgeeks.org"); int x = process.waitFor(); if (x == 0) { System.out.println("Connection Successful, " + "Output was " + x); } else { System.out.println("Internet Not Connected, " + "Output was " + x); } }}
OUTPUT:
METHOD 2:If Internet is not connected it will throw an exception and catch will execute printing respective message.
// Java program for checking Internet connectivityimport java.util.*;import java.io.*;import java.net.URL;import java.net.URLConnection; class checking_internet_connectivity { public static void main(String args[]) { try { URL url = new URL("https://www.geeksforgeeks.org/"); URLConnection connection = url.openConnection(); connection.connect(); System.out.println("Connection Successful"); } catch (Exception e) { System.out.println("Internet Not Connected"); } }}
OUTPUT:
Java-Networking
Java
Java
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
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
LinkedList in Java
Collections in Java | [
{
"code": null,
"e": 24265,
"s": 24237,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 24448,
"s": 24265,
"text": "Checking Internet connectivity using Java can be done using 2 methods:1) by using getRuntime() method of java Runtime class.2) by using methods of java URL and URLConnection classes."
},
{
"code": null,
"e": 24722,
"s": 24448,
"text": "#Java Runtime Class:This class is used to interact with java runtime environment (Java virtual machine) in which the application is running. It provides methods/functions to execute a process or a command, invoke garbage collector, get total and free memory in the JVM etc."
},
{
"code": null,
"e": 24883,
"s": 24722,
"text": "#getRuntime():This method of java runtime class returns the runtime object associated with the current java application.you can learn more about this class here"
},
{
"code": null,
"e": 25024,
"s": 24883,
"text": "#Java URL Class:This class provides methods that returns various information like protocol, hostname, file Name, port Number etc of the URL."
},
{
"code": null,
"e": 25185,
"s": 25024,
"text": "#Java URLConnection class:It represents a link between URL and application and can be used to read and write data to the specified resource referred by the URL."
},
{
"code": null,
"e": 25338,
"s": 25185,
"text": "#openConnection():This method of java URLConnection class opens the connection to the specified URL.you can learn more about these classes here and here"
},
{
"code": null,
"e": 25544,
"s": 25338,
"text": "NOTE: Provided method should be run on a local machine and not on an online compiler.METHOD 1:Output by this method will be 0 if the internet is connected and it will be 1 if the internet is not connected."
},
{
"code": "// Java program for Checking Internet connectivityimport java.util.*;import java.io.*; class checking_internet_connectivity { public static void main(String args[]) throws Exception { Process process = java.lang.Runtime.getRuntime().exec(\"ping www.geeksforgeeks.org\"); int x = process.waitFor(); if (x == 0) { System.out.println(\"Connection Successful, \" + \"Output was \" + x); } else { System.out.println(\"Internet Not Connected, \" + \"Output was \" + x); } }}",
"e": 26137,
"s": 25544,
"text": null
},
{
"code": null,
"e": 26145,
"s": 26137,
"text": "OUTPUT:"
},
{
"code": null,
"e": 26262,
"s": 26145,
"text": "METHOD 2:If Internet is not connected it will throw an exception and catch will execute printing respective message."
},
{
"code": "// Java program for checking Internet connectivityimport java.util.*;import java.io.*;import java.net.URL;import java.net.URLConnection; class checking_internet_connectivity { public static void main(String args[]) { try { URL url = new URL(\"https://www.geeksforgeeks.org/\"); URLConnection connection = url.openConnection(); connection.connect(); System.out.println(\"Connection Successful\"); } catch (Exception e) { System.out.println(\"Internet Not Connected\"); } }}",
"e": 26824,
"s": 26262,
"text": null
},
{
"code": null,
"e": 26832,
"s": 26824,
"text": "OUTPUT:"
},
{
"code": null,
"e": 26848,
"s": 26832,
"text": "Java-Networking"
},
{
"code": null,
"e": 26853,
"s": 26848,
"text": "Java"
},
{
"code": null,
"e": 26858,
"s": 26853,
"text": "Java"
},
{
"code": null,
"e": 26956,
"s": 26858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26965,
"s": 26956,
"text": "Comments"
},
{
"code": null,
"e": 26978,
"s": 26965,
"text": "Old Comments"
},
{
"code": null,
"e": 27029,
"s": 26978,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27059,
"s": 27029,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27090,
"s": 27059,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27109,
"s": 27090,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27141,
"s": 27109,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27159,
"s": 27141,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27179,
"s": 27159,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27211,
"s": 27179,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27230,
"s": 27211,
"text": "LinkedList in Java"
}
] |
What is the use of default methods in Java? | An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
It is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
If you need your class to follow a certain specification you need to implement the required interface and provide body for all the abstract methods in that interface.
If you do not provide the implementation of all the abstract methods of an interface (you, implement) a compile time error is generated.
Suppose we are using certain interface and implemented all the abstract methods in that interface and new methods were added later. Then, all the classes using this interface will not work unless you implement the newly added methods in each of them.
To resolve this issue from Java8 default methods are introduced.
A default method is also known as defender method or virtual extension method. You can define a default method using the default keyword as −
default void display() {
System.out.println("This is a default method");
}
Once write a default implementation to a particular method in an interface. there is no need to implement it in the classes that already using (implementing) this interface.
Following Java Example demonstrates the usage of the default method in Java.
Live Demo
interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}
This is the implementation of the demo method
This is a default method | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static."
},
{
"code": null,
"e": 1374,
"s": 1181,
"text": "It is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface."
},
{
"code": null,
"e": 1541,
"s": 1374,
"text": "If you need your class to follow a certain specification you need to implement the required interface and provide body for all the abstract methods in that interface."
},
{
"code": null,
"e": 1678,
"s": 1541,
"text": "If you do not provide the implementation of all the abstract methods of an interface (you, implement) a compile time error is generated."
},
{
"code": null,
"e": 1929,
"s": 1678,
"text": "Suppose we are using certain interface and implemented all the abstract methods in that interface and new methods were added later. Then, all the classes using this interface will not work unless you implement the newly added methods in each of them."
},
{
"code": null,
"e": 1994,
"s": 1929,
"text": "To resolve this issue from Java8 default methods are introduced."
},
{
"code": null,
"e": 2136,
"s": 1994,
"text": "A default method is also known as defender method or virtual extension method. You can define a default method using the default keyword as −"
},
{
"code": null,
"e": 2220,
"s": 2136,
"text": "default void display() {\n System.out.println(\"This is a default method\"); \n}"
},
{
"code": null,
"e": 2394,
"s": 2220,
"text": "Once write a default implementation to a particular method in an interface. there is no need to implement it in the classes that already using (implementing) this interface."
},
{
"code": null,
"e": 2471,
"s": 2394,
"text": "Following Java Example demonstrates the usage of the default method in Java."
},
{
"code": null,
"e": 2481,
"s": 2471,
"text": "Live Demo"
},
{
"code": null,
"e": 2961,
"s": 2481,
"text": "interface sampleInterface{ \n public void demo(); \n default void display() {\n System.out.println(\"This is a default method\"); \n }\n}\npublic class DefaultMethodExample implements sampleInterface{\n public void demo() {\n System.out.println(\"This is the implementation of the demo method\");\n } \n public static void main(String args[]) { \n DefaultMethodExample obj = new DefaultMethodExample();\n obj.demo();\n obj.display(); \n }\n}"
},
{
"code": null,
"e": 3032,
"s": 2961,
"text": "This is the implementation of the demo method\nThis is a default method"
}
] |
Minimum number of subsets with distinct elements - GeeksforGeeks | 01 Jul, 2021
You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible.Examples :
Input : arr[] = {1, 2, 3, 4}
Output :1
Explanation : A single subset can contains all
values and all values are distinct
Input : arr[] = {1, 2, 3, 3}
Output : 2
Explanation : We need to create two subsets
{1, 2, 3} and {3} [or {1, 3} and {2, 3}] such
that both subsets have distinct elements.
We basically need to find the most frequent element in the array. The result is equal to the frequency of the most frequent element.A simple solution is to run two nested loops to count frequency of every element and return the frequency of the most frequent element. Time complexity of this solution is O(n2).A better solution is to first sort the array and then start count number of repetitions of elements in an iterative manner as all repetition of any number lie beside the number itself. By this method you can find the maximum frequency or repetition by simply traversing the sorted array. This approach will cost O(nlogn) time complexity
C++
Java
Python3
C#
PHP
Javascript
// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.#include <bits/stdc++.h>using namespace std; // Function to count subsets such that all// subsets have distinct elements.int subset(int ar[], int n){ // Take input and initialize res = 0 int res = 0; // Sort the array sort(ar, ar + n); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = max(res, count); } return res;} // Driver codeint main(){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0;}
// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.import java.util.*;import java.lang.*; public class GfG{ // Function to count subsets such that all // subsets have distinct elements. public static int subset(int ar[], int n) { // Take input and initialize res = 0 int res = 0; // Sort the array Arrays.sort(ar); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.max(res, count); } return res; } // Driver function public static void main(String argc[]) { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = 7; System.out.println(subset(arr, n)); } } /* This code is contributed by Sagar Shukla */
# A sorting based solution to find the# minimum number of subsets of a set# such that every subset contains distinct# elements. # function to count subsets such that all# subsets have distinct elements.def subset(ar, n): # take input and initialize res = 0 res = 0 # sort the array ar.sort() # traverse the input array and # find maximum frequency for i in range(0, n) : count = 1 # for each number find its repetition / frequency for i in range(n - 1): if ar[i] == ar[i + 1]: count+=1 else: break # update res res = max(res, count) return res # Driver codear = [ 5, 6, 9, 3, 4, 3, 4 ]n = len(ar)print(subset(ar, n)) # This code is contributed by# Smitha Dinesh Semwal
// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.using System; public class GfG { // Function to count subsets such that all // subsets have distinct elements. public static int subset(int []ar, int n) { // Take input and initialize res = 0 int res = 0; // Sort the array Array.Sort(ar); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its // repetition / frequency for ( ; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.Max(res, count); } return res; } // Driver function public static void Main() { int []arr = { 5, 6, 9, 3, 4, 3, 4 }; int n = 7; Console.WriteLine(subset(arr, n)); } } /* This code is contributed by Vt_m */
<?php// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements. // Function to count subsets such that all// subsets have distinct elements.function subset($ar, $n){ // Take input and initialize res = 0 $res = 0; // Sort the array sort($ar); // Traverse the input array and // find maximum frequency for ($i = 0; $i < $n; $i++) { $count = 1; // For each number find its // repetition / frequency for (; $i < $n - 1; $i++) { if ($ar[$i] == $ar[$i + 1]) $count++; else break; } // Update res $res = max($res, $count); } return $res;} // Driver code$arr = array( 5, 6, 9, 3, 4, 3, 4 );$n = sizeof($arr);echo subset($arr, $n); // This code is contributed// by Sach_Code?>
<script> // JavaScript program sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct // Function to count subsets such that all // subsets have distinct elements. function subset(ar, n) { // Take input and initialize res = 0 let res = 0; // Sort the array ar.sort(); // Traverse the input array and // find maximum frequency for (let i = 0; i < n; i++) { let count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.max(res, count); } return res; } // Driver Code let arr = [ 5, 6, 9, 3, 4, 3, 4 ]; let n = 7; document.write(subset(arr, n)); // This code is contributed by chinmoy1997pal.</script>
Output:
2
An efficient solution is to use hashing. We count frequencies of all elements in a hash table. Finally we return the key with maximum value in hash table.
C++
Java
Python3
C#
Javascript
// A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.#include <bits/stdc++.h>using namespace std; // Function to count subsets such that all// subsets have distinct elements.int subset(int arr[], int n){ // Traverse the input array and // store frequencies of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Find the maximum value in map. int res = 0; for (auto x : mp) res = max(res, x.second); return res;} // Driver codeint main(){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0;}
import java.util.HashMap;import java.util.Map; // A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.class GFG{ // Function to count subsets such that all// subsets have distinct elements.static int subset(int arr[], int n){ // Traverse the input array and // store frequencies of elements HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1); // Find the maximum value in map. int res = 0; for (Map.Entry<Integer,Integer> entry : mp.entrySet()) res = Math.max(res, entry.getValue()); return res;} // Driver codepublic static void main(String[] args){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = arr.length; System.out.println( subset(arr, n)); }} // This code is contributed by Rajput-Ji
# A hashing based solution to find the# minimum number of subsets of a set such # that every subset contains distinct# elements. # Function to count subsets such that# all subsets have distinct elements.def subset(arr, n): # Traverse the input array and # store frequencies of elements mp = {i:0 for i in range(10)} for i in range(n): mp[arr[i]] += 1 # Find the maximum value in map. res = 0 for key, value in mp.items(): res = max(res, value) return res # Driver codeif __name__ == '__main__': arr = [5, 6, 9, 3, 4, 3, 4] n = len(arr) print(subset(arr, n)) # This code is contributed by# Surendra_Gangwar
// A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.using System;using System.Collections.Generic; class GFG{ // Function to count subsets such that all// subsets have distinct elements.static int subset(int []arr, int n){ // Traverse the input array and // store frequencies of elements Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Find the maximum value in map. int res = 0; foreach(KeyValuePair<int, int> entry in mp) res = Math.Max(res, entry.Value); return res;} // Driver codepublic static void Main(String[] args){ int []arr = { 5, 6, 9, 3, 4, 3, 4 }; int n = arr.Length; Console.WriteLine(subset(arr, n));}} // This code is contributed by Rajput-Ji
<script> // A hashing based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. // Function to count subsets such that all // subsets have distinct elements. function subset(arr, n) { // Traverse the input array and // store frequencies of elements var mp = {}; for (var i = 0; i < n; i++) { if (mp.hasOwnProperty(arr[i])) { var val = mp[arr[i]]; delete mp[arr[i]]; mp[arr[i]] = val + 1; } else { mp[arr[i]] = 1; } } // Find the maximum value in map. var res = 0; for (const [key, value] of Object.entries(mp)) { res = Math.max(res, value); } return res; } // Driver code var arr = [5, 6, 9, 3, 4, 3, 4]; var n = arr.length; document.write(subset(arr, n)); // This code is contributed by rdtank. </script>
Output :
2
Sach_Code
SURENDRA_GANGWAR
Rajput-Ji
chinmoy1997pal
rdtank
Arrays
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Python | Using 2D arrays/lists the right way
Linked List vs Array
Introduction to Arrays
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 25005,
"s": 24977,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 25186,
"s": 25005,
"text": "You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible.Examples : "
},
{
"code": null,
"e": 25481,
"s": 25186,
"text": "Input : arr[] = {1, 2, 3, 4}\nOutput :1\nExplanation : A single subset can contains all \nvalues and all values are distinct\n\nInput : arr[] = {1, 2, 3, 3}\nOutput : 2\nExplanation : We need to create two subsets\n{1, 2, 3} and {3} [or {1, 3} and {2, 3}] such\nthat both subsets have distinct elements."
},
{
"code": null,
"e": 26132,
"s": 25483,
"text": "We basically need to find the most frequent element in the array. The result is equal to the frequency of the most frequent element.A simple solution is to run two nested loops to count frequency of every element and return the frequency of the most frequent element. Time complexity of this solution is O(n2).A better solution is to first sort the array and then start count number of repetitions of elements in an iterative manner as all repetition of any number lie beside the number itself. By this method you can find the maximum frequency or repetition by simply traversing the sorted array. This approach will cost O(nlogn) time complexity "
},
{
"code": null,
"e": 26136,
"s": 26132,
"text": "C++"
},
{
"code": null,
"e": 26141,
"s": 26136,
"text": "Java"
},
{
"code": null,
"e": 26149,
"s": 26141,
"text": "Python3"
},
{
"code": null,
"e": 26152,
"s": 26149,
"text": "C#"
},
{
"code": null,
"e": 26156,
"s": 26152,
"text": "PHP"
},
{
"code": null,
"e": 26167,
"s": 26156,
"text": "Javascript"
},
{
"code": "// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.#include <bits/stdc++.h>using namespace std; // Function to count subsets such that all// subsets have distinct elements.int subset(int ar[], int n){ // Take input and initialize res = 0 int res = 0; // Sort the array sort(ar, ar + n); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = max(res, count); } return res;} // Driver codeint main(){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0;}",
"e": 27086,
"s": 26167,
"text": null
},
{
"code": "// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.import java.util.*;import java.lang.*; public class GfG{ // Function to count subsets such that all // subsets have distinct elements. public static int subset(int ar[], int n) { // Take input and initialize res = 0 int res = 0; // Sort the array Arrays.sort(ar); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.max(res, count); } return res; } // Driver function public static void main(String argc[]) { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = 7; System.out.println(subset(arr, n)); } } /* This code is contributed by Sagar Shukla */",
"e": 28224,
"s": 27086,
"text": null
},
{
"code": "# A sorting based solution to find the# minimum number of subsets of a set# such that every subset contains distinct# elements. # function to count subsets such that all# subsets have distinct elements.def subset(ar, n): # take input and initialize res = 0 res = 0 # sort the array ar.sort() # traverse the input array and # find maximum frequency for i in range(0, n) : count = 1 # for each number find its repetition / frequency for i in range(n - 1): if ar[i] == ar[i + 1]: count+=1 else: break # update res res = max(res, count) return res # Driver codear = [ 5, 6, 9, 3, 4, 3, 4 ]n = len(ar)print(subset(ar, n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 29027,
"s": 28224,
"text": null
},
{
"code": "// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.using System; public class GfG { // Function to count subsets such that all // subsets have distinct elements. public static int subset(int []ar, int n) { // Take input and initialize res = 0 int res = 0; // Sort the array Array.Sort(ar); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its // repetition / frequency for ( ; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.Max(res, count); } return res; } // Driver function public static void Main() { int []arr = { 5, 6, 9, 3, 4, 3, 4 }; int n = 7; Console.WriteLine(subset(arr, n)); } } /* This code is contributed by Vt_m */",
"e": 30142,
"s": 29027,
"text": null
},
{
"code": "<?php// A sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements. // Function to count subsets such that all// subsets have distinct elements.function subset($ar, $n){ // Take input and initialize res = 0 $res = 0; // Sort the array sort($ar); // Traverse the input array and // find maximum frequency for ($i = 0; $i < $n; $i++) { $count = 1; // For each number find its // repetition / frequency for (; $i < $n - 1; $i++) { if ($ar[$i] == $ar[$i + 1]) $count++; else break; } // Update res $res = max($res, $count); } return $res;} // Driver code$arr = array( 5, 6, 9, 3, 4, 3, 4 );$n = sizeof($arr);echo subset($arr, $n); // This code is contributed// by Sach_Code?>",
"e": 31026,
"s": 30142,
"text": null
},
{
"code": "<script> // JavaScript program sorting based solution to find the// minimum number of subsets of a set// such that every subset contains distinct // Function to count subsets such that all // subsets have distinct elements. function subset(ar, n) { // Take input and initialize res = 0 let res = 0; // Sort the array ar.sort(); // Traverse the input array and // find maximum frequency for (let i = 0; i < n; i++) { let count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = Math.max(res, count); } return res; } // Driver Code let arr = [ 5, 6, 9, 3, 4, 3, 4 ]; let n = 7; document.write(subset(arr, n)); // This code is contributed by chinmoy1997pal.</script>",
"e": 32061,
"s": 31026,
"text": null
},
{
"code": null,
"e": 32071,
"s": 32061,
"text": "Output: "
},
{
"code": null,
"e": 32073,
"s": 32071,
"text": "2"
},
{
"code": null,
"e": 32231,
"s": 32073,
"text": " An efficient solution is to use hashing. We count frequencies of all elements in a hash table. Finally we return the key with maximum value in hash table. "
},
{
"code": null,
"e": 32235,
"s": 32231,
"text": "C++"
},
{
"code": null,
"e": 32240,
"s": 32235,
"text": "Java"
},
{
"code": null,
"e": 32248,
"s": 32240,
"text": "Python3"
},
{
"code": null,
"e": 32251,
"s": 32248,
"text": "C#"
},
{
"code": null,
"e": 32262,
"s": 32251,
"text": "Javascript"
},
{
"code": "// A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.#include <bits/stdc++.h>using namespace std; // Function to count subsets such that all// subsets have distinct elements.int subset(int arr[], int n){ // Traverse the input array and // store frequencies of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Find the maximum value in map. int res = 0; for (auto x : mp) res = max(res, x.second); return res;} // Driver codeint main(){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0;}",
"e": 32979,
"s": 32262,
"text": null
},
{
"code": "import java.util.HashMap;import java.util.Map; // A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.class GFG{ // Function to count subsets such that all// subsets have distinct elements.static int subset(int arr[], int n){ // Traverse the input array and // store frequencies of elements HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1); // Find the maximum value in map. int res = 0; for (Map.Entry<Integer,Integer> entry : mp.entrySet()) res = Math.max(res, entry.getValue()); return res;} // Driver codepublic static void main(String[] args){ int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = arr.length; System.out.println( subset(arr, n)); }} // This code is contributed by Rajput-Ji",
"e": 33879,
"s": 32979,
"text": null
},
{
"code": "# A hashing based solution to find the# minimum number of subsets of a set such # that every subset contains distinct# elements. # Function to count subsets such that# all subsets have distinct elements.def subset(arr, n): # Traverse the input array and # store frequencies of elements mp = {i:0 for i in range(10)} for i in range(n): mp[arr[i]] += 1 # Find the maximum value in map. res = 0 for key, value in mp.items(): res = max(res, value) return res # Driver codeif __name__ == '__main__': arr = [5, 6, 9, 3, 4, 3, 4] n = len(arr) print(subset(arr, n)) # This code is contributed by# Surendra_Gangwar",
"e": 34543,
"s": 33879,
"text": null
},
{
"code": "// A hashing based solution to find the// minimum number of subsets of a set// such that every subset contains distinct// elements.using System;using System.Collections.Generic; class GFG{ // Function to count subsets such that all// subsets have distinct elements.static int subset(int []arr, int n){ // Traverse the input array and // store frequencies of elements Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Find the maximum value in map. int res = 0; foreach(KeyValuePair<int, int> entry in mp) res = Math.Max(res, entry.Value); return res;} // Driver codepublic static void Main(String[] args){ int []arr = { 5, 6, 9, 3, 4, 3, 4 }; int n = arr.Length; Console.WriteLine(subset(arr, n));}} // This code is contributed by Rajput-Ji",
"e": 35644,
"s": 34543,
"text": null
},
{
"code": "<script> // A hashing based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. // Function to count subsets such that all // subsets have distinct elements. function subset(arr, n) { // Traverse the input array and // store frequencies of elements var mp = {}; for (var i = 0; i < n; i++) { if (mp.hasOwnProperty(arr[i])) { var val = mp[arr[i]]; delete mp[arr[i]]; mp[arr[i]] = val + 1; } else { mp[arr[i]] = 1; } } // Find the maximum value in map. var res = 0; for (const [key, value] of Object.entries(mp)) { res = Math.max(res, value); } return res; } // Driver code var arr = [5, 6, 9, 3, 4, 3, 4]; var n = arr.length; document.write(subset(arr, n)); // This code is contributed by rdtank. </script>",
"e": 36641,
"s": 35644,
"text": null
},
{
"code": null,
"e": 36652,
"s": 36641,
"text": "Output : "
},
{
"code": null,
"e": 36654,
"s": 36652,
"text": "2"
},
{
"code": null,
"e": 36666,
"s": 36656,
"text": "Sach_Code"
},
{
"code": null,
"e": 36683,
"s": 36666,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36693,
"s": 36683,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36708,
"s": 36693,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 36715,
"s": 36708,
"text": "rdtank"
},
{
"code": null,
"e": 36722,
"s": 36715,
"text": "Arrays"
},
{
"code": null,
"e": 36727,
"s": 36722,
"text": "Hash"
},
{
"code": null,
"e": 36735,
"s": 36727,
"text": "Sorting"
},
{
"code": null,
"e": 36742,
"s": 36735,
"text": "Arrays"
},
{
"code": null,
"e": 36747,
"s": 36742,
"text": "Hash"
},
{
"code": null,
"e": 36755,
"s": 36747,
"text": "Sorting"
},
{
"code": null,
"e": 36853,
"s": 36755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36862,
"s": 36853,
"text": "Comments"
},
{
"code": null,
"e": 36875,
"s": 36862,
"text": "Old Comments"
},
{
"code": null,
"e": 36907,
"s": 36875,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36961,
"s": 36907,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 37006,
"s": 36961,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 37027,
"s": 37006,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37050,
"s": 37027,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37086,
"s": 37050,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 37117,
"s": 37086,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 37144,
"s": 37117,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 37178,
"s": 37144,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Max Circular Subarray Sum | Practice | GeeksforGeeks | Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum.
Example 1:
Input:
N = 7
arr[] = {8,-8,9,-9,10,-11,12}
Output:
22
Explanation:
Starting from the last element
of the array, i.e, 12, and
moving in a circular fashion, we
have max subarray as 12, 8, -8, 9,
-9, 10, which gives maximum sum
as 22.
Example 2:
Input:
N = 8
arr[] = {10,-3,-4,7,6,5,-4,-1}
Output:
23
Explanation: Sum of the circular
subarray with maximum sum is 23
Your Task:
The task is to complete the function circularSubarraySum() which returns a sum of the circular subarray with maximum sum.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
-106 <= Arr[i] <= 106
0
anil_maurya1 week ago
class Solution{
public:
// arr: input array
// num: size of array
//Function to find maximum circular subarray sum.
int circularSubarraySum(int arr[], int num){
int totsum=0,sum=0,mn=INT_MIN,mx=INT_MIN;
for(int i=0;i<num;i++)
totsum+=arr[i];
for(int i=0;i<num;i++){
sum+=arr[i];
mx=max(mx,sum);
if(sum<0) sum=0;
}
for(int i=0;i<num;i++)
arr[i]=-arr[i];
sum=0;
for(int i=0;i<num;i++){
sum+=arr[i];
mn=max(mn,sum);
if(sum<0) sum=0;
}
int cir=totsum+mn;
if(cir==0)
return mx;
return max(cir,mx);
}
};
0
shivi13verma1 week ago
141/142 Test Case Passed 1 failed because of Tle :
#can someone help me to make this code more opt.
def circularSubarraySum(arr,n): ##Your code here max_sum=kadane(arr,n) array_sum=0 if max_sum<0: return max_sum for i in range(n): array_sum+=arr[i] arr[i]=-arr[i] return max(array_sum+kadane(arr,n),max_sum) def kadane(arr,n): res=arr[0] ending=arr[0] for i in range(1,n): ending=max(ending+arr[i],arr[i]) res=max(ending,res) return res
0
shubham211019971 week ago
int kardane(int arr[],int n){
int maxEnd=arr[0],maxi=arr[0];
for(int i=1;i<n;i++){
maxEnd=max(maxEnd+arr[i],arr[i]);
maxi=max(maxi,maxEnd);
}
return maxi;
}
int circularSubarraySum(int arr[], int n){
//kadanes Algorithm
int maxi=kardane(arr,n);
if(maxi<0) return maxi;
//circular Array
int sum=0;
for(int i=0;i<n;i++){
sum+=arr[i];
arr[i]=-arr[i];
}
int maxi2=kardane(arr,n)+sum;
// cout<<maxi<<" "<<maxi2<<" "<<sum<<endl;
return max(maxi,maxi2);
}
0
tantade20023 weeks ago
Java solutiojn
// Your code here int res=arr[0]; int res2=arr[0]; int sum=arr[0]; if(arr.length==1){ return arr[0]; }else{ int curr_min=arr[0]; int curr_max=arr[0]; for(int j=1;j<arr.length;j++) { curr_max=Math.max(curr_max+arr[j], arr[j]); res2=Math.max(res2, curr_max); } //System.out.println(res2); for(int j=1;j<arr.length;j++) { curr_min=Math.min(curr_min+arr[j], arr[j]); res=Math.min(res, curr_min); sum=sum+arr[j]; } //System.out.println(sum); //System.out.println(res); } //System.out.println(sum); //System.out.println(res); //System.out.println(sum-res); if(sum-res==0){ return res2; } return(Math.max(res2,(sum-res))); }
0
swapniltayal4223 weeks ago
public: // arr: input array // num: size of array //Function to find maximum circular subarray sum. int kadane(int A[], int n){ int currsum = -10000; int bestsum = -10000; for (int i=0; i<n; i++){ currsum = max(currsum+A[i], A[i]); bestsum = max(currsum, bestsum); }return bestsum; } int circularSubarraySum(int arr[], int num){ // your code here if (num == 1){ return arr[0]; }if (num == 2){ int num = arr[0] + arr[1]; int num2 = max(arr[0], arr[1]); return max(num, num2); } int wrapsum = -10000; int nowrapsum = -10000; nowrapsum = kadane(arr, num); int total = 0; for (int i=0; i<num; i++){ total += arr[i]; arr[i] = -arr[i]; } wrapsum = total + kadane(arr, num); return max(wrapsum, nowrapsum); }
0
harshitjinodiya1 month ago
Java Solution
class Solution{
static int circularSubarraySum(int a[], int n) { int max_normal= normalMaxSum(a, n); if(max_normal<0) return max_normal; int a_sum=0; for(int i=0;i<n;i++) { a_sum+=a[i]; a[i]=-a[i]; } int max_circular = a_sum+normalMaxSum(a, n); return Math.max(max_normal, max_circular); } static int normalMaxSum(int a[], int n) { int res = a[0], maxEnd=a[0]; for(int i=1;i<n;i++) { maxEnd = Math.max(a[i], maxEnd+a[i]); res=Math.max(res, maxEnd); } return res; }}
0
parthgupta18032 months ago
int normalMaxSum(int arr[], int n){int res = arr[0];
int maxEnding = arr[0];
for(int i = 1; i < n; i++){ maxEnding = max(maxEnding + arr[i], arr[i]);
res = max(maxEnding, res);}return res;} int circularSubarraySum(int arr[], int n) { int max_normal = normalMaxSum(arr, n);
if(max_normal < 0) return max_normal;
int arr_sum = 0;
for(int i = 0; i < n; i++){ arr_sum += arr[i];
arr[i] = -arr[i];}
int max_circular = arr_sum + normalMaxSum(arr, n);
return max(max_circular, max_normal);}
0
hamidnourashraf2 months ago
import math
def max_sub_arary(arr, n):
max_sum = -math.inf
_sum = 0
for i in range(0,n):
_sum += arr[i]
max_sum = max(max_sum, _sum)
if _sum < 0:
_sum = 0
return max_sum
def min_sub_array(arr, n):
min_sum = math.inf
_sum = 0
for i in range(0,n):
_sum += arr[i]
min_sum = min(min_sum, _sum)
if _sum > 0:
_sum = 0
return min_sum
def circularSubarraySum(arr,n):
arr_sum = sum(arr)
max_sub_arry_sum = max_sub_arary(arr, n)
min_sub_arry_sum = min_sub_array(arr, n)
if arr_sum - min_sub_arry_sum == 0: --> all negative in arr
return max_sub_arry_sum
return max(max_sub_arry_sum, arr_sum-min_sub_arry_sum)
+1
kartikeyashokgautam2 months ago
JAVA Solution:-
static int circularSubarraySum(int a[], int n) { int total = 0, maxSum = a[0], curMax = 0, minSum = a[0], curMin = 0; for (int x : a) { curMax = Math.max(curMax + x, x); maxSum = Math.max(maxSum, curMax); curMin = Math.min(curMin + x, x); minSum = Math.min(minSum, curMin); total += x; } return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; }
0
ldeepak112 months ago
/**
* Standard Kadane's Algorithm
*/
int maxSumOfNormalSubArray(int arr[], int n) {
int currSum=arr[0];
int currMax=arr[0];
for (int i=1; i<n; i++) {
currSum=max(currSum+arr[i], arr[i]);
currMax=max(currMax, currSum);
}
return currMax;
}
/**
* maxSumOfCircularSubarray=TotalSum - minSumOfNormalSubarray
* maxSumOfCircularSubarray=TotalSum + maxSumOfInvertedSubarray
*/
int maxSumOfCircularSubarray(int arr[], int n) {
/**
* Computing total sum of the array, also inverting the array values.
*/
int totalSum=0;
for (int i=0; i<n; i++) {
totalSum+=arr[i];
arr[i]=-arr[i];
}
return totalSum+maxSumOfNormalSubArray(arr, n);
}
// arr: input array
// num: size of array
//Function to find maximum circular subarray sum.
int circularSubarraySum(int arr[], int num){
// your code here
/**
* Two Cases:
* 1. When the maximum subarray is not circular
* 2. When the maximum subarray is circular.
* Answer would be max of case 1 and case 2
*/
int a=maxSumOfNormalSubArray(arr, num);
int b=maxSumOfCircularSubarray(arr, num);
/**
* Corner case: When all elements are -ve.
* maxSumOfNormalSubArray = max(arr), and it will be -ve
* maxSumOfCircularSubarray = TotalSum - minSumOfNormalSubarray
* minSumOfNormalSubarray = sum(arr), adding all the -ve elements would give us the minimum sum
*
* => maxSumOfCircularSubarray = TotalSum - sum(arr)
* Since TotalSum == sum(arr)
* => maxSumOfCircularSubarray = 0
* Which means sum of an empty subarray. This is wrong as empty subarrays are not allowed.
*
*/
if (a<0) {
return a;
}
else {
return max(a, b);
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 363,
"s": 238,
"text": "Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum."
},
{
"code": null,
"e": 375,
"s": 363,
"text": "\nExample 1:"
},
{
"code": null,
"e": 611,
"s": 375,
"text": "Input:\nN = 7\narr[] = {8,-8,9,-9,10,-11,12}\nOutput:\n22\nExplanation:\nStarting from the last element\nof the array, i.e, 12, and \nmoving in a circular fashion, we \nhave max subarray as 12, 8, -8, 9, \n-9, 10, which gives maximum sum \nas 22."
},
{
"code": null,
"e": 622,
"s": 611,
"text": "Example 2:"
},
{
"code": null,
"e": 744,
"s": 622,
"text": "Input:\nN = 8\narr[] = {10,-3,-4,7,6,5,-4,-1}\nOutput:\n23\nExplanation: Sum of the circular \nsubarray with maximum sum is 23\n"
},
{
"code": null,
"e": 878,
"s": 744,
"text": "\nYour Task:\nThe task is to complete the function circularSubarraySum() which returns a sum of the circular subarray with maximum sum."
},
{
"code": null,
"e": 943,
"s": 878,
"text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 993,
"s": 943,
"text": "\nConstraints:\n1 <= N <= 106\n-106 <= Arr[i] <= 106"
},
{
"code": null,
"e": 995,
"s": 993,
"text": "0"
},
{
"code": null,
"e": 1017,
"s": 995,
"text": "anil_maurya1 week ago"
},
{
"code": null,
"e": 1731,
"s": 1017,
"text": "class Solution{\n public:\n // arr: input array\n // num: size of array\n //Function to find maximum circular subarray sum.\n int circularSubarraySum(int arr[], int num){\n int totsum=0,sum=0,mn=INT_MIN,mx=INT_MIN;\n for(int i=0;i<num;i++)\n totsum+=arr[i];\n for(int i=0;i<num;i++){\n sum+=arr[i];\n mx=max(mx,sum);\n if(sum<0) sum=0;\n }\n for(int i=0;i<num;i++)\n arr[i]=-arr[i];\n sum=0;\n for(int i=0;i<num;i++){\n sum+=arr[i];\n mn=max(mn,sum);\n if(sum<0) sum=0;\n }\n int cir=totsum+mn;\n if(cir==0)\n return mx;\n return max(cir,mx);\n }\n};"
},
{
"code": null,
"e": 1733,
"s": 1731,
"text": "0"
},
{
"code": null,
"e": 1756,
"s": 1733,
"text": "shivi13verma1 week ago"
},
{
"code": null,
"e": 1807,
"s": 1756,
"text": "141/142 Test Case Passed 1 failed because of Tle :"
},
{
"code": null,
"e": 1856,
"s": 1807,
"text": "#can someone help me to make this code more opt."
},
{
"code": null,
"e": 2272,
"s": 1856,
"text": "def circularSubarraySum(arr,n): ##Your code here max_sum=kadane(arr,n) array_sum=0 if max_sum<0: return max_sum for i in range(n): array_sum+=arr[i] arr[i]=-arr[i] return max(array_sum+kadane(arr,n),max_sum) def kadane(arr,n): res=arr[0] ending=arr[0] for i in range(1,n): ending=max(ending+arr[i],arr[i]) res=max(ending,res) return res"
},
{
"code": null,
"e": 2274,
"s": 2272,
"text": "0"
},
{
"code": null,
"e": 2300,
"s": 2274,
"text": "shubham211019971 week ago"
},
{
"code": null,
"e": 2941,
"s": 2300,
"text": "int kardane(int arr[],int n){\n int maxEnd=arr[0],maxi=arr[0];\n for(int i=1;i<n;i++){\n maxEnd=max(maxEnd+arr[i],arr[i]);\n maxi=max(maxi,maxEnd);\n }\n return maxi;\n } \n int circularSubarraySum(int arr[], int n){\n \n //kadanes Algorithm\n int maxi=kardane(arr,n);\n \n if(maxi<0) return maxi;\n \n //circular Array\n int sum=0;\n for(int i=0;i<n;i++){\n sum+=arr[i];\n arr[i]=-arr[i];\n }\n int maxi2=kardane(arr,n)+sum;\n // cout<<maxi<<\" \"<<maxi2<<\" \"<<sum<<endl; \n return max(maxi,maxi2);\n \n \n }"
},
{
"code": null,
"e": 2943,
"s": 2941,
"text": "0"
},
{
"code": null,
"e": 2966,
"s": 2943,
"text": "tantade20023 weeks ago"
},
{
"code": null,
"e": 2981,
"s": 2966,
"text": "Java solutiojn"
},
{
"code": null,
"e": 3710,
"s": 2981,
"text": " // Your code here int res=arr[0]; int res2=arr[0]; int sum=arr[0]; if(arr.length==1){ return arr[0]; }else{ int curr_min=arr[0]; int curr_max=arr[0]; for(int j=1;j<arr.length;j++) { curr_max=Math.max(curr_max+arr[j], arr[j]); res2=Math.max(res2, curr_max); } //System.out.println(res2); for(int j=1;j<arr.length;j++) { curr_min=Math.min(curr_min+arr[j], arr[j]); res=Math.min(res, curr_min); sum=sum+arr[j]; } //System.out.println(sum); //System.out.println(res); } //System.out.println(sum); //System.out.println(res); //System.out.println(sum-res); if(sum-res==0){ return res2; } return(Math.max(res2,(sum-res))); } "
},
{
"code": null,
"e": 3712,
"s": 3710,
"text": "0"
},
{
"code": null,
"e": 3739,
"s": 3712,
"text": "swapniltayal4223 weeks ago"
},
{
"code": null,
"e": 4690,
"s": 3739,
"text": " public: // arr: input array // num: size of array //Function to find maximum circular subarray sum. int kadane(int A[], int n){ int currsum = -10000; int bestsum = -10000; for (int i=0; i<n; i++){ currsum = max(currsum+A[i], A[i]); bestsum = max(currsum, bestsum); }return bestsum; } int circularSubarraySum(int arr[], int num){ // your code here if (num == 1){ return arr[0]; }if (num == 2){ int num = arr[0] + arr[1]; int num2 = max(arr[0], arr[1]); return max(num, num2); } int wrapsum = -10000; int nowrapsum = -10000; nowrapsum = kadane(arr, num); int total = 0; for (int i=0; i<num; i++){ total += arr[i]; arr[i] = -arr[i]; } wrapsum = total + kadane(arr, num); return max(wrapsum, nowrapsum); }"
},
{
"code": null,
"e": 4692,
"s": 4690,
"text": "0"
},
{
"code": null,
"e": 4719,
"s": 4692,
"text": "harshitjinodiya1 month ago"
},
{
"code": null,
"e": 4733,
"s": 4719,
"text": "Java Solution"
},
{
"code": null,
"e": 4749,
"s": 4733,
"text": "class Solution{"
},
{
"code": null,
"e": 5337,
"s": 4749,
"text": " static int circularSubarraySum(int a[], int n) { int max_normal= normalMaxSum(a, n); if(max_normal<0) return max_normal; int a_sum=0; for(int i=0;i<n;i++) { a_sum+=a[i]; a[i]=-a[i]; } int max_circular = a_sum+normalMaxSum(a, n); return Math.max(max_normal, max_circular); } static int normalMaxSum(int a[], int n) { int res = a[0], maxEnd=a[0]; for(int i=1;i<n;i++) { maxEnd = Math.max(a[i], maxEnd+a[i]); res=Math.max(res, maxEnd); } return res; }}"
},
{
"code": null,
"e": 5339,
"s": 5337,
"text": "0"
},
{
"code": null,
"e": 5366,
"s": 5339,
"text": "parthgupta18032 months ago"
},
{
"code": null,
"e": 5421,
"s": 5366,
"text": " int normalMaxSum(int arr[], int n){int res = arr[0];"
},
{
"code": null,
"e": 5445,
"s": 5421,
"text": "int maxEnding = arr[0];"
},
{
"code": null,
"e": 5518,
"s": 5445,
"text": "for(int i = 1; i < n; i++){ maxEnding = max(maxEnding + arr[i], arr[i]);"
},
{
"code": null,
"e": 5658,
"s": 5518,
"text": " res = max(maxEnding, res);}return res;} int circularSubarraySum(int arr[], int n) { int max_normal = normalMaxSum(arr, n);"
},
{
"code": null,
"e": 5696,
"s": 5658,
"text": "if(max_normal < 0) return max_normal;"
},
{
"code": null,
"e": 5713,
"s": 5696,
"text": "int arr_sum = 0;"
},
{
"code": null,
"e": 5760,
"s": 5713,
"text": "for(int i = 0; i < n; i++){ arr_sum += arr[i];"
},
{
"code": null,
"e": 5780,
"s": 5760,
"text": " arr[i] = -arr[i];}"
},
{
"code": null,
"e": 5831,
"s": 5780,
"text": "int max_circular = arr_sum + normalMaxSum(arr, n);"
},
{
"code": null,
"e": 5870,
"s": 5831,
"text": "return max(max_circular, max_normal);}"
},
{
"code": null,
"e": 5874,
"s": 5872,
"text": "0"
},
{
"code": null,
"e": 5902,
"s": 5874,
"text": "hamidnourashraf2 months ago"
},
{
"code": null,
"e": 6721,
"s": 5902,
"text": "import math\ndef max_sub_arary(arr, n):\n max_sum = -math.inf\n _sum = 0\n for i in range(0,n):\n _sum += arr[i]\n max_sum = max(max_sum, _sum)\n if _sum < 0:\n _sum = 0\n return max_sum\n \ndef min_sub_array(arr, n):\n min_sum = math.inf\n _sum = 0\n for i in range(0,n):\n _sum += arr[i]\n min_sum = min(min_sum, _sum)\n if _sum > 0:\n _sum = 0\n return min_sum \n \ndef circularSubarraySum(arr,n):\n arr_sum = sum(arr)\n max_sub_arry_sum = max_sub_arary(arr, n)\n min_sub_arry_sum = min_sub_array(arr, n)\n \n if arr_sum - min_sub_arry_sum == 0: --> all negative in arr\n return max_sub_arry_sum\n return max(max_sub_arry_sum, arr_sum-min_sub_arry_sum)"
},
{
"code": null,
"e": 6724,
"s": 6721,
"text": "+1"
},
{
"code": null,
"e": 6756,
"s": 6724,
"text": "kartikeyashokgautam2 months ago"
},
{
"code": null,
"e": 6772,
"s": 6756,
"text": "JAVA Solution:-"
},
{
"code": null,
"e": 7215,
"s": 6772,
"text": " static int circularSubarraySum(int a[], int n) { int total = 0, maxSum = a[0], curMax = 0, minSum = a[0], curMin = 0; for (int x : a) { curMax = Math.max(curMax + x, x); maxSum = Math.max(maxSum, curMax); curMin = Math.min(curMin + x, x); minSum = Math.min(minSum, curMin); total += x; } return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; }"
},
{
"code": null,
"e": 7219,
"s": 7217,
"text": "0"
},
{
"code": null,
"e": 7241,
"s": 7219,
"text": "ldeepak112 months ago"
},
{
"code": null,
"e": 9269,
"s": 7241,
"text": "/**\n * Standard Kadane's Algorithm\n */\n int maxSumOfNormalSubArray(int arr[], int n) {\n int currSum=arr[0];\n int currMax=arr[0];\n for (int i=1; i<n; i++) {\n currSum=max(currSum+arr[i], arr[i]);\n currMax=max(currMax, currSum);\n }\n return currMax;\n }\n \n /**\n * maxSumOfCircularSubarray=TotalSum - minSumOfNormalSubarray\n * maxSumOfCircularSubarray=TotalSum + maxSumOfInvertedSubarray\n */\n int maxSumOfCircularSubarray(int arr[], int n) {\n /**\n * Computing total sum of the array, also inverting the array values.\n */\n int totalSum=0;\n for (int i=0; i<n; i++) {\n totalSum+=arr[i];\n arr[i]=-arr[i];\n }\n \n return totalSum+maxSumOfNormalSubArray(arr, n);\n }\n \n // arr: input array\n // num: size of array\n //Function to find maximum circular subarray sum.\n int circularSubarraySum(int arr[], int num){\n // your code here\n \n /**\n * Two Cases: \n * 1. When the maximum subarray is not circular\n * 2. When the maximum subarray is circular.\n * Answer would be max of case 1 and case 2\n */\n int a=maxSumOfNormalSubArray(arr, num);\n int b=maxSumOfCircularSubarray(arr, num);\n \n /**\n * Corner case: When all elements are -ve.\n * maxSumOfNormalSubArray = max(arr), and it will be -ve\n * maxSumOfCircularSubarray = TotalSum - minSumOfNormalSubarray\n * minSumOfNormalSubarray = sum(arr), adding all the -ve elements would give us the minimum sum\n * \n * => maxSumOfCircularSubarray = TotalSum - sum(arr)\n * Since TotalSum == sum(arr) \n * => maxSumOfCircularSubarray = 0\n * Which means sum of an empty subarray. This is wrong as empty subarrays are not allowed.\n * \n */\n if (a<0) {\n return a; \n }\n else {\n return max(a, b); \n }\n }"
},
{
"code": null,
"e": 9415,
"s": 9269,
"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": 9451,
"s": 9415,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9461,
"s": 9451,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9471,
"s": 9461,
"text": "\nContest\n"
},
{
"code": null,
"e": 9534,
"s": 9471,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9682,
"s": 9534,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9890,
"s": 9682,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9996,
"s": 9890,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Maximum of all subarrays of size k | Practice | GeeksforGeeks | Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K.
Example 1:
Input:
N = 9, K = 3
arr[] = 1 2 3 1 4 5 2 3 6
Output:
3 3 4 5 5 5 6
Explanation:
1st contiguous subarray = {1 2 3} Max = 3
2nd contiguous subarray = {2 3 1} Max = 3
3rd contiguous subarray = {3 1 4} Max = 4
4th contiguous subarray = {1 4 5} Max = 5
5th contiguous subarray = {4 5 2} Max = 5
6th contiguous subarray = {5 2 3} Max = 5
7th contiguous subarray = {2 3 6} Max = 6
Example 2:
Input:
N = 10, K = 4
arr[] = 8 5 10 7 9 4 15 12 90 13
Output:
10 10 10 15 15 90 90
Explanation:
1st contiguous subarray = {8 5 10 7}, Max = 10
2nd contiguous subarray = {5 10 7 9}, Max = 10
3rd contiguous subarray = {10 7 9 4}, Max = 10
4th contiguous subarray = {7 9 4 15}, Max = 15
5th contiguous subarray = {9 4 15 12},
Max = 15
6th contiguous subarray = {4 15 12 90},
Max = 90
7th contiguous subarray = {15 12 90 13},
Max = 90
Your Task:
You dont need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(k)
Constraints:
1 ≤ N ≤ 107
1 ≤ K ≤ N
0 ≤ arr[i] ≤ 107
0
amanahirwar1512 days ago
C++ EASY SOLUTION USING DEQUE
vector <int> max_of_subarrays(int *arr, int n, int k) { vector<int> ans; deque<int> dq(k); int i; for(i=0; i<k; ++i){ while((!dq.empty()) && arr[i]>=arr[dq.back()]){ dq.pop_back(); } dq.push_back(i); } ans.push_back(arr[dq.front()]); for(i=k; i<n; ++i){ if(dq.front()==i-k){ dq.pop_front(); } while((!dq.empty()) && arr[i]>=arr[dq.back()]){ dq.pop_back(); } dq.push_back(i); ans.push_back(arr[dq.front()]); } return ans; }
+1
bhaskarmaheshwari83 days ago
vector<int> ans; int i=0,j=0; int max1=INT_MIN; while(j<n) { if(j-i+1<=k) { max1=max(max1,arr[j]); if(j-i+1==k) { ans.push_back(max1); } j++; } else { if(arr[i]==max1) { max1=INT_MIN; for(int l=i+1;l<=i+k-1;l++) { max1=max(max1,arr[l]); } } i++; } } return ans;
0
kknamish3 days ago
class Solution:
def max_of_subarrays(self,arr,n,k):
i,j=0,0
mx=max(arr[:k])
ans=[mx]
for i in range(k,n):
if mx!=arr[i-k]:
mx=max(mx,arr[i])
else:
mx=max(arr[i-k+1:i+1])
ans.append(mx)
return ans
+1
harendraseervi1234567895 days ago
Easy C++ solution
vector <int> max_of_subarrays(int *arr, int n, int k)
{
// your code here
vector<int>ans;
int maxi=INT_MIN;
for(int i=0;i<k;i++){
if(arr[i]>maxi) maxi=arr[i];
}
ans.push_back(maxi);
for(int i=k;i<n;i++){
if(arr[i]>maxi){
ans.push_back(arr[i]);
maxi=arr[i];
}
else{
if(arr[i-k]!=maxi){
ans.push_back(maxi);
}
else{
maxi=INT_MIN;
for(int j=i-k+1;j<=i;j++){
maxi=max(arr[j],maxi);
}
ans.push_back(maxi);
}
}
}
return ans;
}
0
tarunkanade5 days ago
4.6/6.8
static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)
{
// Your code here
ArrayDeque<Integer> q = new ArrayDeque<>();
ArrayList<Integer> maxSub = new ArrayList<>();
for(int i=0; i<k; i++){
while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){
q.pollLast();
}
q.offerLast(i);
}
for(int i=k; i<n; i++){
maxSub.add(arr[q.peekFirst()]);
while(!q.isEmpty() && q.peekFirst() <= i-k){
q.pollFirst();
}
while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){
q.pollLast();
}
q.offerLast(i);
}
maxSub.add(arr[q.peekFirst()]);
return maxSub;
}
+1
soumik20001 week ago
Java Max Heap Simple solution
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder()); ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i<k; i++) { pq.add(arr[i]); } list.add(pq.peek()); for(int i = k; i<n; i++) { pq.remove(arr[i-k]); pq.add(arr[i]); list.add(pq.peek()); } return list;
0
himanshukug19cs2 weeks ago
java
int[] maxf= new int[n]; Stack<Integer> st = new Stack<>(); for(int i=n-1;i>=0;i--){ while(!st.empty()&&arr[st.peek()]<=arr[i]){ st.pop(); } if(st.empty()) maxf[i]=n; else maxf[i]=st.peek(); st.push(i); } ArrayList <Integer> al = new ArrayList<>(); for(int i=0;i<=n-k;i++){ int j=i; while(maxf[j]<i+k){ j=maxf[j]; } if(j==i) al.add(arr[i]); else al.add(arr[j]); } return al; }
-3
1941012837shivamkumarsharma3 weeks ago
JAVA Simple Code
// by 1941012837_Shivam Kumar Sharma_ITER(SOA)
class Solution
{
//Function to find maximum of each subarray of size k.
static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)
{
int len=n-k;
int max=0;
ArrayList<Integer>list= new ArrayList<>();
for(int i=0;i<=len;i++){
max=arr[i];
for(int j=1;j<k;j++){
max=Math.max(arr[i+j],max);
}
list.add(max);
} return (list);
}
}
+1
anupb4 weeks ago
Python Solution
class Solution:
#Function to find maximum of each subarray of size k.
def max_of_subarrays(self,arr,n,k):
result = list()
max_num = 0
first_pointer = 0
if k > n:
return max(arr)
sub_array = arr[0:k]
max_num = max(sub_array)
result.append(max_num)
for i in range(k,n):
# for optimization
if max_num > arr[first_pointer]:
sub_array.pop(0)
sub_array.append(arr[i])
max_num = max(max_num, arr[i])
result.append(max_num)
first_pointer += 1
else:
sub_array.pop(0)
sub_array.append(arr[i])
max_num = max(sub_array)
result.append(max_num)
first_pointer += 1
return result
+1
inukurthibhargavi2384 weeks ago
def max_of_subarrays(self,arr,n,k):
ans=[]
i=k
j=0
ans.append(max(arr[:k]))
while i<n:
if arr[j]==ans[-1]:
ans.append(max(arr[j+1:i+1]))
elif arr[i]>ans[-1]:
ans.append(arr[i])
else:
ans.append(ans[-1])
j+=1
i+=1
return ans
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 354,
"s": 238,
"text": "Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K."
},
{
"code": null,
"e": 365,
"s": 354,
"text": "Example 1:"
},
{
"code": null,
"e": 743,
"s": 365,
"text": "Input:\nN = 9, K = 3\narr[] = 1 2 3 1 4 5 2 3 6\nOutput: \n3 3 4 5 5 5 6 \nExplanation: \n1st contiguous subarray = {1 2 3} Max = 3\n2nd contiguous subarray = {2 3 1} Max = 3\n3rd contiguous subarray = {3 1 4} Max = 4\n4th contiguous subarray = {1 4 5} Max = 5\n5th contiguous subarray = {4 5 2} Max = 5\n6th contiguous subarray = {5 2 3} Max = 5\n7th contiguous subarray = {2 3 6} Max = 6"
},
{
"code": null,
"e": 754,
"s": 743,
"text": "Example 2:"
},
{
"code": null,
"e": 1190,
"s": 754,
"text": "Input:\nN = 10, K = 4\narr[] = 8 5 10 7 9 4 15 12 90 13\nOutput: \n10 10 10 15 15 90 90\nExplanation: \n1st contiguous subarray = {8 5 10 7}, Max = 10\n2nd contiguous subarray = {5 10 7 9}, Max = 10\n3rd contiguous subarray = {10 7 9 4}, Max = 10\n4th contiguous subarray = {7 9 4 15}, Max = 15\n5th contiguous subarray = {9 4 15 12}, \nMax = 15\n6th contiguous subarray = {4 15 12 90},\nMax = 90\n7th contiguous subarray = {15 12 90 13}, \nMax = 90\n"
},
{
"code": null,
"e": 1434,
"s": 1190,
"text": "Your Task: \nYou dont need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K."
},
{
"code": null,
"e": 1496,
"s": 1434,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(k)"
},
{
"code": null,
"e": 1548,
"s": 1496,
"text": "Constraints:\n1 ≤ N ≤ 107\n1 ≤ K ≤ N\n0 ≤ arr[i] ≤ 107"
},
{
"code": null,
"e": 1550,
"s": 1548,
"text": "0"
},
{
"code": null,
"e": 1575,
"s": 1550,
"text": "amanahirwar1512 days ago"
},
{
"code": null,
"e": 1605,
"s": 1575,
"text": "C++ EASY SOLUTION USING DEQUE"
},
{
"code": null,
"e": 2229,
"s": 1605,
"text": "vector <int> max_of_subarrays(int *arr, int n, int k) { vector<int> ans; deque<int> dq(k); int i; for(i=0; i<k; ++i){ while((!dq.empty()) && arr[i]>=arr[dq.back()]){ dq.pop_back(); } dq.push_back(i); } ans.push_back(arr[dq.front()]); for(i=k; i<n; ++i){ if(dq.front()==i-k){ dq.pop_front(); } while((!dq.empty()) && arr[i]>=arr[dq.back()]){ dq.pop_back(); } dq.push_back(i); ans.push_back(arr[dq.front()]); } return ans; }"
},
{
"code": null,
"e": 2232,
"s": 2229,
"text": "+1"
},
{
"code": null,
"e": 2261,
"s": 2232,
"text": "bhaskarmaheshwari83 days ago"
},
{
"code": null,
"e": 2992,
"s": 2261,
"text": "vector<int> ans; int i=0,j=0; int max1=INT_MIN; while(j<n) { if(j-i+1<=k) { max1=max(max1,arr[j]); if(j-i+1==k) { ans.push_back(max1); } j++; } else { if(arr[i]==max1) { max1=INT_MIN; for(int l=i+1;l<=i+k-1;l++) { max1=max(max1,arr[l]); } } i++; } } return ans; "
},
{
"code": null,
"e": 2994,
"s": 2992,
"text": "0"
},
{
"code": null,
"e": 3013,
"s": 2994,
"text": "kknamish3 days ago"
},
{
"code": null,
"e": 3321,
"s": 3013,
"text": "class Solution:\n def max_of_subarrays(self,arr,n,k):\n i,j=0,0\n mx=max(arr[:k])\n ans=[mx]\n for i in range(k,n):\n if mx!=arr[i-k]:\n mx=max(mx,arr[i])\n else:\n mx=max(arr[i-k+1:i+1])\n ans.append(mx)\n return ans"
},
{
"code": null,
"e": 3324,
"s": 3321,
"text": "+1"
},
{
"code": null,
"e": 3358,
"s": 3324,
"text": "harendraseervi1234567895 days ago"
},
{
"code": null,
"e": 3376,
"s": 3358,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 4137,
"s": 3376,
"text": "vector <int> max_of_subarrays(int *arr, int n, int k)\n {\n \n // your code here\n vector<int>ans;\n int maxi=INT_MIN;\n for(int i=0;i<k;i++){\n if(arr[i]>maxi) maxi=arr[i];\n }\n ans.push_back(maxi);\n for(int i=k;i<n;i++){\n if(arr[i]>maxi){\n ans.push_back(arr[i]);\n maxi=arr[i];\n }\n else{\n if(arr[i-k]!=maxi){\n ans.push_back(maxi);\n }\n else{\n maxi=INT_MIN;\n for(int j=i-k+1;j<=i;j++){\n maxi=max(arr[j],maxi);\n }\n ans.push_back(maxi);\n }\n }\n }\n return ans;\n }"
},
{
"code": null,
"e": 4139,
"s": 4137,
"text": "0"
},
{
"code": null,
"e": 4161,
"s": 4139,
"text": "tarunkanade5 days ago"
},
{
"code": null,
"e": 4169,
"s": 4161,
"text": "4.6/6.8"
},
{
"code": null,
"e": 5023,
"s": 4169,
"text": "static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)\n {\n // Your code here\n ArrayDeque<Integer> q = new ArrayDeque<>();\n ArrayList<Integer> maxSub = new ArrayList<>();\n \n for(int i=0; i<k; i++){\n while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){\n q.pollLast();\n }\n q.offerLast(i);\n }\n \n for(int i=k; i<n; i++){\n maxSub.add(arr[q.peekFirst()]);\n \n while(!q.isEmpty() && q.peekFirst() <= i-k){\n q.pollFirst();\n }\n \n while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){\n q.pollLast();\n }\n \n q.offerLast(i);\n }\n \n maxSub.add(arr[q.peekFirst()]);\n \n return maxSub;\n }"
},
{
"code": null,
"e": 5026,
"s": 5023,
"text": "+1"
},
{
"code": null,
"e": 5047,
"s": 5026,
"text": "soumik20001 week ago"
},
{
"code": null,
"e": 5077,
"s": 5047,
"text": "Java Max Heap Simple solution"
},
{
"code": null,
"e": 5473,
"s": 5077,
"text": "PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder()); ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i<k; i++) { pq.add(arr[i]); } list.add(pq.peek()); for(int i = k; i<n; i++) { pq.remove(arr[i-k]); pq.add(arr[i]); list.add(pq.peek()); } return list;"
},
{
"code": null,
"e": 5475,
"s": 5473,
"text": "0"
},
{
"code": null,
"e": 5502,
"s": 5475,
"text": "himanshukug19cs2 weeks ago"
},
{
"code": null,
"e": 5508,
"s": 5502,
"text": "java "
},
{
"code": null,
"e": 6129,
"s": 5508,
"text": " int[] maxf= new int[n]; Stack<Integer> st = new Stack<>(); for(int i=n-1;i>=0;i--){ while(!st.empty()&&arr[st.peek()]<=arr[i]){ st.pop(); } if(st.empty()) maxf[i]=n; else maxf[i]=st.peek(); st.push(i); } ArrayList <Integer> al = new ArrayList<>(); for(int i=0;i<=n-k;i++){ int j=i; while(maxf[j]<i+k){ j=maxf[j]; } if(j==i) al.add(arr[i]); else al.add(arr[j]); } return al; }"
},
{
"code": null,
"e": 6132,
"s": 6129,
"text": "-3"
},
{
"code": null,
"e": 6171,
"s": 6132,
"text": "1941012837shivamkumarsharma3 weeks ago"
},
{
"code": null,
"e": 6188,
"s": 6171,
"text": "JAVA Simple Code"
},
{
"code": null,
"e": 6235,
"s": 6188,
"text": "// by 1941012837_Shivam Kumar Sharma_ITER(SOA)"
},
{
"code": null,
"e": 6726,
"s": 6235,
"text": "class Solution\n{\n //Function to find maximum of each subarray of size k.\n static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)\n {\n int len=n-k;\n int max=0;\n ArrayList<Integer>list= new ArrayList<>();\n \n for(int i=0;i<=len;i++){\n max=arr[i];\n \n for(int j=1;j<k;j++){\n \tmax=Math.max(arr[i+j],max);\n } \n list.add(max);\n }\treturn (list);\n \t\t}\t\n \t\t\t}"
},
{
"code": null,
"e": 6729,
"s": 6726,
"text": "+1"
},
{
"code": null,
"e": 6746,
"s": 6729,
"text": "anupb4 weeks ago"
},
{
"code": null,
"e": 6762,
"s": 6746,
"text": "Python Solution"
},
{
"code": null,
"e": 7657,
"s": 6764,
"text": "class Solution:\n \n #Function to find maximum of each subarray of size k.\n def max_of_subarrays(self,arr,n,k):\n result = list()\n max_num = 0\n first_pointer = 0\n \n if k > n:\n return max(arr)\n \n sub_array = arr[0:k]\n max_num = max(sub_array)\n result.append(max_num)\n \n for i in range(k,n):\n # for optimization\n if max_num > arr[first_pointer]:\n sub_array.pop(0)\n sub_array.append(arr[i])\n max_num = max(max_num, arr[i])\n result.append(max_num)\n first_pointer += 1\n else:\n sub_array.pop(0)\n sub_array.append(arr[i])\n max_num = max(sub_array)\n result.append(max_num)\n first_pointer += 1\n \n return result"
},
{
"code": null,
"e": 7662,
"s": 7659,
"text": "+1"
},
{
"code": null,
"e": 7694,
"s": 7662,
"text": "inukurthibhargavi2384 weeks ago"
},
{
"code": null,
"e": 8067,
"s": 7694,
"text": "def max_of_subarrays(self,arr,n,k):\n ans=[]\n i=k\n j=0\n ans.append(max(arr[:k]))\n while i<n:\n if arr[j]==ans[-1]:\n ans.append(max(arr[j+1:i+1]))\n elif arr[i]>ans[-1]:\n ans.append(arr[i])\n else:\n ans.append(ans[-1])\n j+=1\n i+=1\n \n return ans"
},
{
"code": null,
"e": 8213,
"s": 8067,
"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": 8249,
"s": 8213,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8259,
"s": 8249,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8269,
"s": 8259,
"text": "\nContest\n"
},
{
"code": null,
"e": 8332,
"s": 8269,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8480,
"s": 8332,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8688,
"s": 8480,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8794,
"s": 8688,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JQuery .Deferred() method - GeeksforGeeks | 16 Jul, 2020
This JQuery.Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
Syntax:
jQuery.Deferred([beforeStart])
Parameters:
beforeStart: This is a function, which is called just before the constructor returns.
Return Value: This method creates and returns a new deferred object.
There are two examples discussed below:
Example: In this example, the Deferred() is used to create a new object and after that then() method is called with notify and resolve method.<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery.Deferred() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>', '#GFG_DOWN'); def.resolve('Deferred "def" is resolved.<br/>', '#GFG_DOWN'); } </script> </body> </html>Output:
<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery.Deferred() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>', '#GFG_DOWN'); def.resolve('Deferred "def" is resolved.<br/>', '#GFG_DOWN'); } </script> </body> </html>
Output:
Example: In this example, the Deferred() method is used and the state of Deferred object is checked.<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery.Deferred() method"; var def = $.Deferred(); def.resolve(); function Geeks() { $('#GFG_DOWN').text( 'deferred state is ' + def.state()); } </script> </body> </html> Output:
<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery.Deferred() method"; var def = $.Deferred(); def.resolve(); function Geeks() { $('#GFG_DOWN').text( 'deferred state is ' + def.state()); } </script> </body> </html>
Output:
jQuery-Methods
JavaScript
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery? | [
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24305,
"s": 24040,
"text": "This JQuery.Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function."
},
{
"code": null,
"e": 24313,
"s": 24305,
"text": "Syntax:"
},
{
"code": null,
"e": 24344,
"s": 24313,
"text": "jQuery.Deferred([beforeStart])"
},
{
"code": null,
"e": 24356,
"s": 24344,
"text": "Parameters:"
},
{
"code": null,
"e": 24442,
"s": 24356,
"text": "beforeStart: This is a function, which is called just before the constructor returns."
},
{
"code": null,
"e": 24511,
"s": 24442,
"text": "Return Value: This method creates and returns a new deferred object."
},
{
"code": null,
"e": 24551,
"s": 24511,
"text": "There are two examples discussed below:"
},
{
"code": null,
"e": 25783,
"s": 24551,
"text": "Example: In this example, the Deferred() is used to create a new object and after that then() method is called with notify and resolve method.<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery.Deferred() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>', '#GFG_DOWN'); def.resolve('Deferred \"def\" is resolved.<br/>', '#GFG_DOWN'); } </script> </body> </html>Output:"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery.Deferred() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>', '#GFG_DOWN'); def.resolve('Deferred \"def\" is resolved.<br/>', '#GFG_DOWN'); } </script> </body> </html>",
"e": 26866,
"s": 25783,
"text": null
},
{
"code": null,
"e": 26874,
"s": 26866,
"text": "Output:"
},
{
"code": null,
"e": 27683,
"s": 26874,
"text": "Example: In this example, the Deferred() method is used and the state of Deferred object is checked.<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery.Deferred() method\"; var def = $.Deferred(); def.resolve(); function Geeks() { $('#GFG_DOWN').text( 'deferred state is ' + def.state()); } </script> </body> </html> Output:"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery.Deferred() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery.Deferred() method\"; var def = $.Deferred(); def.resolve(); function Geeks() { $('#GFG_DOWN').text( 'deferred state is ' + def.state()); } </script> </body> </html> ",
"e": 28385,
"s": 27683,
"text": null
},
{
"code": null,
"e": 28393,
"s": 28385,
"text": "Output:"
},
{
"code": null,
"e": 28408,
"s": 28393,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 28419,
"s": 28408,
"text": "JavaScript"
},
{
"code": null,
"e": 28426,
"s": 28419,
"text": "JQuery"
},
{
"code": null,
"e": 28443,
"s": 28426,
"text": "Web Technologies"
},
{
"code": null,
"e": 28541,
"s": 28443,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28550,
"s": 28541,
"text": "Comments"
},
{
"code": null,
"e": 28563,
"s": 28550,
"text": "Old Comments"
},
{
"code": null,
"e": 28624,
"s": 28563,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28669,
"s": 28624,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28741,
"s": 28669,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28793,
"s": 28741,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28839,
"s": 28793,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28885,
"s": 28839,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 28914,
"s": 28885,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28977,
"s": 28914,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 29054,
"s": 28977,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Shuffle or Randomize a list in Java - GeeksforGeeks | 09 Sep, 2021
Shuffling a list Collections.shuffle() is used to shuffle lists in java.Class hierarchy:
java
↳ util
↳ Collections
Syntax:
Collections.shuffle(list);
Examples:
Java
// Java program to demonstrate working of shuffle()import java.util.*; public class GFG { public static void main(String[] args) { ArrayList<String> mylist = new ArrayList<String>(); mylist.add("ide"); mylist.add("quiz"); mylist.add("geeksforgeeks"); mylist.add("quiz"); mylist.add("practice"); mylist.add("qa"); System.out.println("Original List : \n" + mylist); Collections.shuffle(mylist); System.out.println("\nShuffled List : \n" + mylist); }}
Original List :
[ide, quiz, geeksforgeeks, quiz, practice, qa]
Shuffled List :
[ide, practice, quiz, qa, geeksforgeeks, quiz]
Shuffling a list using user provided Random Object Syntax:
Collections.shuffle(list, Random object);
Examples:
Java
// Java program to demonstrate working of shuffle()// with user provided source of randomness.import java.util.*; public class GFG { public static void main(String[] args) { ArrayList<String> mylist = new ArrayList<String>(); mylist.add("ide"); mylist.add("quiz"); mylist.add("geeksforgeeks"); mylist.add("quiz"); mylist.add("practice"); mylist.add("qa"); System.out.println("Original List : \n" + mylist); // Here we use Random() to shuffle given list. Collections.shuffle(mylist, new Random()); System.out.println("\nShuffled List with Random() : \n" + mylist); // Here we use Random(3) to shuffle given list. Here 3 // is seed value for Random. Collections.shuffle(mylist, new Random(3)); System.out.println("\nShuffled List with Random(3) : \n" + mylist); // Here we use Random(5) to shuffle given list. Here 5 // is seed value for Random. Collections.shuffle(mylist, new Random(5)); System.out.println("\nShuffled List with Random(5) : \n" + mylist); }}
Original List :
[ide, quiz, geeksforgeeks, quiz, practice, qa]
Shuffled List with Random() :
[geeksforgeeks, practice, qa, ide, quiz, quiz]
Shuffled List with Random(3) :
[quiz, ide, practice, quiz, geeksforgeeks, qa]
Shuffled List with Random(5) :
[ide, quiz, geeksforgeeks, quiz, practice, qa]
How to write our own Shuffle method? We can use Fisher–Yates shuffle Algorithm that works in O(n) time.
Java
// Java Program to shuffle a given arrayimport java.util.Random;import java.util.Arrays;public class ShuffleRand{ // A Function to generate a random permutation of arr[] static void randomize( int arr[], int n) { // Creating a object for Random class Random r = new Random(); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = r.nextInt(i); // Swap arr[i] with the element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array System.out.println(Arrays.toString(arr)); } // Driver Program to test above function public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; randomize (arr, n); }}
[5, 7, 1, 3, 6, 8, 4, 2]
simmytarika5
Java-List-Programs
Java
Java Programs
Randomized
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java | [
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24651,
"s": 24561,
"text": "Shuffling a list Collections.shuffle() is used to shuffle lists in java.Class hierarchy: "
},
{
"code": null,
"e": 24686,
"s": 24651,
"text": "java\n ↳ util\n ↳ Collections"
},
{
"code": null,
"e": 24695,
"s": 24686,
"text": "Syntax: "
},
{
"code": null,
"e": 24722,
"s": 24695,
"text": "Collections.shuffle(list);"
},
{
"code": null,
"e": 24733,
"s": 24722,
"text": "Examples: "
},
{
"code": null,
"e": 24738,
"s": 24733,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of shuffle()import java.util.*; public class GFG { public static void main(String[] args) { ArrayList<String> mylist = new ArrayList<String>(); mylist.add(\"ide\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); mylist.add(\"quiz\"); mylist.add(\"practice\"); mylist.add(\"qa\"); System.out.println(\"Original List : \\n\" + mylist); Collections.shuffle(mylist); System.out.println(\"\\nShuffled List : \\n\" + mylist); }}",
"e": 25269,
"s": 24738,
"text": null
},
{
"code": null,
"e": 25398,
"s": 25269,
"text": "Original List : \n[ide, quiz, geeksforgeeks, quiz, practice, qa]\n\nShuffled List : \n[ide, practice, quiz, qa, geeksforgeeks, quiz]"
},
{
"code": null,
"e": 25459,
"s": 25400,
"text": "Shuffling a list using user provided Random Object Syntax:"
},
{
"code": null,
"e": 25501,
"s": 25459,
"text": "Collections.shuffle(list, Random object);"
},
{
"code": null,
"e": 25512,
"s": 25501,
"text": "Examples: "
},
{
"code": null,
"e": 25517,
"s": 25512,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of shuffle()// with user provided source of randomness.import java.util.*; public class GFG { public static void main(String[] args) { ArrayList<String> mylist = new ArrayList<String>(); mylist.add(\"ide\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); mylist.add(\"quiz\"); mylist.add(\"practice\"); mylist.add(\"qa\"); System.out.println(\"Original List : \\n\" + mylist); // Here we use Random() to shuffle given list. Collections.shuffle(mylist, new Random()); System.out.println(\"\\nShuffled List with Random() : \\n\" + mylist); // Here we use Random(3) to shuffle given list. Here 3 // is seed value for Random. Collections.shuffle(mylist, new Random(3)); System.out.println(\"\\nShuffled List with Random(3) : \\n\" + mylist); // Here we use Random(5) to shuffle given list. Here 5 // is seed value for Random. Collections.shuffle(mylist, new Random(5)); System.out.println(\"\\nShuffled List with Random(5) : \\n\" + mylist); }}",
"e": 26701,
"s": 25517,
"text": null
},
{
"code": null,
"e": 27004,
"s": 26701,
"text": "Original List : \n[ide, quiz, geeksforgeeks, quiz, practice, qa]\n\nShuffled List with Random() : \n[geeksforgeeks, practice, qa, ide, quiz, quiz]\n\nShuffled List with Random(3) : \n[quiz, ide, practice, quiz, geeksforgeeks, qa]\n\nShuffled List with Random(5) : \n[ide, quiz, geeksforgeeks, quiz, practice, qa]"
},
{
"code": null,
"e": 27111,
"s": 27006,
"text": "How to write our own Shuffle method? We can use Fisher–Yates shuffle Algorithm that works in O(n) time. "
},
{
"code": null,
"e": 27116,
"s": 27111,
"text": "Java"
},
{
"code": "// Java Program to shuffle a given arrayimport java.util.Random;import java.util.Arrays;public class ShuffleRand{ // A Function to generate a random permutation of arr[] static void randomize( int arr[], int n) { // Creating a object for Random class Random r = new Random(); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = r.nextInt(i); // Swap arr[i] with the element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array System.out.println(Arrays.toString(arr)); } // Driver Program to test above function public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; randomize (arr, n); }}",
"e": 28154,
"s": 27116,
"text": null
},
{
"code": null,
"e": 28179,
"s": 28154,
"text": "[5, 7, 1, 3, 6, 8, 4, 2]"
},
{
"code": null,
"e": 28194,
"s": 28181,
"text": "simmytarika5"
},
{
"code": null,
"e": 28213,
"s": 28194,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 28218,
"s": 28213,
"text": "Java"
},
{
"code": null,
"e": 28232,
"s": 28218,
"text": "Java Programs"
},
{
"code": null,
"e": 28243,
"s": 28232,
"text": "Randomized"
},
{
"code": null,
"e": 28248,
"s": 28243,
"text": "Java"
},
{
"code": null,
"e": 28346,
"s": 28248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28355,
"s": 28346,
"text": "Comments"
},
{
"code": null,
"e": 28368,
"s": 28355,
"text": "Old Comments"
},
{
"code": null,
"e": 28400,
"s": 28368,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28430,
"s": 28400,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28449,
"s": 28430,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28480,
"s": 28449,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28498,
"s": 28480,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28526,
"s": 28498,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 28570,
"s": 28526,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28596,
"s": 28570,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28643,
"s": 28596,
"text": "Implementing a Linked List in Java using Class"
}
] |
What are generator functions in JavaScript? | Generator Functions allows execution of code in between when a function is exited and resumed later. So, generators can be used to manage flow control in a code. Cancel asynchronous operations easily since execution can be paused anytime.
Here’s the syntax; do not forget to add an asterisk after the “function” keyword. You can add an asterisk using any of the following −
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {}
Let’s see how to use a generator function
Live Demo
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html> | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Generator Functions allows execution of code in between when a function is exited and resumed later. So, generators can be used to manage flow control in a code. Cancel asynchronous operations easily since execution can be paused anytime."
},
{
"code": null,
"e": 1436,
"s": 1301,
"text": "Here’s the syntax; do not forget to add an asterisk after the “function” keyword. You can add an asterisk using any of the following −"
},
{
"code": null,
"e": 1525,
"s": 1436,
"text": "function *myFunction() {}\n// or\nfunction* myFunction() {}\n// or\nfunction*myFunction() {}"
},
{
"code": null,
"e": 1567,
"s": 1525,
"text": "Let’s see how to use a generator function"
},
{
"code": null,
"e": 1577,
"s": 1567,
"text": "Live Demo"
},
{
"code": null,
"e": 2086,
"s": 1577,
"text": "<html>\n <body>\n <script>\n function* display() {\n var num = 1;\n while (num < 5)\n yield num++;\n }\n var myGenerator = display();\n\n document.write(myGenerator.next().value);\n document.write(\"<br>\"+myGenerator.next().value);\n document.write(\"<br>\"+myGenerator.next().value);\n document.write(\"<br>\"+myGenerator.next().value);\n document.write(\"<br>\"+myGenerator.next().value);\n </script>\n </body>\n</html>"
}
] |
How do you initialize jagged arrays in C#? | A Jagged array is an array of arrays. This is how you can initialize it.
int[][] rank = new int[2][]{new int[]{3,2,7},new int[]{9,4,5,6}};
The following is an example showing how to initialize jagged arrays in C#.
Live Demo
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4} };
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4 | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "A Jagged array is an array of arrays. This is how you can initialize it."
},
{
"code": null,
"e": 1201,
"s": 1135,
"text": "int[][] rank = new int[2][]{new int[]{3,2,7},new int[]{9,4,5,6}};"
},
{
"code": null,
"e": 1276,
"s": 1201,
"text": "The following is an example showing how to initialize jagged arrays in C#."
},
{
"code": null,
"e": 1287,
"s": 1276,
"text": " Live Demo"
},
{
"code": null,
"e": 1701,
"s": 1287,
"text": "using System;\nnamespace ArrayApplication {\n class MyArray {\n static void Main(string[] args) {\n int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4} };\n int i, j;\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0}][{1}] = {2}\", i, j, a[i][j]);\n }\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1773,
"s": 1701,
"text": "a[0][0] = 0\na[0][1] = 0\na[1][0] = 1\na[1][1] = 2\na[2][0] = 2\na[2][1] = 4"
}
] |
How to replace NA’s to a value of selected columns in an R data frame? | In data analysis, finding some NA values in a data frame is very common but all the NA values do not create problems if the column that contain NA values is not useful for the analysis. We can replace all NA values to 0 or to any other for the columns that are useful.
Consider the below data frame −
> set.seed(99)
> x1<-sample(c(5,10,15,NA),20,replace=TRUE)
> x2<-sample(c(1,2,3,NA),20,replace=TRUE)
> x3<-sample(c(20,21,22,23,24,25,NA),20,replace=TRUE)
> x4<-sample(c(letters[1:10],NA),20,replace=TRUE)
> x5<-sample(c(1:10,NA),20,replace=TRUE)
> df<-data.frame(x1,x2,x3,x4,x5)
> df
x1 x2 x3 x4 x5
1 NA NA 25 <NA> NA
2 5 2 24 f 2
3 NA 2 25 i 7
4 10 NA 23 i 10
5 10 1 21 c 3
6 5 NA NA h NA
7 15 2 20 g 10
8 10 NA 25 d 10
9 10 2 23 c 5
10 10 1 NA f 8
11 NA 3 25 <NA> 5
12 10 2 NA h 4
13 NA 3 25 g 1
14 5 2 NA c 8
15 NA 2 NA <NA> 3
16 NA NA 23 f 7
17 15 1 24 <NA> 9
18 NA NA NA b 3
19 5 3 NA d 3
20 10 2 20 g 8
Changing NA’s to zero of consecutive columns −
> df[,c("x1","x2")][is.na(df[,c("x1","x2")])] <- 0
> df
x1 x2 x3 x4 x5
1 0 0 25 <NA> NA
2 5 2 24 f 2
3 0 2 25 i 7
4 10 0 23 i 10
5 10 1 21 c 3
6 5 0 NA h NA
7 15 2 20 g 10
8 10 0 25 d 10
9 10 2 23 c 5
10 10 1 NA f 8
11 0 3 25 <NA> 5
12 10 2 NA h 4
13 0 3 25 g 1
14 5 2 NA c 8
15 0 2 NA <NA> 3
16 0 0 23 f 7
17 15 1 24 <NA> 9
18 0 0 NA b 3
19 5 3 NA d 3
20 10 2 20 g 8
Changing NA’s to zero of non-consecutive columns −
> df[,c("x3","x5")][is.na(df[,c("x3","x5")])] <- 0
> df
x1 x2 x3 x4 x5
1 0 0 25 <NA> 0
2 5 2 24 f 2
3 0 2 25 i 7
4 10 0 23 i 10
5 10 1 21 c 3
6 5 0 0 h 0
7 15 2 20 g 10
8 10 0 25 d 10
9 10 2 23 c 5
10 10 1 0 f 8
11 0 3 25 <NA> 5
12 10 2 0 h 4
13 0 3 25 g 1
14 5 2 0 c 8
15 0 2 0 <NA> 3
16 0 0 23 f 7
17 15 1 24 <NA> 9
18 0 0 0 b 3
19 5 3 0 d 3
20 10 2 20 g 8 | [
{
"code": null,
"e": 1331,
"s": 1062,
"text": "In data analysis, finding some NA values in a data frame is very common but all the NA values do not create problems if the column that contain NA values is not useful for the analysis. We can replace all NA values to 0 or to any other for the columns that are useful."
},
{
"code": null,
"e": 1363,
"s": 1331,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 2197,
"s": 1363,
"text": "> set.seed(99)\n> x1<-sample(c(5,10,15,NA),20,replace=TRUE)\n> x2<-sample(c(1,2,3,NA),20,replace=TRUE)\n> x3<-sample(c(20,21,22,23,24,25,NA),20,replace=TRUE)\n> x4<-sample(c(letters[1:10],NA),20,replace=TRUE)\n> x5<-sample(c(1:10,NA),20,replace=TRUE)\n> df<-data.frame(x1,x2,x3,x4,x5)\n> df\n x1 x2 x3 x4 x5\n1 NA NA 25 <NA> NA\n2 5 2 24 f 2\n3 NA 2 25 i 7\n4 10 NA 23 i 10\n5 10 1 21 c 3\n6 5 NA NA h NA\n7 15 2 20 g 10\n8 10 NA 25 d 10\n9 10 2 23 c 5\n10 10 1 NA f 8\n11 NA 3 25 <NA> 5\n12 10 2 NA h 4\n13 NA 3 25 g 1\n14 5 2 NA c 8\n15 NA 2 NA <NA> 3\n16 NA NA 23 f 7\n17 15 1 24 <NA> 9\n18 NA NA NA b 3\n19 5 3 NA d 3 \n20 10 2 20 g 8"
},
{
"code": null,
"e": 2244,
"s": 2197,
"text": "Changing NA’s to zero of consecutive columns −"
},
{
"code": null,
"e": 2612,
"s": 2244,
"text": "> df[,c(\"x1\",\"x2\")][is.na(df[,c(\"x1\",\"x2\")])] <- 0\n> df\nx1 x2 x3 x4 x5\n1 0 0 25 <NA> NA\n2 5 2 24 f 2\n3 0 2 25 i 7\n4 10 0 23 i 10\n5 10 1 21 c 3\n6 5 0 NA h NA\n7 15 2 20 g 10\n8 10 0 25 d 10\n9 10 2 23 c 5\n10 10 1 NA f 8\n11 0 3 25 <NA> 5\n12 10 2 NA h 4\n13 0 3 25 g 1\n14 5 2 NA c 8\n15 0 2 NA <NA> 3\n16 0 0 23 f 7\n17 15 1 24 <NA> 9\n18 0 0 NA b 3\n19 5 3 NA d 3\n20 10 2 20 g 8"
},
{
"code": null,
"e": 2663,
"s": 2612,
"text": "Changing NA’s to zero of non-consecutive columns −"
},
{
"code": null,
"e": 3022,
"s": 2663,
"text": "> df[,c(\"x3\",\"x5\")][is.na(df[,c(\"x3\",\"x5\")])] <- 0\n> df\nx1 x2 x3 x4 x5\n1 0 0 25 <NA> 0\n2 5 2 24 f 2\n3 0 2 25 i 7\n4 10 0 23 i 10\n5 10 1 21 c 3\n6 5 0 0 h 0\n7 15 2 20 g 10\n8 10 0 25 d 10\n9 10 2 23 c 5\n10 10 1 0 f 8\n11 0 3 25 <NA> 5\n12 10 2 0 h 4\n13 0 3 25 g 1\n14 5 2 0 c 8\n15 0 2 0 <NA> 3\n16 0 0 23 f 7\n17 15 1 24 <NA> 9\n18 0 0 0 b 3\n19 5 3 0 d 3\n20 10 2 20 g 8"
}
] |
Apache IVY - Settings File | Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file.
<ivysettings>
<properties file="${ivy.settings.dir}/ivysettings-file.properties" />
<settings defaultCache="${cache.dir}" defaultResolver="ibiblio" checkUpToDate="false" />
<resolvers>
<ibiblio name="ibiblio" />
<filesystem name="internal">
<ivy pattern="${repository.dir}/[module]/ivy-[revision].xml" />
<artifact pattern="${repository.dir}/[module]/[artifact]-[revision].[ext]" />
</filesystem>
</resolvers>
<modules>
<module organisation="tutorialspoint" name=".*" resolver="internal" />
</modules>
</ivysettings>
Following are the important tags of Ivy Setting file.
property − To set an ivy variable. Cardinality: 0..n
property − To set an ivy variable. Cardinality: 0..n
properties − To set an ivy variables using properties file. Cardinality: 0..n
properties − To set an ivy variables using properties file. Cardinality: 0..n
settings − To configure ivy with default values. Cardinality: 0..1
settings − To configure ivy with default values. Cardinality: 0..1
include − To include another settings file. Cardinality: 0..n
include − To include another settings file. Cardinality: 0..n
classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n
classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n
typedef − To define new types in ivy. Cardinality: 0..n
typedef − To define new types in ivy. Cardinality: 0..n
lock-strategies − To define lock strategies. Cardinality: 0..1
lock-strategies − To define lock strategies. Cardinality: 0..1
caches − To define repository cache managers. Cardinality: 0..1
caches − To define repository cache managers. Cardinality: 0..1
latest-strategies − To define latest strategies. Cardinality: 0..1
latest-strategies − To define latest strategies. Cardinality: 0..1
parsers − To define module descriptor parsers. Cardinality: 0..1
parsers − To define module descriptor parsers. Cardinality: 0..1
version-matchers − To define new version matchers. Cardinality: 0..1
version-matchers − To define new version matchers. Cardinality: 0..1
triggers − To register triggers on ivy events. Cardinality: 0..1
triggers − To register triggers on ivy events. Cardinality: 0..1
namespaces − To define new namespaces. Cardinality: 0..1
namespaces − To define new namespaces. Cardinality: 0..1
macrodef − To define a new macro resolver. Cardinality: 0..n
macrodef − To define a new macro resolver. Cardinality: 0..n
resolvers − To define dependency resolvers. Cardinality: 0..1
resolvers − To define dependency resolvers. Cardinality: 0..1
conflict-managers − To define conflicts managers. Cardinality: 0..1
conflict-managers − To define conflicts managers. Cardinality: 0..1
modules − To define rules between modules and dependency resolvers. Cardinality: 0..1
modules − To define rules between modules and dependency resolvers. Cardinality: 0..1
outputters − To define the list of available report outputters. Cardinality: 0..1
outputters − To define the list of available report outputters. Cardinality: 0..1
statuses − To define the list of available statuses. Cardinality: 0..1
statuses − To define the list of available statuses. Cardinality: 0..1
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2157,
"s": 2004,
"text": "Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file."
},
{
"code": null,
"e": 2734,
"s": 2157,
"text": "<ivysettings>\n <properties file=\"${ivy.settings.dir}/ivysettings-file.properties\" />\n <settings defaultCache=\"${cache.dir}\" defaultResolver=\"ibiblio\" checkUpToDate=\"false\" />\n <resolvers>\n <ibiblio name=\"ibiblio\" />\n <filesystem name=\"internal\">\n <ivy pattern=\"${repository.dir}/[module]/ivy-[revision].xml\" />\n <artifact pattern=\"${repository.dir}/[module]/[artifact]-[revision].[ext]\" />\n </filesystem>\n </resolvers>\n <modules>\n <module organisation=\"tutorialspoint\" name=\".*\" resolver=\"internal\" />\n </modules>\n</ivysettings>"
},
{
"code": null,
"e": 2788,
"s": 2734,
"text": "Following are the important tags of Ivy Setting file."
},
{
"code": null,
"e": 2841,
"s": 2788,
"text": "property − To set an ivy variable. Cardinality: 0..n"
},
{
"code": null,
"e": 2894,
"s": 2841,
"text": "property − To set an ivy variable. Cardinality: 0..n"
},
{
"code": null,
"e": 2972,
"s": 2894,
"text": "properties − To set an ivy variables using properties file. Cardinality: 0..n"
},
{
"code": null,
"e": 3050,
"s": 2972,
"text": "properties − To set an ivy variables using properties file. Cardinality: 0..n"
},
{
"code": null,
"e": 3117,
"s": 3050,
"text": "settings − To configure ivy with default values. Cardinality: 0..1"
},
{
"code": null,
"e": 3184,
"s": 3117,
"text": "settings − To configure ivy with default values. Cardinality: 0..1"
},
{
"code": null,
"e": 3246,
"s": 3184,
"text": "include − To include another settings file. Cardinality: 0..n"
},
{
"code": null,
"e": 3308,
"s": 3246,
"text": "include − To include another settings file. Cardinality: 0..n"
},
{
"code": null,
"e": 3395,
"s": 3308,
"text": "classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n"
},
{
"code": null,
"e": 3482,
"s": 3395,
"text": "classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n"
},
{
"code": null,
"e": 3538,
"s": 3482,
"text": "typedef − To define new types in ivy. Cardinality: 0..n"
},
{
"code": null,
"e": 3594,
"s": 3538,
"text": "typedef − To define new types in ivy. Cardinality: 0..n"
},
{
"code": null,
"e": 3657,
"s": 3594,
"text": "lock-strategies − To define lock strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 3720,
"s": 3657,
"text": "lock-strategies − To define lock strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 3784,
"s": 3720,
"text": "caches − To define repository cache managers. Cardinality: 0..1"
},
{
"code": null,
"e": 3848,
"s": 3784,
"text": "caches − To define repository cache managers. Cardinality: 0..1"
},
{
"code": null,
"e": 3915,
"s": 3848,
"text": "latest-strategies − To define latest strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 3982,
"s": 3915,
"text": "latest-strategies − To define latest strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 4047,
"s": 3982,
"text": "parsers − To define module descriptor parsers. Cardinality: 0..1"
},
{
"code": null,
"e": 4112,
"s": 4047,
"text": "parsers − To define module descriptor parsers. Cardinality: 0..1"
},
{
"code": null,
"e": 4181,
"s": 4112,
"text": "version-matchers − To define new version matchers. Cardinality: 0..1"
},
{
"code": null,
"e": 4250,
"s": 4181,
"text": "version-matchers − To define new version matchers. Cardinality: 0..1"
},
{
"code": null,
"e": 4315,
"s": 4250,
"text": "triggers − To\tregister triggers on ivy events. Cardinality: 0..1"
},
{
"code": null,
"e": 4380,
"s": 4315,
"text": "triggers − To\tregister triggers on ivy events. Cardinality: 0..1"
},
{
"code": null,
"e": 4437,
"s": 4380,
"text": "namespaces − To define new namespaces. Cardinality: 0..1"
},
{
"code": null,
"e": 4494,
"s": 4437,
"text": "namespaces − To define new namespaces. Cardinality: 0..1"
},
{
"code": null,
"e": 4555,
"s": 4494,
"text": "macrodef − To define a new macro resolver. Cardinality: 0..n"
},
{
"code": null,
"e": 4616,
"s": 4555,
"text": "macrodef − To define a new macro resolver. Cardinality: 0..n"
},
{
"code": null,
"e": 4678,
"s": 4616,
"text": "resolvers − To define dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 4740,
"s": 4678,
"text": "resolvers − To define dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 4808,
"s": 4740,
"text": "conflict-managers − To define conflicts managers. Cardinality: 0..1"
},
{
"code": null,
"e": 4876,
"s": 4808,
"text": "conflict-managers − To define conflicts managers. Cardinality: 0..1"
},
{
"code": null,
"e": 4962,
"s": 4876,
"text": "modules − To define rules between modules and dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 5048,
"s": 4962,
"text": "modules − To define rules between modules and dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 5130,
"s": 5048,
"text": "outputters − To define the list of available report outputters. Cardinality: 0..1"
},
{
"code": null,
"e": 5212,
"s": 5130,
"text": "outputters − To define the list of available report outputters. Cardinality: 0..1"
},
{
"code": null,
"e": 5283,
"s": 5212,
"text": "statuses − To define the list of available statuses. Cardinality: 0..1"
},
{
"code": null,
"e": 5354,
"s": 5283,
"text": "statuses − To define the list of available statuses. Cardinality: 0..1"
},
{
"code": null,
"e": 5389,
"s": 5354,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5408,
"s": 5389,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5443,
"s": 5408,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5464,
"s": 5443,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5497,
"s": 5464,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5510,
"s": 5497,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5545,
"s": 5510,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5563,
"s": 5545,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5596,
"s": 5563,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5614,
"s": 5596,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5647,
"s": 5614,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5665,
"s": 5647,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5672,
"s": 5665,
"text": " Print"
},
{
"code": null,
"e": 5683,
"s": 5672,
"text": " Add Notes"
}
] |
Make an Ordered list with Bootstrap | For ordered list in Bootstrap, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap lists</title>
<meta name = "viewport" content = "width=device-width, initial-scale = 1">
<link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Lists</h1>
<h2>Fruits (Ordered List)</h2>
<ol>
<li>Kiwi</li>
<li>Apple</li>
<li>Mango</li>
</ol>
</body>
</html> | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "For ordered list in Bootstrap, you can try to run the following code −"
},
{
"code": null,
"e": 1144,
"s": 1133,
"text": " Live Demo"
},
{
"code": null,
"e": 1799,
"s": 1144,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap lists</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h1>Lists</h1>\n <h2>Fruits (Ordered List)</h2>\n <ol>\n <li>Kiwi</li>\n <li>Apple</li>\n <li>Mango</li>\n </ol>\n </body>\n</html>"
}
] |
PyTorch – How to get the exponents of tensor elements? | To find the exponential of the elements of an input tensor, we can apply
Tensor.exp() or torch.exp(input). Here, input is the input tensor for
which the exponentials are computed. Both the methods return a new
tensor with the exponential values of the elements of the input tensor.
Tensor.exp()
or
torch.exp(input)
We could use the following steps to compute the exponentials of the
elements of an input tensor −
Import the torch library. Make sure you have it already installed.
import torch
Create a tensor and print it.
t1 = torch.rand(4,3)
print("Tensor:", t1)
Compute the exponential of the elements of the tensor. For this, use torch.exp(input) and optionally assign this value to a new variable.
exp_t1 = torch.exp(t1)
Print the resultant tensor.
print("Exponentials of elements:\n", exp_t1)
The following Python program shows how to compute the exponentials of
the elements of an input tensor.
# import torch library
import torch
# create a tensor
t1 = torch.tensor([1,2,3,4,5])
# display the tensor
print("Tensor t1:\n", t1)
# Compute the exponential of the elements of the tensor
exp_t1 = t1.exp()
print("Exponential of t1:\n",exp_t1)
# create another tensor
t2 = torch.randn(2,3)
print("Tensor t2:\n", t2)
# Compute the exponential of the elements of the above tensor
exp_t2 = t2.exp()
print("Exponential of t2:\n",exp_t2)
Tensor t1:
tensor([1, 2, 3, 4, 5])
Exponential of t1:
tensor([ 2.7183, 7.3891, 20.0855, 54.5981, 148.4132])
Tensor t2:
tensor([[ 0.2986, 0.0348, 2.1201],
[-0.4488, -0.2205, 0.5417]])
Exponential of t2:
tensor([[1.3480, 1.0354, 8.3319],
[0.6384, 0.8021, 1.7189]])
# import torch library
import torch
# create a tensor
t1 = torch.tensor([[1,2,3],[4,5,6]])
# display the tensor
print("Tensor t1:\n", t1)
# Other way to compute the exponential of the elements
exp_t1 = torch.exp(t1)
print("Exponential of t1:\n",exp_t1)
# create another tensor
t2 = torch.randn(4,3)
print("Tensor t2:\n", t2)
# compute the exponential of the elements of the tensor
exp_t2 = torch.exp(t2)
print("Exponential of t2:\n",exp_t2)
Tensor t1:
tensor([[1, 2, 3],
[4, 5, 6]])
Exponential of t1:
tensor([[ 2.7183, 7.3891, 20.0855],
[ 54.5981, 148.4132, 403.4288]])
Tensor t2:
tensor([[ 1.3574, -0.3132, 0.9117],
[-0.4421, 1.4100, -0.9875],
[ 0.1515, 0.1374, -0.6713],
[ 1.1636, -0.1663, -1.1224]])
Exponential of t2:
tensor([[3.8862, 0.7311, 2.4884],
[0.6427, 4.0959, 0.3725],
[1.1636, 1.1473, 0.5110],
[3.2014, 0.8468, 0.3255]]) | [
{
"code": null,
"e": 1344,
"s": 1062,
"text": "To find the exponential of the elements of an input tensor, we can apply\nTensor.exp() or torch.exp(input). Here, input is the input tensor for\nwhich the exponentials are computed. Both the methods return a new\ntensor with the exponential values of the elements of the input tensor."
},
{
"code": null,
"e": 1357,
"s": 1344,
"text": "Tensor.exp()"
},
{
"code": null,
"e": 1360,
"s": 1357,
"text": "or"
},
{
"code": null,
"e": 1378,
"s": 1360,
"text": "torch.exp(input)\n"
},
{
"code": null,
"e": 1476,
"s": 1378,
"text": "We could use the following steps to compute the exponentials of the\nelements of an input tensor −"
},
{
"code": null,
"e": 1543,
"s": 1476,
"text": "Import the torch library. Make sure you have it already installed."
},
{
"code": null,
"e": 1556,
"s": 1543,
"text": "import torch"
},
{
"code": null,
"e": 1586,
"s": 1556,
"text": "Create a tensor and print it."
},
{
"code": null,
"e": 1628,
"s": 1586,
"text": "t1 = torch.rand(4,3)\nprint(\"Tensor:\", t1)"
},
{
"code": null,
"e": 1766,
"s": 1628,
"text": "Compute the exponential of the elements of the tensor. For this, use torch.exp(input) and optionally assign this value to a new variable."
},
{
"code": null,
"e": 1790,
"s": 1766,
"text": "exp_t1 = torch.exp(t1)\n"
},
{
"code": null,
"e": 1818,
"s": 1790,
"text": "Print the resultant tensor."
},
{
"code": null,
"e": 1863,
"s": 1818,
"text": "print(\"Exponentials of elements:\\n\", exp_t1)"
},
{
"code": null,
"e": 1966,
"s": 1863,
"text": "The following Python program shows how to compute the exponentials of\nthe elements of an input tensor."
},
{
"code": null,
"e": 2403,
"s": 1966,
"text": "# import torch library\nimport torch\n\n# create a tensor\nt1 = torch.tensor([1,2,3,4,5])\n\n# display the tensor\nprint(\"Tensor t1:\\n\", t1)\n\n# Compute the exponential of the elements of the tensor\nexp_t1 = t1.exp()\nprint(\"Exponential of t1:\\n\",exp_t1)\n\n# create another tensor\nt2 = torch.randn(2,3)\nprint(\"Tensor t2:\\n\", t2)\n\n# Compute the exponential of the elements of the above tensor\nexp_t2 = t2.exp()\nprint(\"Exponential of t2:\\n\",exp_t2)"
},
{
"code": null,
"e": 2676,
"s": 2403,
"text": "Tensor t1:\n tensor([1, 2, 3, 4, 5])\nExponential of t1:\n tensor([ 2.7183, 7.3891, 20.0855, 54.5981, 148.4132])\nTensor t2:\n tensor([[ 0.2986, 0.0348, 2.1201],\n [-0.4488, -0.2205, 0.5417]])\nExponential of t2:\n tensor([[1.3480, 1.0354, 8.3319],\n [0.6384, 0.8021, 1.7189]])"
},
{
"code": null,
"e": 3122,
"s": 2676,
"text": "# import torch library\nimport torch\n\n# create a tensor\nt1 = torch.tensor([[1,2,3],[4,5,6]])\n\n# display the tensor\nprint(\"Tensor t1:\\n\", t1)\n\n# Other way to compute the exponential of the elements\nexp_t1 = torch.exp(t1)\nprint(\"Exponential of t1:\\n\",exp_t1)\n\n# create another tensor\nt2 = torch.randn(4,3)\nprint(\"Tensor t2:\\n\", t2)\n\n# compute the exponential of the elements of the tensor\nexp_t2 = torch.exp(t2)\nprint(\"Exponential of t2:\\n\",exp_t2)"
},
{
"code": null,
"e": 3545,
"s": 3122,
"text": "Tensor t1:\n tensor([[1, 2, 3],\n [4, 5, 6]])\nExponential of t1:\n tensor([[ 2.7183, 7.3891, 20.0855],\n [ 54.5981, 148.4132, 403.4288]])\nTensor t2:\n tensor([[ 1.3574, -0.3132, 0.9117],\n [-0.4421, 1.4100, -0.9875],\n [ 0.1515, 0.1374, -0.6713],\n [ 1.1636, -0.1663, -1.1224]])\nExponential of t2:\n tensor([[3.8862, 0.7311, 2.4884],\n [0.6427, 4.0959, 0.3725],\n [1.1636, 1.1473, 0.5110],\n [3.2014, 0.8468, 0.3255]])"
}
] |
GATE | GATE CS 2012 | Question 8 - GeeksforGeeks | 28 Jun, 2021
A process executes the code
fork();
fork();
fork();
The total number of child processes created is(A) 3(B) 4(C) 7(D) 8Answer: (C)Explanation: Let us put some label names for the three lines
fork (); // Line 1
fork (); // Line 2
fork (); // Line 3
L1 // There will be 1 child process created by line 1
/ \
L2 L2 // There will be 2 child processes created by line 2
/ \ / \
L3 L3 L3 L3 // There will be 4 child processes created by line 3
We can also use direct formula to get the number of child processes. With n fork statements, there are always 2^n – 1 child processes. Also see this post for more details.Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63 | [
{
"code": null,
"e": 24044,
"s": 24016,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24072,
"s": 24044,
"text": "A process executes the code"
},
{
"code": null,
"e": 24097,
"s": 24072,
"text": "fork();\nfork();\nfork(); "
},
{
"code": null,
"e": 24235,
"s": 24097,
"text": "The total number of child processes created is(A) 3(B) 4(C) 7(D) 8Answer: (C)Explanation: Let us put some label names for the three lines"
},
{
"code": null,
"e": 24537,
"s": 24235,
"text": " fork (); // Line 1\n fork (); // Line 2\n fork (); // Line 3\n\n L1 // There will be 1 child process created by line 1\n / \\\n L2 L2 // There will be 2 child processes created by line 2\n / \\ / \\\nL3 L3 L3 L3 // There will be 4 child processes created by line 3"
},
{
"code": null,
"e": 24730,
"s": 24537,
"text": "We can also use direct formula to get the number of child processes. With n fork statements, there are always 2^n – 1 child processes. Also see this post for more details.Quiz of this Question"
},
{
"code": null,
"e": 24743,
"s": 24730,
"text": "GATE-CS-2012"
},
{
"code": null,
"e": 24761,
"s": 24743,
"text": "GATE-GATE CS 2012"
},
{
"code": null,
"e": 24766,
"s": 24761,
"text": "GATE"
},
{
"code": null,
"e": 24864,
"s": 24766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24873,
"s": 24864,
"text": "Comments"
},
{
"code": null,
"e": 24886,
"s": 24873,
"text": "Old Comments"
},
{
"code": null,
"e": 24920,
"s": 24886,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 24953,
"s": 24920,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 24995,
"s": 24953,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25029,
"s": 24995,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25071,
"s": 25029,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25113,
"s": 25071,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25155,
"s": 25113,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25189,
"s": 25155,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25223,
"s": 25189,
"text": "GATE | GATE-IT-2004 | Question 83"
}
] |
How to find the union of two vectors in R? | The union of vectors return all the unique values in both the vectors. For example, if we have a vector x that contains 1, 2, 3, 4, 2, 3, 4, 1, 1, 4 and another vector that contains 2, 1, 2, 4, 5, 7, 5, 1, 2, 3, 7, 6, 5, 7, 4, 2, 4, 1, 5, 8, 1, 3 then the union of these two vectors will be 1, 2, 3, 4, 5, 6, 7, 8. In R, we can do this by using union function.
Live Demo
> x1<-rpois(10,2)
> x1
[1] 2 2 0 1 1 1 4 1 2 2
Live Demo
> y1<-rpois(10,5)
> y1
[1] 3 5 6 6 10 3 5 9 3 8
> union(x1,y1)
[1] 2 0 1 4 3 5 6 10 9 8
Live Demo
> x2<-rpois(100,5)
> x2
[1] 10 5 5 5 4 7 9 3 7 3 5 5 3 3 5 4 4 4 3 6 8 6 5 4 4
[26] 4 2 7 6 9 2 3 3 7 3 1 2 6 3 1 6 8 5 7 5 7 5 4 9 7
[51] 4 8 9 2 4 5 4 11 8 6 2 5 1 1 4 5 2 6 3 5 5 6 8 8 6
[76] 3 6 6 7 7 5 3 5 4 10 3 9 3 3 7 5 6 5 9 2 6 10 4 1 4
Live Demo
> y2<-rpois(100,10)
> y2
[1] 8 9 10 11 7 11 7 8 17 11 17 13 6 10 7 6 11 15 7 13 6 9 7 7 4
[26] 18 7 12 8 8 12 16 10 11 11 5 15 9 7 12 7 10 3 8 11 7 9 14 11 10
[51] 11 10 8 11 8 8 6 7 11 8 11 13 8 9 5 19 16 9 8 14 16 6 9 6 9
[76] 10 14 11 11 10 5 11 6 10 11 10 7 11 9 17 12 5 11 8 11 10 13 15 5 10
> union(x2,y2)
[1] 10 5 4 7 9 3 6 8 2 1 11 17 13 15 18 12 16 14 19
Live Demo
> x3<-sample(0:9,200,replace=TRUE)
> x3
[1] 1 7 1 7 5 9 2 6 5 8 8 2 5 1 1 7 5 0 0 4 7 3 9 6 4 2 0 8 8 0 9 9 5 4 0 2 5
[38] 0 0 7 0 0 3 0 5 1 2 1 5 1 7 2 8 8 5 7 8 4 8 2 1 8 9 3 9 9 2 8 1 3 3 2 5 2
[75] 7 4 6 0 4 0 2 6 2 9 2 9 7 2 9 4 7 4 2 0 2 9 7 7 5 4 1 8 6 9 2 3 0 9 7 2 3
[112] 9 8 2 4 2 8 9 6 7 2 2 7 2 6 7 4 6 0 7 6 6 3 9 6 2 4 7 4 2 2 7 6 3 8 4 4 2
[149] 0 6 6 5 3 0 8 0 0 6 0 6 1 4 4 5 1 2 4 8 0 5 7 1 8 2 2 5 6 5 2 0 2 5 4 7 2
[186] 9 3 3 2 2 2 0 0 3 8 1 0 0 0 6
Live Demo
> y3<-sample(1:50,200,replace=TRUE)
> y3
[1] 2 31 7 14 40 15 14 21 21 16 5 26 21 44 11 18 40 25 5 42 38 45 28 42 4
[26] 19 35 16 32 8 32 33 34 16 44 23 19 11 5 16 12 13 35 7 17 17 16 35 36 32
[51] 17 31 33 13 12 20 48 43 21 36 23 35 21 22 23 1 48 45 27 49 48 42 41 3 37
[76] 2 12 34 16 41 32 39 13 13 37 29 50 22 45 28 12 19 10 31 49 37 20 23 27 33
[101] 20 10 27 33 7 5 35 15 10 7 34 12 1 46 12 2 2 36 13 29 45 4 36 1 27
[126] 42 8 34 24 11 45 39 39 33 12 41 41 45 6 2 16 40 39 14 32 7 29 12 13 16
[151] 33 3 30 2 35 6 33 30 43 25 34 42 38 4 24 40 15 45 18 41 10 9 24 4 42
[176] 11 32 14 8 49 47 6 38 45 20 30 48 26 17 49 34 24 12 31 24 26 3 13 9 6
> union(x3,y3)
[1] 1 7 5 9 2 6 8 0 4 3 31 14 40 15 21 16 26 44 11 18 25 42 38 45 28
[26] 19 35 32 33 34 23 12 13 17 36 20 48 43 22 27 49 41 37 39 29 50 10 46 24 30
[51] 47
Live Demo
> x4<-round(runif(200,2,4))
> x4
[1] 3 3 4 4 4 2 2 3 2 4 4 3 4 2 3 3 3 4 4 3 3 3 3 3 2 4 4 3 3 3 4 3 4 3 4 3 3
[38] 2 3 3 3 3 2 4 2 4 2 3 2 2 3 3 4 3 3 4 3 3 2 2 3 3 3 4 2 3 4 3 3 3 4 3 3 4
[75] 4 4 3 3 3 3 2 3 3 3 3 3 4 2 3 3 2 2 4 3 2 3 3 3 3 2 2 3 3 3 2 2 3 4 3 2 3
[112] 3 2 4 3 3 3 4 3 3 3 3 3 3 4 4 3 3 3 3 4 4 3 4 2 4 4 3 2 2 3 2 3 2 2 3 4 3
[149] 3 2 4 3 2 3 3 3 3 3 4 3 2 2 3 2 4 3 2 3 3 2 4 4 4 3 3 3 2 3 3 3 3 3 3 2 3
[186] 3 3 3 4 4 4 2 4 2 4 4 4 2 4 3
Live Demo
> y4<-round(runif(200,2,10))
> y4
[1] 9 6 3 5 6 2 8 3 9 5 6 4 4 7 6 5 8 3 7 4 5 7 6 7 4
[26] 9 3 10 9 3 6 5 9 3 5 6 3 7 3 2 7 8 7 3 8 8 10 6 6 10
[51] 5 7 3 7 6 9 6 7 9 5 3 8 5 8 5 10 3 9 5 10 7 6 5 9 4
[76] 8 10 6 6 8 6 5 10 7 3 9 4 5 10 5 10 3 2 5 8 3 3 5 9 9
[101] 6 5 8 9 9 6 5 3 6 8 3 4 3 9 10 9 7 2 9 10 2 10 10 8 4
[126] 9 9 5 7 2 4 8 7 8 8 3 9 3 7 5 8 3 8 5 9 4 8 8 10 2
[151] 4 3 10 5 4 4 6 6 3 7 6 6 6 9 3 2 6 2 3 2 4 2 7 5 3
[176] 4 3 9 4 2 7 9 7 10 8 8 2 6 3 4 9 6 10 6 2 3 9 5 9 7
Live Demo
> union(x3,y4)
[1] 1 7 5 9 2 6 8 0 4 3 10
Live Demo
> x5<-round(runif(200,0,20))
> x5
[1] 1 20 11 4 19 5 8 19 0 14 1 5 1 3 8 18 2 9 0 12 1 15 7 15 4
[26] 18 6 6 2 18 0 18 11 18 7 6 14 15 8 7 0 18 12 15 7 20 2 10 13 5
[51] 14 19 1 17 7 18 12 9 3 10 3 8 2 1 15 7 4 14 0 15 5 8 12 9 16
[76] 12 9 16 5 10 7 14 17 16 9 10 16 9 14 5 17 8 8 2 18 1 18 14 3 2
[101] 6 7 9 19 20 13 1 9 9 16 4 5 1 1 16 2 8 10 5 4 15 6 11 6 18
[126] 17 7 0 15 13 16 13 19 2 19 16 18 9 13 20 3 4 3 18 1 8 13 19 6 7
[151] 8 18 13 12 11 18 18 11 12 7 1 12 2 17 15 6 13 11 13 2 12 10 7 5 15
[176] 18 8 2 17 4 1 8 17 15 12 2 4 9 13 0 13 12 3 3 11 4 15 5 1 5
Live Demo
> y5<-round(runif(200,18,30))
> y5
[1] 23 18 24 29 20 22 22 23 28 26 23 28 27 22 19 25 23 27 28 27 23 25 29 19 25
[26] 25 27 27 24 30 24 20 29 27 27 27 19 18 21 23 19 19 27 27 22 25 27 19 28 23
[51] 27 25 24 24 19 21 19 24 30 21 26 19 20 24 30 23 19 25 19 29 23 25 21 20 25
[76] 29 22 29 19 19 24 24 29 23 27 22 25 20 26 23 24 30 28 19 26 22 24 19 19 24
[101] 28 24 24 26 29 26 29 22 22 21 24 30 27 25 28 21 22 21 28 23 25 23 20 22 23
[126] 25 21 20 24 26 18 29 25 18 19 21 18 18 28 30 22 30 26 28 19 27 20 26 21 20
[151] 18 25 21 20 26 30 25 22 22 22 22 25 23 19 22 25 27 25 19 19 29 19 24 30 18
[176] 26 20 19 24 20 25 20 27 28 28 20 26 20 28 21 29 25 25 25 20 24 28 30 23 20
Live Demo
> union(x5,y5)
[1] 1 20 11 4 19 5 8 0 14 3 18 2 9 12 15 7 6 10 13 17 16 23 24 29 22
[26] 28 26 27 25 30 21 | [
{
"code": null,
"e": 1423,
"s": 1062,
"text": "The union of vectors return all the unique values in both the vectors. For example, if we have a vector x that contains 1, 2, 3, 4, 2, 3, 4, 1, 1, 4 and another vector that contains 2, 1, 2, 4, 5, 7, 5, 1, 2, 3, 7, 6, 5, 7, 4, 2, 4, 1, 5, 8, 1, 3 then the union of these two vectors will be 1, 2, 3, 4, 5, 6, 7, 8. In R, we can do this by using union function."
},
{
"code": null,
"e": 1433,
"s": 1423,
"text": "Live Demo"
},
{
"code": null,
"e": 1456,
"s": 1433,
"text": "> x1<-rpois(10,2)\n> x1"
},
{
"code": null,
"e": 1480,
"s": 1456,
"text": "[1] 2 2 0 1 1 1 4 1 2 2"
},
{
"code": null,
"e": 1490,
"s": 1480,
"text": "Live Demo"
},
{
"code": null,
"e": 1513,
"s": 1490,
"text": "> y1<-rpois(10,5)\n> y1"
},
{
"code": null,
"e": 1538,
"s": 1513,
"text": "[1] 3 5 6 6 10 3 5 9 3 8"
},
{
"code": null,
"e": 1553,
"s": 1538,
"text": "> union(x1,y1)"
},
{
"code": null,
"e": 1578,
"s": 1553,
"text": "[1] 2 0 1 4 3 5 6 10 9 8"
},
{
"code": null,
"e": 1588,
"s": 1578,
"text": "Live Demo"
},
{
"code": null,
"e": 1612,
"s": 1588,
"text": "> x2<-rpois(100,5)\n> x2"
},
{
"code": null,
"e": 1835,
"s": 1612,
"text": "[1] 10 5 5 5 4 7 9 3 7 3 5 5 3 3 5 4 4 4 3 6 8 6 5 4 4\n[26] 4 2 7 6 9 2 3 3 7 3 1 2 6 3 1 6 8 5 7 5 7 5 4 9 7\n[51] 4 8 9 2 4 5 4 11 8 6 2 5 1 1 4 5 2 6 3 5 5 6 8 8 6\n[76] 3 6 6 7 7 5 3 5 4 10 3 9 3 3 7 5 6 5 9 2 6 10 4 1 4"
},
{
"code": null,
"e": 1845,
"s": 1835,
"text": "Live Demo"
},
{
"code": null,
"e": 1870,
"s": 1845,
"text": "> y2<-rpois(100,10)\n> y2"
},
{
"code": null,
"e": 2142,
"s": 1870,
"text": "[1] 8 9 10 11 7 11 7 8 17 11 17 13 6 10 7 6 11 15 7 13 6 9 7 7 4\n[26] 18 7 12 8 8 12 16 10 11 11 5 15 9 7 12 7 10 3 8 11 7 9 14 11 10\n[51] 11 10 8 11 8 8 6 7 11 8 11 13 8 9 5 19 16 9 8 14 16 6 9 6 9\n[76] 10 14 11 11 10 5 11 6 10 11 10 7 11 9 17 12 5 11 8 11 10 13 15 5 10"
},
{
"code": null,
"e": 2157,
"s": 2142,
"text": "> union(x2,y2)"
},
{
"code": null,
"e": 2209,
"s": 2157,
"text": "[1] 10 5 4 7 9 3 6 8 2 1 11 17 13 15 18 12 16 14 19"
},
{
"code": null,
"e": 2219,
"s": 2209,
"text": "Live Demo"
},
{
"code": null,
"e": 2259,
"s": 2219,
"text": "> x3<-sample(0:9,200,replace=TRUE)\n> x3"
},
{
"code": null,
"e": 2691,
"s": 2259,
"text": "[1] 1 7 1 7 5 9 2 6 5 8 8 2 5 1 1 7 5 0 0 4 7 3 9 6 4 2 0 8 8 0 9 9 5 4 0 2 5\n[38] 0 0 7 0 0 3 0 5 1 2 1 5 1 7 2 8 8 5 7 8 4 8 2 1 8 9 3 9 9 2 8 1 3 3 2 5 2\n[75] 7 4 6 0 4 0 2 6 2 9 2 9 7 2 9 4 7 4 2 0 2 9 7 7 5 4 1 8 6 9 2 3 0 9 7 2 3\n[112] 9 8 2 4 2 8 9 6 7 2 2 7 2 6 7 4 6 0 7 6 6 3 9 6 2 4 7 4 2 2 7 6 3 8 4 4 2\n[149] 0 6 6 5 3 0 8 0 0 6 0 6 1 4 4 5 1 2 4 8 0 5 7 1 8 2 2 5 6 5 2 0 2 5 4 7 2\n[186] 9 3 3 2 2 2 0 0 3 8 1 0 0 0 6"
},
{
"code": null,
"e": 2701,
"s": 2691,
"text": "Live Demo"
},
{
"code": null,
"e": 2742,
"s": 2701,
"text": "> y3<-sample(1:50,200,replace=TRUE)\n> y3"
},
{
"code": null,
"e": 3351,
"s": 2742,
"text": "[1] 2 31 7 14 40 15 14 21 21 16 5 26 21 44 11 18 40 25 5 42 38 45 28 42 4\n[26] 19 35 16 32 8 32 33 34 16 44 23 19 11 5 16 12 13 35 7 17 17 16 35 36 32\n[51] 17 31 33 13 12 20 48 43 21 36 23 35 21 22 23 1 48 45 27 49 48 42 41 3 37\n[76] 2 12 34 16 41 32 39 13 13 37 29 50 22 45 28 12 19 10 31 49 37 20 23 27 33\n[101] 20 10 27 33 7 5 35 15 10 7 34 12 1 46 12 2 2 36 13 29 45 4 36 1 27\n[126] 42 8 34 24 11 45 39 39 33 12 41 41 45 6 2 16 40 39 14 32 7 29 12 13 16\n[151] 33 3 30 2 35 6 33 30 43 25 34 42 38 4 24 40 15 45 18 41 10 9 24 4 42\n[176] 11 32 14 8 49 47 6 38 45 20 30 48 26 17 49 34 24 12 31 24 26 3 13 9 6"
},
{
"code": null,
"e": 3366,
"s": 3351,
"text": "> union(x3,y3)"
},
{
"code": null,
"e": 3523,
"s": 3366,
"text": "[1] 1 7 5 9 2 6 8 0 4 3 31 14 40 15 21 16 26 44 11 18 25 42 38 45 28\n[26] 19 35 32 33 34 23 12 13 17 36 20 48 43 22 27 49 41 37 39 29 50 10 46 24 30\n[51] 47"
},
{
"code": null,
"e": 3533,
"s": 3523,
"text": "Live Demo"
},
{
"code": null,
"e": 3566,
"s": 3533,
"text": "> x4<-round(runif(200,2,4))\n> x4"
},
{
"code": null,
"e": 3998,
"s": 3566,
"text": "[1] 3 3 4 4 4 2 2 3 2 4 4 3 4 2 3 3 3 4 4 3 3 3 3 3 2 4 4 3 3 3 4 3 4 3 4 3 3\n[38] 2 3 3 3 3 2 4 2 4 2 3 2 2 3 3 4 3 3 4 3 3 2 2 3 3 3 4 2 3 4 3 3 3 4 3 3 4\n[75] 4 4 3 3 3 3 2 3 3 3 3 3 4 2 3 3 2 2 4 3 2 3 3 3 3 2 2 3 3 3 2 2 3 4 3 2 3\n[112] 3 2 4 3 3 3 4 3 3 3 3 3 3 4 4 3 3 3 3 4 4 3 4 2 4 4 3 2 2 3 2 3 2 2 3 4 3\n[149] 3 2 4 3 2 3 3 3 3 3 4 3 2 2 3 2 4 3 2 3 3 2 4 4 4 3 3 3 2 3 3 3 3 3 3 2 3\n[186] 3 3 3 4 4 4 2 4 2 4 4 4 2 4 3"
},
{
"code": null,
"e": 4008,
"s": 3998,
"text": "Live Demo"
},
{
"code": null,
"e": 4042,
"s": 4008,
"text": "> y4<-round(runif(200,2,10))\n> y4"
},
{
"code": null,
"e": 4502,
"s": 4042,
"text": "[1] 9 6 3 5 6 2 8 3 9 5 6 4 4 7 6 5 8 3 7 4 5 7 6 7 4\n[26] 9 3 10 9 3 6 5 9 3 5 6 3 7 3 2 7 8 7 3 8 8 10 6 6 10\n[51] 5 7 3 7 6 9 6 7 9 5 3 8 5 8 5 10 3 9 5 10 7 6 5 9 4\n[76] 8 10 6 6 8 6 5 10 7 3 9 4 5 10 5 10 3 2 5 8 3 3 5 9 9\n[101] 6 5 8 9 9 6 5 3 6 8 3 4 3 9 10 9 7 2 9 10 2 10 10 8 4\n[126] 9 9 5 7 2 4 8 7 8 8 3 9 3 7 5 8 3 8 5 9 4 8 8 10 2\n[151] 4 3 10 5 4 4 6 6 3 7 6 6 6 9 3 2 6 2 3 2 4 2 7 5 3\n[176] 4 3 9 4 2 7 9 7 10 8 8 2 6 3 4 9 6 10 6 2 3 9 5 9 7"
},
{
"code": null,
"e": 4512,
"s": 4502,
"text": "Live Demo"
},
{
"code": null,
"e": 4527,
"s": 4512,
"text": "> union(x3,y4)"
},
{
"code": null,
"e": 4554,
"s": 4527,
"text": "[1] 1 7 5 9 2 6 8 0 4 3 10"
},
{
"code": null,
"e": 4564,
"s": 4554,
"text": "Live Demo"
},
{
"code": null,
"e": 4598,
"s": 4564,
"text": "> x5<-round(runif(200,0,20))\n> x5"
},
{
"code": null,
"e": 5137,
"s": 4598,
"text": "[1] 1 20 11 4 19 5 8 19 0 14 1 5 1 3 8 18 2 9 0 12 1 15 7 15 4\n[26] 18 6 6 2 18 0 18 11 18 7 6 14 15 8 7 0 18 12 15 7 20 2 10 13 5\n[51] 14 19 1 17 7 18 12 9 3 10 3 8 2 1 15 7 4 14 0 15 5 8 12 9 16\n[76] 12 9 16 5 10 7 14 17 16 9 10 16 9 14 5 17 8 8 2 18 1 18 14 3 2\n[101] 6 7 9 19 20 13 1 9 9 16 4 5 1 1 16 2 8 10 5 4 15 6 11 6 18\n[126] 17 7 0 15 13 16 13 19 2 19 16 18 9 13 20 3 4 3 18 1 8 13 19 6 7\n[151] 8 18 13 12 11 18 18 11 12 7 1 12 2 17 15 6 13 11 13 2 12 10 7 5 15\n[176] 18 8 2 17 4 1 8 17 15 12 2 4 9 13 0 13 12 3 3 11 4 15 5 1 5"
},
{
"code": null,
"e": 5147,
"s": 5137,
"text": "Live Demo"
},
{
"code": null,
"e": 5182,
"s": 5147,
"text": "> y5<-round(runif(200,18,30))\n> y5"
},
{
"code": null,
"e": 5825,
"s": 5182,
"text": "[1] 23 18 24 29 20 22 22 23 28 26 23 28 27 22 19 25 23 27 28 27 23 25 29 19 25\n[26] 25 27 27 24 30 24 20 29 27 27 27 19 18 21 23 19 19 27 27 22 25 27 19 28 23\n[51] 27 25 24 24 19 21 19 24 30 21 26 19 20 24 30 23 19 25 19 29 23 25 21 20 25\n[76] 29 22 29 19 19 24 24 29 23 27 22 25 20 26 23 24 30 28 19 26 22 24 19 19 24\n[101] 28 24 24 26 29 26 29 22 22 21 24 30 27 25 28 21 22 21 28 23 25 23 20 22 23\n[126] 25 21 20 24 26 18 29 25 18 19 21 18 18 28 30 22 30 26 28 19 27 20 26 21 20\n[151] 18 25 21 20 26 30 25 22 22 22 22 25 23 19 22 25 27 25 19 19 29 19 24 30 18\n[176] 26 20 19 24 20 25 20 27 28 28 20 26 20 28 21 29 25 25 25 20 24 28 30 23 20"
},
{
"code": null,
"e": 5835,
"s": 5825,
"text": "Live Demo"
},
{
"code": null,
"e": 5850,
"s": 5835,
"text": "> union(x5,y5)"
},
{
"code": null,
"e": 5942,
"s": 5850,
"text": "[1] 1 20 11 4 19 5 8 0 14 3 18 2 9 12 15 7 6 10 13 17 16 23 24 29 22\n[26] 28 26 27 25 30 21"
}
] |
Java 9 - Process API Improvements | In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process's native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes' liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits.
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
String np = "Not Present";
Process p = pb.start();
ProcessHandle.Info info = p.info();
System.out.printf("Process ID : %s%n", p.pid());
System.out.printf("Command name : %s%n", info.command().orElse(np));
System.out.printf("Command line : %s%n", info.commandLine().orElse(np));
System.out.printf("Start time: %s%n",
info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
.toLocalDateTime().toString()).orElse(np));
System.out.printf("Arguments : %s%n",
info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
System.out.printf("User : %s%n", info.user().orElse(np));
}
}
You will see the following output.
Process ID : 5800
Command name : C:\Windows\System32\notepad.exe
Command line : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2588,
"s": 2109,
"text": "In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process's native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes' liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits."
},
{
"code": null,
"e": 3562,
"s": 2588,
"text": "import java.time.ZoneId;\nimport java.util.stream.Stream;\nimport java.util.stream.Collectors;\nimport java.io.IOException;\n\npublic class Tester {\n public static void main(String[] args) throws IOException {\n ProcessBuilder pb = new ProcessBuilder(\"notepad.exe\");\n String np = \"Not Present\";\n Process p = pb.start();\n ProcessHandle.Info info = p.info();\n System.out.printf(\"Process ID : %s%n\", p.pid());\n System.out.printf(\"Command name : %s%n\", info.command().orElse(np));\n System.out.printf(\"Command line : %s%n\", info.commandLine().orElse(np));\n\n System.out.printf(\"Start time: %s%n\",\n info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())\n .toLocalDateTime().toString()).orElse(np));\n\n System.out.printf(\"Arguments : %s%n\",\n info.arguments().map(a -> Stream.of(a).collect(\n Collectors.joining(\" \"))).orElse(np));\n\n System.out.printf(\"User : %s%n\", info.user().orElse(np));\n } \n}"
},
{
"code": null,
"e": 3597,
"s": 3562,
"text": "You will see the following output."
},
{
"code": null,
"e": 3770,
"s": 3597,
"text": "Process ID : 5800\nCommand name : C:\\Windows\\System32\\notepad.exe\nCommand line : Not Present\nStart time: 2017-11-04T21:35:03.626\nArguments : Not Present\nUser: administrator\n"
},
{
"code": null,
"e": 3803,
"s": 3770,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3819,
"s": 3803,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3852,
"s": 3819,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3868,
"s": 3852,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3903,
"s": 3868,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3917,
"s": 3903,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3951,
"s": 3917,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3965,
"s": 3951,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4002,
"s": 3965,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4017,
"s": 4002,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4050,
"s": 4017,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4069,
"s": 4050,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4076,
"s": 4069,
"text": " Print"
},
{
"code": null,
"e": 4087,
"s": 4076,
"text": " Add Notes"
}
] |
PHP Escaping From HTML | PHP file can have mixed content with code within tags embedded in a HTML document. Code outside tags is ignored by the parser, leaving it to be interpreted by client browser. A HTML document can have multiple blocks of PHP, each inside <?php and ?> tags.
<p>
HTML block
</p>
<?php
//php block
..
..
?>
<p>
HTML block
</p>
<?php
//php block
..
..
?>
<p>
HTML block
</p>
Every time opening PHP tag is encountered, parser starts rendering the output to the client until closing tag is reached. If code consusts of conditional statement, th parser determines which block to be skipped.
Again till another opening tag comes, everything is treated as HTML leaving the browser to process the same.
This description is applicable to all versions of PHP.
Following example shows PHP code embedded in HTML
<html>
<body>
<!..HTML code--!>
<h3>Hello World</h3>
<!-- PHP code --!>
<?php
echo "Hello World in PHP";
?>
<!-- This is HTML code --!>
<p>Hello world again</p>
<?php
echo "Hello World again in PHP";
?>
</body>
</html>
This will produce following result −
Hello World
Hello World in PHP
Hello world again
Hello World again in PHP
Example using mixed HTML and PHP code
<?php $marks=10; ?>
<h1>Using conditional statement</h1>
<?php if ($marks >=50): ?>
<h2 style="color:blue;">Result:pass</p>
<?php else: ?>
<h2 style="color:red;"> Result:Fail</p>
<?php endif; ?>
This will produce following result −
Using conditional statement
Result:Fail
change marks to 60 and run again
Using conditional statement
Result:pass
change marks to 60 and run again
Using conditional statement
Result:pass | [
{
"code": null,
"e": 1317,
"s": 1062,
"text": "PHP file can have mixed content with code within tags embedded in a HTML document. Code outside tags is ignored by the parser, leaving it to be interpreted by client browser. A HTML document can have multiple blocks of PHP, each inside <?php and ?> tags."
},
{
"code": null,
"e": 1431,
"s": 1317,
"text": "<p>\nHTML block\n</p>\n<?php\n//php block\n..\n..\n?>\n<p>\nHTML block\n</p>\n<?php\n//php block\n..\n..\n?>\n<p>\nHTML block\n</p>"
},
{
"code": null,
"e": 1644,
"s": 1431,
"text": "Every time opening PHP tag is encountered, parser starts rendering the output to the client until closing tag is reached. If code consusts of conditional statement, th parser determines which block to be skipped."
},
{
"code": null,
"e": 1753,
"s": 1644,
"text": "Again till another opening tag comes, everything is treated as HTML leaving the browser to process the same."
},
{
"code": null,
"e": 1808,
"s": 1753,
"text": "This description is applicable to all versions of PHP."
},
{
"code": null,
"e": 1858,
"s": 1808,
"text": "Following example shows PHP code embedded in HTML"
},
{
"code": null,
"e": 2077,
"s": 1858,
"text": "<html>\n<body>\n<!..HTML code--!>\n<h3>Hello World</h3>\n<!-- PHP code --!>\n<?php\necho \"Hello World in PHP\";\n?>\n<!-- This is HTML code --!>\n<p>Hello world again</p>\n<?php\necho \"Hello World again in PHP\";\n?>\n</body>\n</html>"
},
{
"code": null,
"e": 2114,
"s": 2077,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2188,
"s": 2114,
"text": "Hello World\nHello World in PHP\nHello world again\nHello World again in PHP"
},
{
"code": null,
"e": 2226,
"s": 2188,
"text": "Example using mixed HTML and PHP code"
},
{
"code": null,
"e": 2421,
"s": 2226,
"text": "<?php $marks=10; ?>\n<h1>Using conditional statement</h1>\n<?php if ($marks >=50): ?>\n<h2 style=\"color:blue;\">Result:pass</p>\n<?php else: ?>\n<h2 style=\"color:red;\"> Result:Fail</p>\n<?php endif; ?>"
},
{
"code": null,
"e": 2458,
"s": 2421,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2571,
"s": 2458,
"text": "Using conditional statement\nResult:Fail\nchange marks to 60 and run again\nUsing conditional statement\nResult:pass"
},
{
"code": null,
"e": 2644,
"s": 2571,
"text": "change marks to 60 and run again\nUsing conditional statement\nResult:pass"
}
] |
How to plot bar graphs with same X coordinates side by side in Matplotlib? | To plot bar graphs with same X coordinates (G1, G2, G3, G4 and G5), side by side in matplotlib, we can take the following steps −
Create the following lists – labels, men_means and women_means with different data elements.
Create the following lists – labels, men_means and women_means with different data elements.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Set the width variable, i.e., width=0.35.
Set the width variable, i.e., width=0.35.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
Set a title for the axes using set_title() method.
Set a title for the axes using set_title() method.
Get or set the current tick locations and labels of the X-axis using set_xticks() method.
Get or set the current tick locations and labels of the X-axis using set_xticks() method.
Set X-axis tick labels of the grid using set_xticklabels() method.
Set X-axis tick labels of the grid using set_xticklabels() method.
Place a legend on the figure using legend() method.
Place a legend on the figure using legend() method.
Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method).
Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method).
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(x - width / 2, men_means, width, label='Men')
rects2 = ax.bar(x + width / 2, women_means, width, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show() | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "To plot bar graphs with same X coordinates (G1, G2, G3, G4 and G5), side by side in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1285,
"s": 1192,
"text": "Create the following lists – labels, men_means and women_means with different data elements."
},
{
"code": null,
"e": 1378,
"s": 1285,
"text": "Create the following lists – labels, men_means and women_means with different data elements."
},
{
"code": null,
"e": 1461,
"s": 1378,
"text": "Return evenly spaced values within a given interval, using numpy.arrange() method."
},
{
"code": null,
"e": 1544,
"s": 1461,
"text": "Return evenly spaced values within a given interval, using numpy.arrange() method."
},
{
"code": null,
"e": 1586,
"s": 1544,
"text": "Set the width variable, i.e., width=0.35."
},
{
"code": null,
"e": 1628,
"s": 1586,
"text": "Set the width variable, i.e., width=0.35."
},
{
"code": null,
"e": 1716,
"s": 1628,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1804,
"s": 1716,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 2013,
"s": 1804,
"text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method."
},
{
"code": null,
"e": 2222,
"s": 2013,
"text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method."
},
{
"code": null,
"e": 2270,
"s": 2222,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 2318,
"s": 2270,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 2369,
"s": 2318,
"text": "Set a title for the axes using set_title() method."
},
{
"code": null,
"e": 2420,
"s": 2369,
"text": "Set a title for the axes using set_title() method."
},
{
"code": null,
"e": 2510,
"s": 2420,
"text": "Get or set the current tick locations and labels of the X-axis using set_xticks() method."
},
{
"code": null,
"e": 2600,
"s": 2510,
"text": "Get or set the current tick locations and labels of the X-axis using set_xticks() method."
},
{
"code": null,
"e": 2667,
"s": 2600,
"text": "Set X-axis tick labels of the grid using set_xticklabels() method."
},
{
"code": null,
"e": 2734,
"s": 2667,
"text": "Set X-axis tick labels of the grid using set_xticklabels() method."
},
{
"code": null,
"e": 2786,
"s": 2734,
"text": "Place a legend on the figure using legend() method."
},
{
"code": null,
"e": 2838,
"s": 2786,
"text": "Place a legend on the figure using legend() method."
},
{
"code": null,
"e": 2946,
"s": 2838,
"text": "Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method)."
},
{
"code": null,
"e": 3054,
"s": 2946,
"text": "Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method)."
},
{
"code": null,
"e": 3101,
"s": 3054,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 3148,
"s": 3101,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 4061,
"s": 3148,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nlabels = ['G1', 'G2', 'G3', 'G4', 'G5']\nmen_means = [20, 34, 30, 35, 27]\nwomen_means = [25, 32, 34, 20, 25]\n\nx = np.arange(len(labels))\nwidth = 0.35\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width / 2, men_means, width, label='Men')\nrects2 = ax.bar(x + width / 2, women_means, width, label='Women')\n\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend()\n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\nautolabel(rects1)\nautolabel(rects2)\n\nplt.show()"
}
] |
Function overloading and const keyword in C++ | In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions.
#include <iostream>
using namespace std;
class my_class {
public:
void my_func() const {
cout << "Calling the constant function" << endl;
}
void my_func() {
cout << "Calling the normal function" << endl;
}
};
int main() {
my_class obj;
const my_class obj_c;
obj.my_func();
obj_c.my_func();
}
Calling the normal function
Calling the constant function
Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called.
If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error.
#include <iostream>
using namespace std;
class my_class {
public:
void my_func(const int x) {
cout << "Calling the function with constant x" << endl;
}
void my_func(int x){
cout << "Calling the function with x" << endl;
}
};
int main() {
my_class obj;
obj.my_func(10);
}
[Error] 'void my_class::my_func(int)' cannot be overloaded
[Error] with 'void my_class::my_func(int)'
But if the arguments are reference or pointer type, then it will not generate error.
#include <iostream>
using namespace std;
class my_class {
public:
void my_func(const int *x) {
cout << "Calling the function with constant x" << endl;
}
void my_func(int *x) {
cout << "Calling the function with x" << endl;
}
};
int main() {
my_class obj;
int x = 10;
obj.my_func(&x);
}
Calling the function with x | [
{
"code": null,
"e": 1273,
"s": 1062,
"text": "In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions."
},
{
"code": null,
"e": 1622,
"s": 1273,
"text": "#include <iostream>\nusing namespace std;\nclass my_class {\n public:\n void my_func() const {\n cout << \"Calling the constant function\" << endl;\n }\n void my_func() {\n cout << \"Calling the normal function\" << endl;\n }\n};\nint main() {\n my_class obj;\n const my_class obj_c;\n obj.my_func();\n obj_c.my_func();\n}"
},
{
"code": null,
"e": 1680,
"s": 1622,
"text": "Calling the normal function\nCalling the constant function"
},
{
"code": null,
"e": 1827,
"s": 1680,
"text": "Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called."
},
{
"code": null,
"e": 1954,
"s": 1827,
"text": "If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error."
},
{
"code": null,
"e": 2276,
"s": 1954,
"text": "#include <iostream>\nusing namespace std;\nclass my_class {\n public:\n void my_func(const int x) {\n cout << \"Calling the function with constant x\" << endl;\n }\n void my_func(int x){\n cout << \"Calling the function with x\" << endl;\n }\n};\nint main() {\n my_class obj;\n obj.my_func(10);\n}"
},
{
"code": null,
"e": 2378,
"s": 2276,
"text": "[Error] 'void my_class::my_func(int)' cannot be overloaded\n[Error] with 'void my_class::my_func(int)'"
},
{
"code": null,
"e": 2463,
"s": 2378,
"text": "But if the arguments are reference or pointer type, then it will not generate error."
},
{
"code": null,
"e": 2803,
"s": 2463,
"text": "#include <iostream>\nusing namespace std;\nclass my_class {\n public:\n void my_func(const int *x) {\n cout << \"Calling the function with constant x\" << endl;\n }\n void my_func(int *x) {\n cout << \"Calling the function with x\" << endl;\n }\n};\nint main() {\n my_class obj;\n int x = 10;\n obj.my_func(&x);\n}"
},
{
"code": null,
"e": 2831,
"s": 2803,
"text": "Calling the function with x"
}
] |
How to draw a star in HTML5 SVG? | SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. For drawing a star in HTML5 SVG, you need to set the x and y coordinates properly for each corner.
You can try to run the following code to learn how to draw a star in HTML5 SVG:
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 10%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>HTML5 SVG Polygon Star</title>
</head>
<body>
<h2>HTML5 SVG Star</h2>
<svg id = "svgelem" width = "300" height = "300" xmlns = "http://www.w3.org/2000/svg">
<polygon points="100,10 40,180 190,60 10,60 160,180" fill="blue"/>
</svg>
</body>
</html> | [
{
"code": null,
"e": 1315,
"s": 1062,
"text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG."
},
{
"code": null,
"e": 1549,
"s": 1315,
"text": "To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. For drawing a star in HTML5 SVG, you need to set the x and y coordinates properly for each corner."
},
{
"code": null,
"e": 1629,
"s": 1549,
"text": "You can try to run the following code to learn how to draw a star in HTML5 SVG:"
},
{
"code": null,
"e": 2250,
"s": 1629,
"text": "<!DOCTYPE html>\n <html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 10%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>HTML5 SVG Polygon Star</title>\n </head>\n <body>\n <h2>HTML5 SVG Star</h2>\n <svg id = \"svgelem\" width = \"300\" height = \"300\" xmlns = \"http://www.w3.org/2000/svg\">\n <polygon points=\"100,10 40,180 190,60 10,60 160,180\" fill=\"blue\"/>\n </svg>\n </body>\n</html>"
}
] |
Python - Remove keys with substring values - GeeksforGeeks | 31 Jan, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed.
Input : test_dict = {1 : ‘Gfg is best for geeks’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {1: ‘Gfg is best for geeks’}Input : test_dict = {1 : ‘Gfg is love’, 2: ‘Gfg is good’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {}
Method #1 : Using any() + loop The combination of above functionalities can be used to solve this problem. In this, we extract all the items from dictionary which do not have desired values, the filtration is performed using any() and generator expression.
Python3
# Python3 code to demonstrate working of# Remove keys with substring values# Using any() + generator expression # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using any() + generator expressionres = dict()for key, val in test_dict.items(): if not any(ele in val for ele in sub_list): res[key] = val # printing resultprint("Filtered Dictionary : " + str(res))
The original dictionary : {1: ‘Gfg is best for geeks’, 2: ‘Gfg is good’, 3: ‘I love Gfg’} Filtered Dictionary : {1: ‘Gfg is best for geeks’}
Method #2 : Using dictionary comprehension + any() The combination of above methods provide the shorthand to execute this task. In this, we perform this task in similar way as above method, but in one liner format using comprehension.
Python3
# Python3 code to demonstrate working of# Remove keys with substring values# Using dictionary comprehension + any() # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using dictionary comprehension + any()res = {key : val for key, val in test_dict.items() if not any(ele in val for ele in sub_list)} # printing resultprint("Filtered Dictionary : " + str(res))
The original dictionary : {1: 'Gfg is best for geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}
adnanirshad158
Python dictionary-programs
Python
Python Programs
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
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": 25555,
"s": 25527,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 25849,
"s": 25555,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 26126,
"s": 25849,
"text": "Input : test_dict = {1 : ‘Gfg is best for geeks’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {1: ‘Gfg is best for geeks’}Input : test_dict = {1 : ‘Gfg is love’, 2: ‘Gfg is good’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {} "
},
{
"code": null,
"e": 26384,
"s": 26126,
"text": "Method #1 : Using any() + loop The combination of above functionalities can be used to solve this problem. In this, we extract all the items from dictionary which do not have desired values, the filtration is performed using any() and generator expression. "
},
{
"code": null,
"e": 26392,
"s": 26384,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove keys with substring values# Using any() + generator expression # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using any() + generator expressionres = dict()for key, val in test_dict.items(): if not any(ele in val for ele in sub_list): res[key] = val # printing resultprint(\"Filtered Dictionary : \" + str(res))",
"e": 26996,
"s": 26392,
"text": null
},
{
"code": null,
"e": 27138,
"s": 26996,
"text": "The original dictionary : {1: ‘Gfg is best for geeks’, 2: ‘Gfg is good’, 3: ‘I love Gfg’} Filtered Dictionary : {1: ‘Gfg is best for geeks’} "
},
{
"code": null,
"e": 27377,
"s": 27140,
"text": " Method #2 : Using dictionary comprehension + any() The combination of above methods provide the shorthand to execute this task. In this, we perform this task in similar way as above method, but in one liner format using comprehension. "
},
{
"code": null,
"e": 27385,
"s": 27377,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove keys with substring values# Using dictionary comprehension + any() # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using dictionary comprehension + any()res = {key : val for key, val in test_dict.items() if not any(ele in val for ele in sub_list)} # printing resultprint(\"Filtered Dictionary : \" + str(res))",
"e": 27978,
"s": 27385,
"text": null
},
{
"code": null,
"e": 28119,
"s": 27978,
"text": "The original dictionary : {1: 'Gfg is best for geeks', 2: 'Gfg is good', 3: 'I love Gfg'}\nFiltered Dictionary : {1: 'Gfg is best for geeks'}"
},
{
"code": null,
"e": 28136,
"s": 28121,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28163,
"s": 28136,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 28170,
"s": 28163,
"text": "Python"
},
{
"code": null,
"e": 28186,
"s": 28170,
"text": "Python Programs"
},
{
"code": null,
"e": 28284,
"s": 28186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28316,
"s": 28284,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28358,
"s": 28316,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28400,
"s": 28358,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28456,
"s": 28400,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28483,
"s": 28456,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28505,
"s": 28483,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28544,
"s": 28505,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28590,
"s": 28544,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28628,
"s": 28590,
"text": "Python | Convert a list to dictionary"
}
] |
Java Program to Convert Integer List to Integer Array - GeeksforGeeks | 17 Jun, 2021
There are many ways to convert integer List to ArrayList where in this article we will be discussing out 2 approaches as below:
Using concept od streams in Java8Using Apache Commons LangUsing Guava Library
Using concept od streams in Java8
Using Apache Commons Lang
Using Guava Library
Method 1: Using concept od streams in Java8
So, first, we will get to know about how to convert integer list to array list using java 8. In java 8 there is a stream provided for converting a list of integer to an integer array.
Procedure:
Convert List<Integer> to Stream<Integer> using List.stream() —> Here List is calling stream() method.
Now we convert Stream<Integer> to int[].
Example:
Java
// Java Program to Convert Integer List to Integer Array // Importing Arrays and List classes// from java.util packageimport java.util.Arrays;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an List of integer type and // customly inserting input elements a arguments List<Integer> list = Arrays.asList(1, 3, 5, 7, 9); // Converting Stream<Integer> to integer array // using stream() and mapToInt() methods, lately // storing them in an integer array int[] primitive = list.stream() .mapToInt(Integer::inValue) .toArray(); // Print and display the integer array System.out.println(Arrays.toString(primitive)); }}
Output:
[1,3,5,7,9]
Method 2: Using Apache Commons Lang
Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints. We need to convert a list of integers to an Integer array first. We can use List.toArray() for easy conversion.
Procedure:
Use toPrimtive() method of Apache Common Lang’sUse List.toArray() method
Use toPrimtive() method of Apache Common Lang’s
Use List.toArray() method
Example:
Java
// Java Program to Convert Integer List to Integer Array // Importing ArrayUtis class// Importing Arrays and List class from java.util packageimport java.util.Arrays;import java.util.List;import org.apache.commons.lang3.ArrayUtils; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List class of integer type List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); // Using toPrimtive() method of Apache Common Lang's int[] primitive = ArrayUtils.toPrimitive( list.toArray(new Integer[0])); // Print and display the integer array System.out.println(Arrays.toString(primitive)); }}
Output:
[1,2,3,4,5]
Method 3: Using Guava Library
Guava library is an open-source decentralized software development model which is a set of common libraries of java providing utility methods for collections, caching, primitives support, concurrency, string processing, and validations. Here we will be glancing at string processing in the guava library by converting integer list to integer array. It is depicted in below example as follows:
Example
Java
// Java Program to Convert List to Integer Array// Using Guava Library // Importing required classesimport com.google.common.primitives.Ints;import java.util.Arrays;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List class of integer type List<Integer> ints = Arrays.asList(3, 7, 8, 6, 1); // Converting a list of Integer to primitive integer // array and storing in integer array int[] primitive = Ints.toArray(ints); // Print and display the integer array via Guava // by converting it to string // via standard toString() method System.out.println(Arrays.toString(primitive)); }}
Output:
3,7,8,6,1
Java-Array-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25250,
"s": 25222,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25378,
"s": 25250,
"text": "There are many ways to convert integer List to ArrayList where in this article we will be discussing out 2 approaches as below:"
},
{
"code": null,
"e": 25456,
"s": 25378,
"text": "Using concept od streams in Java8Using Apache Commons LangUsing Guava Library"
},
{
"code": null,
"e": 25490,
"s": 25456,
"text": "Using concept od streams in Java8"
},
{
"code": null,
"e": 25516,
"s": 25490,
"text": "Using Apache Commons Lang"
},
{
"code": null,
"e": 25536,
"s": 25516,
"text": "Using Guava Library"
},
{
"code": null,
"e": 25580,
"s": 25536,
"text": "Method 1: Using concept od streams in Java8"
},
{
"code": null,
"e": 25764,
"s": 25580,
"text": "So, first, we will get to know about how to convert integer list to array list using java 8. In java 8 there is a stream provided for converting a list of integer to an integer array."
},
{
"code": null,
"e": 25775,
"s": 25764,
"text": "Procedure:"
},
{
"code": null,
"e": 25877,
"s": 25775,
"text": "Convert List<Integer> to Stream<Integer> using List.stream() —> Here List is calling stream() method."
},
{
"code": null,
"e": 25918,
"s": 25877,
"text": "Now we convert Stream<Integer> to int[]."
},
{
"code": null,
"e": 25927,
"s": 25918,
"text": "Example:"
},
{
"code": null,
"e": 25932,
"s": 25927,
"text": "Java"
},
{
"code": "// Java Program to Convert Integer List to Integer Array // Importing Arrays and List classes// from java.util packageimport java.util.Arrays;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an List of integer type and // customly inserting input elements a arguments List<Integer> list = Arrays.asList(1, 3, 5, 7, 9); // Converting Stream<Integer> to integer array // using stream() and mapToInt() methods, lately // storing them in an integer array int[] primitive = list.stream() .mapToInt(Integer::inValue) .toArray(); // Print and display the integer array System.out.println(Arrays.toString(primitive)); }}",
"e": 26762,
"s": 25932,
"text": null
},
{
"code": null,
"e": 26770,
"s": 26762,
"text": "Output:"
},
{
"code": null,
"e": 26782,
"s": 26770,
"text": "[1,3,5,7,9]"
},
{
"code": null,
"e": 26818,
"s": 26782,
"text": "Method 2: Using Apache Commons Lang"
},
{
"code": null,
"e": 27052,
"s": 26818,
"text": "Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints. We need to convert a list of integers to an Integer array first. We can use List.toArray() for easy conversion."
},
{
"code": null,
"e": 27063,
"s": 27052,
"text": "Procedure:"
},
{
"code": null,
"e": 27137,
"s": 27063,
"text": " Use toPrimtive() method of Apache Common Lang’sUse List.toArray() method"
},
{
"code": null,
"e": 27186,
"s": 27137,
"text": " Use toPrimtive() method of Apache Common Lang’s"
},
{
"code": null,
"e": 27212,
"s": 27186,
"text": "Use List.toArray() method"
},
{
"code": null,
"e": 27221,
"s": 27212,
"text": "Example:"
},
{
"code": null,
"e": 27226,
"s": 27221,
"text": "Java"
},
{
"code": "// Java Program to Convert Integer List to Integer Array // Importing ArrayUtis class// Importing Arrays and List class from java.util packageimport java.util.Arrays;import java.util.List;import org.apache.commons.lang3.ArrayUtils; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List class of integer type List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); // Using toPrimtive() method of Apache Common Lang's int[] primitive = ArrayUtils.toPrimitive( list.toArray(new Integer[0])); // Print and display the integer array System.out.println(Arrays.toString(primitive)); }}",
"e": 27940,
"s": 27226,
"text": null
},
{
"code": null,
"e": 27948,
"s": 27940,
"text": "Output:"
},
{
"code": null,
"e": 27960,
"s": 27948,
"text": "[1,2,3,4,5]"
},
{
"code": null,
"e": 27990,
"s": 27960,
"text": "Method 3: Using Guava Library"
},
{
"code": null,
"e": 28383,
"s": 27990,
"text": "Guava library is an open-source decentralized software development model which is a set of common libraries of java providing utility methods for collections, caching, primitives support, concurrency, string processing, and validations. Here we will be glancing at string processing in the guava library by converting integer list to integer array. It is depicted in below example as follows:"
},
{
"code": null,
"e": 28391,
"s": 28383,
"text": "Example"
},
{
"code": null,
"e": 28396,
"s": 28391,
"text": "Java"
},
{
"code": "// Java Program to Convert List to Integer Array// Using Guava Library // Importing required classesimport com.google.common.primitives.Ints;import java.util.Arrays;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List class of integer type List<Integer> ints = Arrays.asList(3, 7, 8, 6, 1); // Converting a list of Integer to primitive integer // array and storing in integer array int[] primitive = Ints.toArray(ints); // Print and display the integer array via Guava // by converting it to string // via standard toString() method System.out.println(Arrays.toString(primitive)); }}",
"e": 29153,
"s": 28396,
"text": null
},
{
"code": null,
"e": 29161,
"s": 29153,
"text": "Output:"
},
{
"code": null,
"e": 29171,
"s": 29161,
"text": "3,7,8,6,1"
},
{
"code": null,
"e": 29191,
"s": 29171,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 29198,
"s": 29191,
"text": "Picked"
},
{
"code": null,
"e": 29203,
"s": 29198,
"text": "Java"
},
{
"code": null,
"e": 29217,
"s": 29203,
"text": "Java Programs"
},
{
"code": null,
"e": 29222,
"s": 29217,
"text": "Java"
},
{
"code": null,
"e": 29320,
"s": 29222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29335,
"s": 29320,
"text": "Stream In Java"
},
{
"code": null,
"e": 29356,
"s": 29335,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29375,
"s": 29356,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29405,
"s": 29375,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29451,
"s": 29405,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29477,
"s": 29451,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29511,
"s": 29477,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29558,
"s": 29511,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29590,
"s": 29558,
"text": "How to Iterate HashMap in Java?"
}
] |
Queries to check if the path between two nodes in a tree is a palindrome - GeeksforGeeks | 03 Sep, 2021
Given a tree with N nodes and N – 1 edges. Each edge of the tree is labeled by a string of lowercase english alphabets. You are given Q queries. In each query you are given two node x and y. For the path between x to y, the task is to check if it is possible to make a new palindrome string which use all the characters in the path from node x to node y. Note that you can use the characters in any order you like and root node is always 1.Examples:
Input:
1
(bbc)/ \(ac)
2 3
Q[][] = {{1, 2}, {2, 3}, {3, 1}, {3, 3}}
Output:
Yes
Yes
No
Yes
Query 1: "bbc" can be arranged into "bcb"
which is a palindrome.
Query 2: "bbcac" -> "bcacb"
Query 3: No permutation of "ac" is palindrome.
Query 4: "acac" -> "acca"
Input:
1
/ | \
/(ab) |(bca) \(bc)
2 3 4
\(ab)
5
Q[][] = {{1, 5}, {4, 5}, {5, 4}}
Output:
Yes
No
No
Approach: For each query, the character count for path x to y has to be calculated. After finding the characters count, it can be easily checked whether the characters will form a palindrome or not using the approach discussed in this article. Steps to get the character count for path x to y.
Set the initial character count for each node.Update character count of the root’s child node and then repeat the same process for its child node.Find LCA (Lowest Common Ancestor) of x and y.Calculate character count for path x to y with the following step: For each character charCount[i] = (xNodeCharCount[i] – lcaNodeCharCount[i]) + (yNodeCharCount[i] – lcaNodeCharCount[i]) Now check whether a palindrome can be formed with the current count of characters.
Set the initial character count for each node.
Update character count of the root’s child node and then repeat the same process for its child node.
Find LCA (Lowest Common Ancestor) of x and y.
Calculate character count for path x to y with the following step: For each character charCount[i] = (xNodeCharCount[i] – lcaNodeCharCount[i]) + (yNodeCharCount[i] – lcaNodeCharCount[i])
Now check whether a palindrome can be formed with the current count of characters.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX_SIZE = 100005, MAX_CHAR = 26;int nodeCharactersCount[MAX_SIZE][MAX_CHAR]; vector<int> tree[MAX_SIZE]; // Function that returns true if a palindromic// string can be formed using the given charactersbool canFormPalindrome(int* charArray){ // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true;} // Find to find the Lowest Common// Ancestor in the treeint LCA(int currentNode, int x, int y){ // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].size(); l++) { // Next node that will be checked int nextNode = tree[currentNode][l]; // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 and yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca;} // Function to calculate the character count for// each path from node i to 1 (root node)void buildTree(int i){ for (int l = 0; l < tree[i].size(); l++) { int nextNode = tree[i][l]; for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); }} // Function that returns true if a palindromic path// is possible between the nodes x and ybool canFormPalindromicPath(int x, int y){ int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int charactersCountFromXtoY[MAX_CHAR] = { 0 }; // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false;} // Function to update character count at node vvoid updateNodeCharactersCount(string str, int v){ // Updating the character count at node v for (int i = 0; i < str.length(); i++) nodeCharactersCount[v][str[i] - 'a']++;} // Function to perform the queriesvoid performQueries(vector<vector<int> > queries, int q){ int i = 0; while (i < q) { int x = queries[i][0]; int y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) cout << "Yes\n"; else cout << "No\n"; i++; }} // Driver codeint main(){ // Fill the complete array with 0 memset(nodeCharactersCount, 0, sizeof(nodeCharactersCount)); // Edge between 1 and 2 labelled "bbc" tree[1].push_back(2); updateNodeCharactersCount("bbc", 2); // Edge between 1 and 3 labelled "ac" tree[1].push_back(3); updateNodeCharactersCount("ac", 3); // Update the character count // from root to the ith node buildTree(1); vector<vector<int> > queries{ { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.size(); // Perform the queries performQueries(queries, q); return 0;}
// Java implementation of the approachimport java.util.*; @SuppressWarnings("unchecked")class GFG { static int MAX_SIZE = 100005, MAX_CHAR = 26; static int[][] nodeCharactersCount = new int[MAX_SIZE][MAX_CHAR]; static Vector<Integer>[] tree = new Vector[MAX_SIZE]; // Function that returns true if a palindromic // string can be formed using the given characters static boolean canFormPalindrome(int[] charArray) { // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree static int LCA(int currentNode, int x, int y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].size(); l++) { // Next node that will be checked int nextNode = tree[currentNode].elementAt(l); // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) static void buildTree(int i) { for (int l = 0; l < tree[i].size(); l++) { int nextNode = tree[i].elementAt(l); for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y static boolean canFormPalindromicPath(int x, int y) { int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int[] charactersCountFromXtoY = new int[MAX_CHAR]; Arrays.fill(charactersCountFromXtoY, 0); // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v static void updateNodeCharactersCount(String str, int v) { // Updating the character count at node v for (int i = 0; i < str.length(); i++) nodeCharactersCount[v][str.charAt(i) - 'a']++; } // Function to perform the queries static void performQueries(int[][] queries, int q) { int i = 0; while (i < q) { int x = queries[i][0]; int y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) System.out.println("Yes"); else System.out.println("No"); i++; } } // Driver Code public static void main(String[] args) { // Fill the complete array with 0 for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_CHAR; j++) { nodeCharactersCount[i][j] = 0; } } for (int i = 0; i < MAX_SIZE; i++) { tree[i] = new Vector<>(); } // Edge between 1 and 2 labelled "bbc" tree[1].add(2); updateNodeCharactersCount("bbc", 2); // Edge between 1 and 3 labelled "ac" tree[1].add(3); updateNodeCharactersCount("ac", 3); // Update the character count // from root to the ith node buildTree(1); int[][] queries = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.length; // Perform the queries performQueries(queries, q); }} // This code is contributed by// sanjeev2552
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ static int MAX_SIZE = 100005, MAX_CHAR = 26; static int[,] nodecharsCount = new int[MAX_SIZE, MAX_CHAR]; static List<int>[] tree = new List<int>[MAX_SIZE]; // Function that returns true if a palindromic // string can be formed using the given characters static bool canFormPalindrome(int[] charArray) { // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree static int LCA(int currentNode, int x, int y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].Count; l++) { // Next node that will be checked int nextNode = tree[currentNode][l]; // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) static void buildTree(int i) { for (int l = 0; l < tree[i].Count; l++) { int nextNode = tree[i][l]; for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodecharsCount[nextNode,j] += nodecharsCount[i,j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y static bool canFormPalindromicPath(int x, int y) { int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int[] charactersCountFromXtoY = new int[MAX_CHAR]; // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodecharsCount[x, i] + nodecharsCount[y, i] - 2 * nodecharsCount[lcaNode, i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v static void updateNodecharsCount(String str, int v) { // Updating the character count at node v for (int i = 0; i < str.Length; i++) nodecharsCount[v, str[i] - 'a']++; } // Function to perform the queries static void performQueries(int[,] queries, int q) { int i = 0; while (i < q) { int x = queries[i, 0]; int y = queries[i, 1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) Console.WriteLine("Yes"); else Console.WriteLine("No"); i++; } } // Driver Code public static void Main(String[] args) { // Fill the complete array with 0 for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_CHAR; j++) { nodecharsCount[i, j] = 0; } } for (int i = 0; i < MAX_SIZE; i++) { tree[i] = new List<int>(); } // Edge between 1 and 2 labelled "bbc" tree[1].Add(2); updateNodecharsCount("bbc", 2); // Edge between 1 and 3 labelled "ac" tree[1].Add(3); updateNodecharsCount("ac", 3); // Update the character count // from root to the ith node buildTree(1); int[,] queries = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.GetLength(0); // Perform the queries performQueries(queries, q); }} // This code is contributed by aashish1995
<script> // JavaScript implementation of the approach let MAX_SIZE = 100005, MAX_CHAR = 26; let nodeCharactersCount = new Array(MAX_SIZE); let tree = new Array(MAX_SIZE); // Function that returns true if a palindromic // string can be formed using the given characters function canFormPalindrome(charArray) { // Count odd occurring characters let oddCount = 0; for (let i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree function LCA(currentNode, x, y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; let xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y let gotLca = -1; // Iterating in the child // substree of the currentNode for (let l = 0; l < tree[currentNode].length; l++) { // Next node that will be checked let nextNode = tree[currentNode][l]; // Look for the next child subtree let out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) function buildTree(i) { for (let l = 0; l < tree[i].length; l++) { let nextNode = tree[i][l]; for (let j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y function canFormPalindromicPath(x, y) { let lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); let charactersCountFromXtoY = new Array(MAX_CHAR); charactersCountFromXtoY.fill(0); // Calculating the character count // for path node x to y for (let i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v function updateNodeCharactersCount(str, v) { // Updating the character count at node v for (let i = 0; i < str.length; i++) nodeCharactersCount[v][str[i].charCodeAt() - 'a'.charCodeAt()]++; } // Function to perform the queries function performQueries(queries, q) { let i = 0; while (i < q) { let x = queries[i][0]; let y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) document.write("Yes" + "</br>"); else document.write("No" + "</br>"); i++; } } // Fill the complete array with 0 for (let i = 0; i < MAX_SIZE; i++) { nodeCharactersCount[i] = new Array(MAX_CHAR); for (let j = 0; j < MAX_CHAR; j++) { nodeCharactersCount[i][j] = 0; } } for (let i = 0; i < MAX_SIZE; i++) { tree[i] = []; } // Edge between 1 and 2 labelled "bbc" tree[1].push(2); updateNodeCharactersCount("bbc", 2); // Edge between 1 and 3 labelled "ac" tree[1].push(3); updateNodeCharactersCount("ac", 3); // Update the character count // from root to the ith node buildTree(1); let queries = [ [ 1, 2 ], [ 2, 3 ], [ 3, 1 ], [ 3, 3 ] ]; let q = queries.length; // Perform the queries performQueries(queries, q); </script>
// JavaScript implementation of the approach let MAX_SIZE = 1000; let tree = new Array(MAX_SIZE); for (let i = 0; i < tree.length; i++) { tree[i] = [];} function addEdgesWithLabel(a, b, str) { tree[a].push([b, str]); tree[b].push([a, str]);} function dfs(node, parent, label, lev) { memo[node][0] = parent; level[node] = lev; label_array[node][0] = label; for (let i = 1; i <= log; i++) { if (memo[node][i - 1] != -1) { memo[node][i] = memo[memo[node][i - 1]][i - 1]; label_array[node][i] = label_array[node][i] + label_array[memo[node][i - 1]][i - 1]; } } for (let i = 0; i < tree[node].length; i++) { if (tree[node][i][0] != parent) { dfs(tree[node][i][0], node, tree[node][i][1], level[node] + 1) } } } function findPathString(u, v) { let res = ''; if (level[u] < level[v]) { let temp = u; u = v; v = temp; } for (let i = log; i >= 0; i--) { if (level[u] - Math.pow(2, i) >= level[v]) { res = res + label_array[u][i]; u = memo[u][i]; } } if (u == v) { return res; } for (let i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { res = res + label_array[u][i] + label_array[v][i]; v = memo[v][i]; u = memo[u][i]; } } res = res + label_array[u][0] + label_array[v][0]; return res;} function checkIfPalindrom(str) { // Create a list let list = []; // For each character in input strings, // remove character if list contains // else add character to list for (let i = 0; i < str.length; i++) { if (list.includes(str[i])) list.splice(list.indexOf(str[i]), 1); else list.push(str[i]); } // If character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // If string length is even if (str.length % 2 == 0 && list.length == 0 || (str.length % 2 == 1 && list.length == 1)) return 'YES'; // If string length is odd else return 'NO';} let memo = new Array(MAX_SIZE); let log = Math.ceil(Math.log(MAX_SIZE) / Math.log(2)); for (let i = 0; i < memo.length; i++) { memo[i] = new Array(log + 1); for (let j = 0; j < log + 1; j++) { memo[i][j] = -1; }} let label_array = new Array(MAX_SIZE); for (let i = 0; i < label_array.length; i++) { label_array[i] = new Array(log + 1); for (let j = 0; j < log + 1; j++) { label_array[i][j] = ''; }} let level = new Array(MAX_SIZE);level.fill(0);addEdgesWithLabel(1, 2, 'bbc');addEdgesWithLabel(1, 3, 'ac');dfs(1, -1, '', 0);document.write(checkIfPalindrom(findPathString(1, 2)) + '<br>');document.write(checkIfPalindrom(findPathString(2, 3)) + '<br>');document.write(checkIfPalindrom(findPathString(3, 1)) + '<br>');document.write(checkIfPalindrom(findPathString(3, 3)) + '<br>'); // This code is contributed by gaurav2146
Yes
Yes
No
Yes
sanjeev2552
aashish1995
mukesh07
gaurav2146
LCA
palindrome
Strings
Tree
Strings
Tree
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree) | [
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 26627,
"s": 26175,
"text": "Given a tree with N nodes and N – 1 edges. Each edge of the tree is labeled by a string of lowercase english alphabets. You are given Q queries. In each query you are given two node x and y. For the path between x to y, the task is to check if it is possible to make a new palindrome string which use all the characters in the path from node x to node y. Note that you can use the characters in any order you like and root node is always 1.Examples: "
},
{
"code": null,
"e": 27056,
"s": 26627,
"text": "Input:\n 1\n (bbc)/ \\(ac)\n 2 3\nQ[][] = {{1, 2}, {2, 3}, {3, 1}, {3, 3}}\nOutput:\nYes\nYes\nNo\nYes\nQuery 1: \"bbc\" can be arranged into \"bcb\" \nwhich is a palindrome.\nQuery 2: \"bbcac\" -> \"bcacb\"\nQuery 3: No permutation of \"ac\" is palindrome.\nQuery 4: \"acac\" -> \"acca\"\n\nInput:\n 1\n / | \\\n /(ab) |(bca) \\(bc)\n 2 3 4\n \\(ab)\n 5\nQ[][] = {{1, 5}, {4, 5}, {5, 4}}\nOutput:\nYes\nNo\nNo"
},
{
"code": null,
"e": 27354,
"s": 27058,
"text": "Approach: For each query, the character count for path x to y has to be calculated. After finding the characters count, it can be easily checked whether the characters will form a palindrome or not using the approach discussed in this article. Steps to get the character count for path x to y. "
},
{
"code": null,
"e": 27816,
"s": 27354,
"text": "Set the initial character count for each node.Update character count of the root’s child node and then repeat the same process for its child node.Find LCA (Lowest Common Ancestor) of x and y.Calculate character count for path x to y with the following step: For each character charCount[i] = (xNodeCharCount[i] – lcaNodeCharCount[i]) + (yNodeCharCount[i] – lcaNodeCharCount[i]) Now check whether a palindrome can be formed with the current count of characters."
},
{
"code": null,
"e": 27863,
"s": 27816,
"text": "Set the initial character count for each node."
},
{
"code": null,
"e": 27964,
"s": 27863,
"text": "Update character count of the root’s child node and then repeat the same process for its child node."
},
{
"code": null,
"e": 28010,
"s": 27964,
"text": "Find LCA (Lowest Common Ancestor) of x and y."
},
{
"code": null,
"e": 28199,
"s": 28010,
"text": "Calculate character count for path x to y with the following step: For each character charCount[i] = (xNodeCharCount[i] – lcaNodeCharCount[i]) + (yNodeCharCount[i] – lcaNodeCharCount[i]) "
},
{
"code": null,
"e": 28282,
"s": 28199,
"text": "Now check whether a palindrome can be formed with the current count of characters."
},
{
"code": null,
"e": 28335,
"s": 28282,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28339,
"s": 28335,
"text": "C++"
},
{
"code": null,
"e": 28344,
"s": 28339,
"text": "Java"
},
{
"code": null,
"e": 28347,
"s": 28344,
"text": "C#"
},
{
"code": null,
"e": 28358,
"s": 28347,
"text": "Javascript"
},
{
"code": null,
"e": 28369,
"s": 28358,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX_SIZE = 100005, MAX_CHAR = 26;int nodeCharactersCount[MAX_SIZE][MAX_CHAR]; vector<int> tree[MAX_SIZE]; // Function that returns true if a palindromic// string can be formed using the given charactersbool canFormPalindrome(int* charArray){ // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true;} // Find to find the Lowest Common// Ancestor in the treeint LCA(int currentNode, int x, int y){ // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].size(); l++) { // Next node that will be checked int nextNode = tree[currentNode][l]; // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 and yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca;} // Function to calculate the character count for// each path from node i to 1 (root node)void buildTree(int i){ for (int l = 0; l < tree[i].size(); l++) { int nextNode = tree[i][l]; for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); }} // Function that returns true if a palindromic path// is possible between the nodes x and ybool canFormPalindromicPath(int x, int y){ int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int charactersCountFromXtoY[MAX_CHAR] = { 0 }; // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false;} // Function to update character count at node vvoid updateNodeCharactersCount(string str, int v){ // Updating the character count at node v for (int i = 0; i < str.length(); i++) nodeCharactersCount[v][str[i] - 'a']++;} // Function to perform the queriesvoid performQueries(vector<vector<int> > queries, int q){ int i = 0; while (i < q) { int x = queries[i][0]; int y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) cout << \"Yes\\n\"; else cout << \"No\\n\"; i++; }} // Driver codeint main(){ // Fill the complete array with 0 memset(nodeCharactersCount, 0, sizeof(nodeCharactersCount)); // Edge between 1 and 2 labelled \"bbc\" tree[1].push_back(2); updateNodeCharactersCount(\"bbc\", 2); // Edge between 1 and 3 labelled \"ac\" tree[1].push_back(3); updateNodeCharactersCount(\"ac\", 3); // Update the character count // from root to the ith node buildTree(1); vector<vector<int> > queries{ { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.size(); // Perform the queries performQueries(queries, q); return 0;}",
"e": 32833,
"s": 28369,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; @SuppressWarnings(\"unchecked\")class GFG { static int MAX_SIZE = 100005, MAX_CHAR = 26; static int[][] nodeCharactersCount = new int[MAX_SIZE][MAX_CHAR]; static Vector<Integer>[] tree = new Vector[MAX_SIZE]; // Function that returns true if a palindromic // string can be formed using the given characters static boolean canFormPalindrome(int[] charArray) { // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree static int LCA(int currentNode, int x, int y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].size(); l++) { // Next node that will be checked int nextNode = tree[currentNode].elementAt(l); // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) static void buildTree(int i) { for (int l = 0; l < tree[i].size(); l++) { int nextNode = tree[i].elementAt(l); for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y static boolean canFormPalindromicPath(int x, int y) { int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int[] charactersCountFromXtoY = new int[MAX_CHAR]; Arrays.fill(charactersCountFromXtoY, 0); // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v static void updateNodeCharactersCount(String str, int v) { // Updating the character count at node v for (int i = 0; i < str.length(); i++) nodeCharactersCount[v][str.charAt(i) - 'a']++; } // Function to perform the queries static void performQueries(int[][] queries, int q) { int i = 0; while (i < q) { int x = queries[i][0]; int y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) System.out.println(\"Yes\"); else System.out.println(\"No\"); i++; } } // Driver Code public static void main(String[] args) { // Fill the complete array with 0 for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_CHAR; j++) { nodeCharactersCount[i][j] = 0; } } for (int i = 0; i < MAX_SIZE; i++) { tree[i] = new Vector<>(); } // Edge between 1 and 2 labelled \"bbc\" tree[1].add(2); updateNodeCharactersCount(\"bbc\", 2); // Edge between 1 and 3 labelled \"ac\" tree[1].add(3); updateNodeCharactersCount(\"ac\", 3); // Update the character count // from root to the ith node buildTree(1); int[][] queries = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.length; // Perform the queries performQueries(queries, q); }} // This code is contributed by// sanjeev2552",
"e": 38170,
"s": 32833,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ static int MAX_SIZE = 100005, MAX_CHAR = 26; static int[,] nodecharsCount = new int[MAX_SIZE, MAX_CHAR]; static List<int>[] tree = new List<int>[MAX_SIZE]; // Function that returns true if a palindromic // string can be formed using the given characters static bool canFormPalindrome(int[] charArray) { // Count odd occurring characters int oddCount = 0; for (int i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree static int LCA(int currentNode, int x, int y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; int xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y int gotLca = -1; // Iterating in the child // substree of the currentNode for (int l = 0; l < tree[currentNode].Count; l++) { // Next node that will be checked int nextNode = tree[currentNode][l]; // Look for the next child subtree int out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) static void buildTree(int i) { for (int l = 0; l < tree[i].Count; l++) { int nextNode = tree[i][l]; for (int j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodecharsCount[nextNode,j] += nodecharsCount[i,j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y static bool canFormPalindromicPath(int x, int y) { int lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); int[] charactersCountFromXtoY = new int[MAX_CHAR]; // Calculating the character count // for path node x to y for (int i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodecharsCount[x, i] + nodecharsCount[y, i] - 2 * nodecharsCount[lcaNode, i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v static void updateNodecharsCount(String str, int v) { // Updating the character count at node v for (int i = 0; i < str.Length; i++) nodecharsCount[v, str[i] - 'a']++; } // Function to perform the queries static void performQueries(int[,] queries, int q) { int i = 0; while (i < q) { int x = queries[i, 0]; int y = queries[i, 1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); i++; } } // Driver Code public static void Main(String[] args) { // Fill the complete array with 0 for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_CHAR; j++) { nodecharsCount[i, j] = 0; } } for (int i = 0; i < MAX_SIZE; i++) { tree[i] = new List<int>(); } // Edge between 1 and 2 labelled \"bbc\" tree[1].Add(2); updateNodecharsCount(\"bbc\", 2); // Edge between 1 and 3 labelled \"ac\" tree[1].Add(3); updateNodecharsCount(\"ac\", 3); // Update the character count // from root to the ith node buildTree(1); int[,] queries = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; int q = queries.GetLength(0); // Perform the queries performQueries(queries, q); }} // This code is contributed by aashish1995",
"e": 42703,
"s": 38170,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach let MAX_SIZE = 100005, MAX_CHAR = 26; let nodeCharactersCount = new Array(MAX_SIZE); let tree = new Array(MAX_SIZE); // Function that returns true if a palindromic // string can be formed using the given characters function canFormPalindrome(charArray) { // Count odd occurring characters let oddCount = 0; for (let i = 0; i < MAX_CHAR; i++) { if (charArray[i] % 2 == 1) oddCount++; } // Return false if odd count is more than 1, if (oddCount >= 2) return false; else return true; } // Find to find the Lowest Common // Ancestor in the tree function LCA(currentNode, x, y) { // Base case if (currentNode == x) return x; // Base case if (currentNode == y) return y; let xLca, yLca; // Initially value -1 denotes that // we need to find the ancestor xLca = yLca = -1; // -1 denotes that we need to find the lca // for x and y, values other than x and y // will be the LCA of x and y let gotLca = -1; // Iterating in the child // substree of the currentNode for (let l = 0; l < tree[currentNode].length; l++) { // Next node that will be checked let nextNode = tree[currentNode][l]; // Look for the next child subtree let out_ = LCA(nextNode, x, y); if (out_ == x) xLca = out_; if (out_ == y) yLca = out_; // Both the nodes exist in the different // subtrees, in this case parent node // will be the lca if (xLca != -1 && yLca != -1) return currentNode; // Handle the cases where LCA is already // calculated or both x and y are present // in the same subtree if (out_ != -1) gotLca = out_; } return gotLca; } // Function to calculate the character count for // each path from node i to 1 (root node) function buildTree(i) { for (let l = 0; l < tree[i].length; l++) { let nextNode = tree[i][l]; for (let j = 0; j < MAX_CHAR; j++) { // Updating the character count // for each node nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; } // Look for the child subtree buildTree(nextNode); } } // Function that returns true if a palindromic path // is possible between the nodes x and y function canFormPalindromicPath(x, y) { let lcaNode; // If both x and y are same then // lca will be the node itself if (x == y) lcaNode = x; // Find the lca of x and y else lcaNode = LCA(1, x, y); let charactersCountFromXtoY = new Array(MAX_CHAR); charactersCountFromXtoY.fill(0); // Calculating the character count // for path node x to y for (let i = 0; i < MAX_CHAR; i++) { charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + nodeCharactersCount[y][i] - 2 * nodeCharactersCount[lcaNode][i]; } // Checking if we can form the palindrome // string with the all character count if (canFormPalindrome(charactersCountFromXtoY)) return true; return false; } // Function to update character count at node v function updateNodeCharactersCount(str, v) { // Updating the character count at node v for (let i = 0; i < str.length; i++) nodeCharactersCount[v][str[i].charCodeAt() - 'a'.charCodeAt()]++; } // Function to perform the queries function performQueries(queries, q) { let i = 0; while (i < q) { let x = queries[i][0]; let y = queries[i][1]; // If path can be a palindrome if (canFormPalindromicPath(x, y)) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\" + \"</br>\"); i++; } } // Fill the complete array with 0 for (let i = 0; i < MAX_SIZE; i++) { nodeCharactersCount[i] = new Array(MAX_CHAR); for (let j = 0; j < MAX_CHAR; j++) { nodeCharactersCount[i][j] = 0; } } for (let i = 0; i < MAX_SIZE; i++) { tree[i] = []; } // Edge between 1 and 2 labelled \"bbc\" tree[1].push(2); updateNodeCharactersCount(\"bbc\", 2); // Edge between 1 and 3 labelled \"ac\" tree[1].push(3); updateNodeCharactersCount(\"ac\", 3); // Update the character count // from root to the ith node buildTree(1); let queries = [ [ 1, 2 ], [ 2, 3 ], [ 3, 1 ], [ 3, 3 ] ]; let q = queries.length; // Perform the queries performQueries(queries, q); </script>",
"e": 47737,
"s": 42703,
"text": null
},
{
"code": "// JavaScript implementation of the approach let MAX_SIZE = 1000; let tree = new Array(MAX_SIZE); for (let i = 0; i < tree.length; i++) { tree[i] = [];} function addEdgesWithLabel(a, b, str) { tree[a].push([b, str]); tree[b].push([a, str]);} function dfs(node, parent, label, lev) { memo[node][0] = parent; level[node] = lev; label_array[node][0] = label; for (let i = 1; i <= log; i++) { if (memo[node][i - 1] != -1) { memo[node][i] = memo[memo[node][i - 1]][i - 1]; label_array[node][i] = label_array[node][i] + label_array[memo[node][i - 1]][i - 1]; } } for (let i = 0; i < tree[node].length; i++) { if (tree[node][i][0] != parent) { dfs(tree[node][i][0], node, tree[node][i][1], level[node] + 1) } } } function findPathString(u, v) { let res = ''; if (level[u] < level[v]) { let temp = u; u = v; v = temp; } for (let i = log; i >= 0; i--) { if (level[u] - Math.pow(2, i) >= level[v]) { res = res + label_array[u][i]; u = memo[u][i]; } } if (u == v) { return res; } for (let i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { res = res + label_array[u][i] + label_array[v][i]; v = memo[v][i]; u = memo[u][i]; } } res = res + label_array[u][0] + label_array[v][0]; return res;} function checkIfPalindrom(str) { // Create a list let list = []; // For each character in input strings, // remove character if list contains // else add character to list for (let i = 0; i < str.length; i++) { if (list.includes(str[i])) list.splice(list.indexOf(str[i]), 1); else list.push(str[i]); } // If character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // If string length is even if (str.length % 2 == 0 && list.length == 0 || (str.length % 2 == 1 && list.length == 1)) return 'YES'; // If string length is odd else return 'NO';} let memo = new Array(MAX_SIZE); let log = Math.ceil(Math.log(MAX_SIZE) / Math.log(2)); for (let i = 0; i < memo.length; i++) { memo[i] = new Array(log + 1); for (let j = 0; j < log + 1; j++) { memo[i][j] = -1; }} let label_array = new Array(MAX_SIZE); for (let i = 0; i < label_array.length; i++) { label_array[i] = new Array(log + 1); for (let j = 0; j < log + 1; j++) { label_array[i][j] = ''; }} let level = new Array(MAX_SIZE);level.fill(0);addEdgesWithLabel(1, 2, 'bbc');addEdgesWithLabel(1, 3, 'ac');dfs(1, -1, '', 0);document.write(checkIfPalindrom(findPathString(1, 2)) + '<br>');document.write(checkIfPalindrom(findPathString(2, 3)) + '<br>');document.write(checkIfPalindrom(findPathString(3, 1)) + '<br>');document.write(checkIfPalindrom(findPathString(3, 3)) + '<br>'); // This code is contributed by gaurav2146",
"e": 50738,
"s": 47737,
"text": null
},
{
"code": null,
"e": 50753,
"s": 50738,
"text": "Yes\nYes\nNo\nYes"
},
{
"code": null,
"e": 50767,
"s": 50755,
"text": "sanjeev2552"
},
{
"code": null,
"e": 50779,
"s": 50767,
"text": "aashish1995"
},
{
"code": null,
"e": 50788,
"s": 50779,
"text": "mukesh07"
},
{
"code": null,
"e": 50799,
"s": 50788,
"text": "gaurav2146"
},
{
"code": null,
"e": 50803,
"s": 50799,
"text": "LCA"
},
{
"code": null,
"e": 50814,
"s": 50803,
"text": "palindrome"
},
{
"code": null,
"e": 50822,
"s": 50814,
"text": "Strings"
},
{
"code": null,
"e": 50827,
"s": 50822,
"text": "Tree"
},
{
"code": null,
"e": 50835,
"s": 50827,
"text": "Strings"
},
{
"code": null,
"e": 50840,
"s": 50835,
"text": "Tree"
},
{
"code": null,
"e": 50851,
"s": 50840,
"text": "palindrome"
},
{
"code": null,
"e": 50949,
"s": 50851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50994,
"s": 50949,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 51039,
"s": 50994,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 51056,
"s": 51039,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 51085,
"s": 51056,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 51100,
"s": 51085,
"text": "sprintf() in C"
},
{
"code": null,
"e": 51150,
"s": 51100,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 51185,
"s": 51150,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 51214,
"s": 51185,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 51248,
"s": 51214,
"text": "Level Order Binary Tree Traversal"
}
] |
How to hide or show one record from an ng-repeat within a table based on ng-click? - GeeksforGeeks | 18 Oct, 2019
The way to hide or show a particular record in a table is similar to what is used to hide or show any elements of the DOM. The basic and the first thing that comes to mind is the ng-show and ng-hide directives which show or hides respectively based on binary results of the expressions bound to them. Another way can be the use ofng-if which works like an if block in general programming. If the expression is true the element is visible or not.Controlling this can be easily done by the ng-click command which can be used to call a function or run a piece of code that manipulates the entities present in the boolean expressions.
Approach 1: Here the tr element is visible only if the expression bound to the ng-show is true.Here ng-hide is commented out in the example but it works in the same way ng-show. The difference is that it hides the tr element if the boolean expression gives a true value.The ng-show and ng-hide directives both can have general function calls but they should return a boolean value.
Syntax:
< tr ng-repeat="x in [some list]" ng-show="[some boolean expression]" > < tr >
< tr ng-repeat="x in [some list]" ng-hide="[some boolean expression]" > < tr >
Example:
<!DOCTYPE html><html> <head> <title> Angular show hide table element on click </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <div ng-app="mainApp" ng-controller="MyCtrl"> <button ng-click="showPresent()"> Show People Present </button> <button ng-click="showAbsent()"> Show People Absent </button> <table> <tr> <td>Name</td> <td>Age</td> </tr> <!-- The next two lines are interchangeable --> <!-- <tr ng-repeat="p in people" ng-hide="p.attended!=flag"></tr> --> <tr ng-repeat="p in people" ng-show="p.attended==flag"> <td>{{p.name}}</td> <td>{{p.Age}}</td> </tr> </table> </div> <script> var app = angular.module("mainApp", []); app.controller("MyCtrl", function($scope) { $scope.flag = 1; $scope.people = [{ name: "GeekAgashi", Age: 12, attended: 1 }, { name: "GeekSatoshi", Age: 16, attended: 0 }, { name: "GeekNakumato", Age: 14, attended: 1 }]; $scope.showPresent = function() { $scope.flag = 1; }; $scope.showAbsent = function() { $scope.flag = 0; }; }); </script> </body> </html>
Output:
When the “Show People Present” is clicked the boolean is true for all objects whose attended value matches the flag value as it is changes to 1 by call from ng-click:
When the “Show People Absent” is clicked the boolean is true for all objects whose attended value matches the flag value as it is changes to 0 by call from ng-click:
Approach 2: Here we use the ngIf to show or hide records of the table. The code remains the same as the work is nearly the same. But ngIf is less reliable than ng-show or ng-hide but what it does is that it removes the elements from the DOM completely.
Syantax:
< tr ng-repeat="x in [some list]" ng-if="[some boolean expression]" > < tr >
Example:
<!DOCTYPE html><html> <head> <title>Angular show or hide element on click</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <div ng-app="mainApp" ng-controller="MyCtrl"> <button ng-click="showPresent()"> Show People Present </button> <button ng-click="showAbsent()"> Show People Absent </button> <table> <tr> <td>Name</td> <td>Age</td> </tr> <!--The main change in the code is in the next line--> <tr ng-repeat="p in people" ng-if="p.attended==flag"> <td>{{p.name}}</td> <td>{{p.Age}}</td> </tr> </table> </div> <script> var app = angular.module("mainApp", []); app.controller("MyCtrl", function($scope) { $scope.flag = 1; $scope.people = [{ name: "GeekAgashi", Age: 12, attended: 1 }, { name: "GeekSatoshi", Age: 16, attended: 0 }, { name: "GeekNakumato", Age: 14, attended: 1 }]; $scope.showPresent = function() { $scope.flag = 1; }; $scope.showAbsent = function() { $scope.flag = 0; }; }); </script> </body> </html>
Output:
Output remains the same as they both work in the same way:
AngularJS-Directives
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
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": 25814,
"s": 25786,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 26445,
"s": 25814,
"text": "The way to hide or show a particular record in a table is similar to what is used to hide or show any elements of the DOM. The basic and the first thing that comes to mind is the ng-show and ng-hide directives which show or hides respectively based on binary results of the expressions bound to them. Another way can be the use ofng-if which works like an if block in general programming. If the expression is true the element is visible or not.Controlling this can be easily done by the ng-click command which can be used to call a function or run a piece of code that manipulates the entities present in the boolean expressions."
},
{
"code": null,
"e": 26827,
"s": 26445,
"text": "Approach 1: Here the tr element is visible only if the expression bound to the ng-show is true.Here ng-hide is commented out in the example but it works in the same way ng-show. The difference is that it hides the tr element if the boolean expression gives a true value.The ng-show and ng-hide directives both can have general function calls but they should return a boolean value."
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "Syntax:"
},
{
"code": null,
"e": 26994,
"s": 26835,
"text": "< tr ng-repeat=\"x in [some list]\" ng-show=\"[some boolean expression]\" > < tr >\n< tr ng-repeat=\"x in [some list]\" ng-hide=\"[some boolean expression]\" > < tr >\n"
},
{
"code": null,
"e": 27003,
"s": 26994,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Angular show hide table element on click </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <div ng-app=\"mainApp\" ng-controller=\"MyCtrl\"> <button ng-click=\"showPresent()\"> Show People Present </button> <button ng-click=\"showAbsent()\"> Show People Absent </button> <table> <tr> <td>Name</td> <td>Age</td> </tr> <!-- The next two lines are interchangeable --> <!-- <tr ng-repeat=\"p in people\" ng-hide=\"p.attended!=flag\"></tr> --> <tr ng-repeat=\"p in people\" ng-show=\"p.attended==flag\"> <td>{{p.name}}</td> <td>{{p.Age}}</td> </tr> </table> </div> <script> var app = angular.module(\"mainApp\", []); app.controller(\"MyCtrl\", function($scope) { $scope.flag = 1; $scope.people = [{ name: \"GeekAgashi\", Age: 12, attended: 1 }, { name: \"GeekSatoshi\", Age: 16, attended: 0 }, { name: \"GeekNakumato\", Age: 14, attended: 1 }]; $scope.showPresent = function() { $scope.flag = 1; }; $scope.showAbsent = function() { $scope.flag = 0; }; }); </script> </body> </html>",
"e": 28557,
"s": 27003,
"text": null
},
{
"code": null,
"e": 28565,
"s": 28557,
"text": "Output:"
},
{
"code": null,
"e": 28732,
"s": 28565,
"text": "When the “Show People Present” is clicked the boolean is true for all objects whose attended value matches the flag value as it is changes to 1 by call from ng-click:"
},
{
"code": null,
"e": 28898,
"s": 28732,
"text": "When the “Show People Absent” is clicked the boolean is true for all objects whose attended value matches the flag value as it is changes to 0 by call from ng-click:"
},
{
"code": null,
"e": 29151,
"s": 28898,
"text": "Approach 2: Here we use the ngIf to show or hide records of the table. The code remains the same as the work is nearly the same. But ngIf is less reliable than ng-show or ng-hide but what it does is that it removes the elements from the DOM completely."
},
{
"code": null,
"e": 29160,
"s": 29151,
"text": "Syantax:"
},
{
"code": null,
"e": 29237,
"s": 29160,
"text": "< tr ng-repeat=\"x in [some list]\" ng-if=\"[some boolean expression]\" > < tr >"
},
{
"code": null,
"e": 29246,
"s": 29237,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Angular show or hide element on click</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <div ng-app=\"mainApp\" ng-controller=\"MyCtrl\"> <button ng-click=\"showPresent()\"> Show People Present </button> <button ng-click=\"showAbsent()\"> Show People Absent </button> <table> <tr> <td>Name</td> <td>Age</td> </tr> <!--The main change in the code is in the next line--> <tr ng-repeat=\"p in people\" ng-if=\"p.attended==flag\"> <td>{{p.name}}</td> <td>{{p.Age}}</td> </tr> </table> </div> <script> var app = angular.module(\"mainApp\", []); app.controller(\"MyCtrl\", function($scope) { $scope.flag = 1; $scope.people = [{ name: \"GeekAgashi\", Age: 12, attended: 1 }, { name: \"GeekSatoshi\", Age: 16, attended: 0 }, { name: \"GeekNakumato\", Age: 14, attended: 1 }]; $scope.showPresent = function() { $scope.flag = 1; }; $scope.showAbsent = function() { $scope.flag = 0; }; }); </script> </body> </html>",
"e": 30728,
"s": 29246,
"text": null
},
{
"code": null,
"e": 30736,
"s": 30728,
"text": "Output:"
},
{
"code": null,
"e": 30795,
"s": 30736,
"text": "Output remains the same as they both work in the same way:"
},
{
"code": null,
"e": 30816,
"s": 30795,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 30823,
"s": 30816,
"text": "Picked"
},
{
"code": null,
"e": 30833,
"s": 30823,
"text": "AngularJS"
},
{
"code": null,
"e": 30850,
"s": 30833,
"text": "Web Technologies"
},
{
"code": null,
"e": 30948,
"s": 30850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30983,
"s": 30948,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31014,
"s": 30983,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 31049,
"s": 31014,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 31094,
"s": 31049,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 31136,
"s": 31094,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 31176,
"s": 31136,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31209,
"s": 31176,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31254,
"s": 31209,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31297,
"s": 31254,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Destructuring Declarations in Kotlin - GeeksforGeeks | 02 Aug, 2019
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once.For example :
val (emp_id,salary) = employee
These multiple variables correspond to the properties of a class that are associated with an instance. These variables can be used independently in any way you want.
println(emp_id+" "+salary)
The destructing declaration works on the concept of component() functions. The number of variables that a destructing declaration can define, the class provide those number of component functions, starting from component1(), component2() up to componentN(). The data class in Kotlin by default implement component functions.
Destructuring declaration compiled to following code:-
val emp_id = employee.component1()
val salary = employee.component2()
Kotlin program of returning two values from a function –
// A sample data classdata class Data(val name:String,val age:Int) // A function returning two valuesfun sendData():Data{ return Data("Jack",30)} fun main(){ val obj = sendData() // Using instance to access properties println("Name is ${obj.name}") println("Age is ${obj.age}") // Creating two variables using destructing declaration val (name,age) = sendData() println("Name is $name") println("Age is $age") }
Output:
Name is JackAge is 30Name is JackAge is 30
Note: The component function definitions must be preceded by the operator keyword if to be used in a destructuring declaration.
Underscore for unused variablesSometimes, you might want to ignore a variable in a destructuring declaration. To do so, put an underscore in place of its name. In this case, the component function for the given variable isn’t invoked.
Following the arrival of Kotlin 1.1, the destructing declaration syntax can be used for lambda parameters also. If a lambda parameter has a parameter of Pair type or some other type that declares component functions, then we can introduce new parameters by putting them in parenthesis. The rules are the same as defined above.
Kotlin program of using destructuring declaration for lambda parameters –
fun main(){ val map = mutableMapOf<Int,String>() map.put(1,"Ishita") map.put(2,"Kamal") map.put(3,"Kanika") map.put(4,"Minal") map.put(5,"Neha") map.put(6,"Pratyush") map.put(7,"Shagun") map.put(8,"Shashank") map.put(9,"Uday") map.put(10,"Vandit") println("Initial map is") println(map) // Destructuring a map entry into key and values val newmap = map.mapValues { (key,value) -> "Hello ${value}" } println("Map after appending Hello") println(newmap)}
Output:
Initial map is{1=Ishita, 2=Kamal, 3=Kanika, 4=Minal, 5=Neha, 6=Pratyush, 7=Shagun, 8=Shashank, 9=Uday, 10=Vandit}Map after appending Hello{1=Hello Ishita, 2=Hello Kamal, 3=Hello Kanika, 4=Hello Minal, 5=Hello Neha, 6=Hello Pratyush, 7=Hello Shagun, 8=Hello Shashank, 9=Hello Uday, 10=Hello Vandit}
If a component of the destructured parameter is not in use, we can replace it with the underscore to avoid calling component function:
map.mapValues { (_,value) -> "${value}" }
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
How to Get Current Location in Android?
Kotlin Setters and Getters
Kotlin Android Tutorial
How to Change the Color of Status Bar in an Android App?
Kotlin when expression | [
{
"code": null,
"e": 25135,
"s": 25107,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 25371,
"s": 25135,
"text": "Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once.For example :"
},
{
"code": null,
"e": 25402,
"s": 25371,
"text": "val (emp_id,salary) = employee"
},
{
"code": null,
"e": 25568,
"s": 25402,
"text": "These multiple variables correspond to the properties of a class that are associated with an instance. These variables can be used independently in any way you want."
},
{
"code": null,
"e": 25595,
"s": 25568,
"text": "println(emp_id+\" \"+salary)"
},
{
"code": null,
"e": 25920,
"s": 25595,
"text": "The destructing declaration works on the concept of component() functions. The number of variables that a destructing declaration can define, the class provide those number of component functions, starting from component1(), component2() up to componentN(). The data class in Kotlin by default implement component functions."
},
{
"code": null,
"e": 25975,
"s": 25920,
"text": "Destructuring declaration compiled to following code:-"
},
{
"code": null,
"e": 26046,
"s": 25975,
"text": "val emp_id = employee.component1()\nval salary = employee.component2()\n"
},
{
"code": null,
"e": 26103,
"s": 26046,
"text": "Kotlin program of returning two values from a function –"
},
{
"code": "// A sample data classdata class Data(val name:String,val age:Int) // A function returning two valuesfun sendData():Data{ return Data(\"Jack\",30)} fun main(){ val obj = sendData() // Using instance to access properties println(\"Name is ${obj.name}\") println(\"Age is ${obj.age}\") // Creating two variables using destructing declaration val (name,age) = sendData() println(\"Name is $name\") println(\"Age is $age\") }",
"e": 26553,
"s": 26103,
"text": null
},
{
"code": null,
"e": 26561,
"s": 26553,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26561,
"text": "Name is JackAge is 30Name is JackAge is 30"
},
{
"code": null,
"e": 26732,
"s": 26604,
"text": "Note: The component function definitions must be preceded by the operator keyword if to be used in a destructuring declaration."
},
{
"code": null,
"e": 26967,
"s": 26732,
"text": "Underscore for unused variablesSometimes, you might want to ignore a variable in a destructuring declaration. To do so, put an underscore in place of its name. In this case, the component function for the given variable isn’t invoked."
},
{
"code": null,
"e": 27294,
"s": 26967,
"text": "Following the arrival of Kotlin 1.1, the destructing declaration syntax can be used for lambda parameters also. If a lambda parameter has a parameter of Pair type or some other type that declares component functions, then we can introduce new parameters by putting them in parenthesis. The rules are the same as defined above."
},
{
"code": null,
"e": 27368,
"s": 27294,
"text": "Kotlin program of using destructuring declaration for lambda parameters –"
},
{
"code": "fun main(){ val map = mutableMapOf<Int,String>() map.put(1,\"Ishita\") map.put(2,\"Kamal\") map.put(3,\"Kanika\") map.put(4,\"Minal\") map.put(5,\"Neha\") map.put(6,\"Pratyush\") map.put(7,\"Shagun\") map.put(8,\"Shashank\") map.put(9,\"Uday\") map.put(10,\"Vandit\") println(\"Initial map is\") println(map) // Destructuring a map entry into key and values val newmap = map.mapValues { (key,value) -> \"Hello ${value}\" } println(\"Map after appending Hello\") println(newmap)}",
"e": 27872,
"s": 27368,
"text": null
},
{
"code": null,
"e": 27880,
"s": 27872,
"text": "Output:"
},
{
"code": null,
"e": 28178,
"s": 27880,
"text": "Initial map is{1=Ishita, 2=Kamal, 3=Kanika, 4=Minal, 5=Neha, 6=Pratyush, 7=Shagun, 8=Shashank, 9=Uday, 10=Vandit}Map after appending Hello{1=Hello Ishita, 2=Hello Kamal, 3=Hello Kanika, 4=Hello Minal, 5=Hello Neha, 6=Hello Pratyush, 7=Hello Shagun, 8=Hello Shashank, 9=Hello Uday, 10=Hello Vandit}"
},
{
"code": null,
"e": 28313,
"s": 28178,
"text": "If a component of the destructured parameter is not in use, we can replace it with the underscore to avoid calling component function:"
},
{
"code": null,
"e": 28355,
"s": 28313,
"text": "map.mapValues { (_,value) -> \"${value}\" }"
},
{
"code": null,
"e": 28362,
"s": 28355,
"text": "Kotlin"
},
{
"code": null,
"e": 28460,
"s": 28362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28503,
"s": 28460,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28534,
"s": 28503,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28576,
"s": 28534,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 28618,
"s": 28576,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28681,
"s": 28618,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 28721,
"s": 28681,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 28748,
"s": 28721,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 28772,
"s": 28748,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 28829,
"s": 28772,
"text": "How to Change the Color of Status Bar in an Android App?"
}
] |
Python | Alternate element summation in list - GeeksforGeeks | 29 Mar, 2019
The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + list slicing + sum()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, summation by the sum function
# Python3 code to demonstrate# alternate elements summation# using list comprehension + list slicing # initializing list test_list = [2, 1, 5, 6, 8, 10] # printing original list print("The original list : " + str(test_list)) # using list comprehension + list slicing# alternate elements summationres = [sum(test_list[i : : 2]) for i in range(len(test_list)//(len(test_list)//2))] # print resultprint("The alternate elements summation list : " + str(res))
The original list : [2, 1, 5, 6, 8, 10]
The alternate elements summation list : [15, 17]
Method #2 : Using loopThis is the brute method to perform this particular task in which we have the summation of alternate elements in different element indices and then return the output list.
# Python3 code to demonstrate# alternate elements summation# using loop # initializing list test_list = [2, 1, 5, 6, 8, 10] # printing original list print("The original list : " + str(test_list)) # using loop# alternate elements summationres = [0, 0]for i in range(0, len(test_list)): if(i % 2): res[1] += test_list[i] else : res[0] += test_list[i] # print resultprint("The alternate elements summation list : " + str(res))
The original list : [2, 1, 5, 6, 8, 10]
The alternate elements summation list : [15, 17]
Marketing
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 25607,
"s": 25579,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 25885,
"s": 25607,
"text": "The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 26172,
"s": 25885,
"text": "Method #1 : Using list comprehension + list slicing + sum()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, summation by the sum function"
},
{
"code": "# Python3 code to demonstrate# alternate elements summation# using list comprehension + list slicing # initializing list test_list = [2, 1, 5, 6, 8, 10] # printing original list print(\"The original list : \" + str(test_list)) # using list comprehension + list slicing# alternate elements summationres = [sum(test_list[i : : 2]) for i in range(len(test_list)//(len(test_list)//2))] # print resultprint(\"The alternate elements summation list : \" + str(res))",
"e": 26636,
"s": 26172,
"text": null
},
{
"code": null,
"e": 26726,
"s": 26636,
"text": "The original list : [2, 1, 5, 6, 8, 10]\nThe alternate elements summation list : [15, 17]\n"
},
{
"code": null,
"e": 26922,
"s": 26728,
"text": "Method #2 : Using loopThis is the brute method to perform this particular task in which we have the summation of alternate elements in different element indices and then return the output list."
},
{
"code": "# Python3 code to demonstrate# alternate elements summation# using loop # initializing list test_list = [2, 1, 5, 6, 8, 10] # printing original list print(\"The original list : \" + str(test_list)) # using loop# alternate elements summationres = [0, 0]for i in range(0, len(test_list)): if(i % 2): res[1] += test_list[i] else : res[0] += test_list[i] # print resultprint(\"The alternate elements summation list : \" + str(res))",
"e": 27370,
"s": 26922,
"text": null
},
{
"code": null,
"e": 27460,
"s": 27370,
"text": "The original list : [2, 1, 5, 6, 8, 10]\nThe alternate elements summation list : [15, 17]\n"
},
{
"code": null,
"e": 27470,
"s": 27460,
"text": "Marketing"
},
{
"code": null,
"e": 27491,
"s": 27470,
"text": "Python list-programs"
},
{
"code": null,
"e": 27498,
"s": 27491,
"text": "Python"
},
{
"code": null,
"e": 27514,
"s": 27498,
"text": "Python Programs"
},
{
"code": null,
"e": 27612,
"s": 27514,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27630,
"s": 27612,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27665,
"s": 27630,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27697,
"s": 27665,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27719,
"s": 27697,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27761,
"s": 27719,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27804,
"s": 27761,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27826,
"s": 27804,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27865,
"s": 27826,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27911,
"s": 27865,
"text": "Python | Split string into list of characters"
}
] |
CSS | :only-child Selector - GeeksforGeeks | 17 Dec, 2018
The :only-child selector in CSS is used to match every element that is the only child of its parent. It represents an element without any siblings.
Syntax:
:only-child {
// CSS property
}
Example 1:
<!DOCTYPE html><html> <head> <title>:only-child selector</title> <style> h1 { color: green; text-align: center; } h2 { text-align: center; } div:only-child { color: white; background: green; } div { display: block; margin: 6px; font-size: 17px; padding: 5px 8px; border: solid 2px grey; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:only-child selector</h2> <div> <div>I am an only child.</div> </div> <div> <div>I am the 1st child.</div> <div>I am the 2nd child.</div> <div>I am the 3rd child, <div> Only child of parent.</div></div> </div> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>:only-child selector</title> <style> h1 { color: green; text-align: center; } h2 { text-align: center; } li:only-child { color: green; } li { font-size: 20px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:only-child selector</h2> <ol> <li>Data Structures</li> <ul> <li>Arrays </li> </ul> <li>Languages</li> <ul> <li>C++ </li> <li>Python</li> </ul> <li>Algorithms</li> <ul> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <ul> <li>Bubble sort </li> </ul> </ul> </ol> </body></html>
Output:
Supported Browser: The browser supported by :only-child selector are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 3.2
Opera 9.6
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 24889,
"s": 24861,
"text": "\n17 Dec, 2018"
},
{
"code": null,
"e": 25037,
"s": 24889,
"text": "The :only-child selector in CSS is used to match every element that is the only child of its parent. It represents an element without any siblings."
},
{
"code": null,
"e": 25045,
"s": 25037,
"text": "Syntax:"
},
{
"code": null,
"e": 25083,
"s": 25045,
"text": ":only-child {\n // CSS property\n} \n"
},
{
"code": null,
"e": 25094,
"s": 25083,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>:only-child selector</title> <style> h1 { color: green; text-align: center; } h2 { text-align: center; } div:only-child { color: white; background: green; } div { display: block; margin: 6px; font-size: 17px; padding: 5px 8px; border: solid 2px grey; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:only-child selector</h2> <div> <div>I am an only child.</div> </div> <div> <div>I am the 1st child.</div> <div>I am the 2nd child.</div> <div>I am the 3rd child, <div> Only child of parent.</div></div> </div> </body></html>",
"e": 26028,
"s": 25094,
"text": null
},
{
"code": null,
"e": 26036,
"s": 26028,
"text": "Output:"
},
{
"code": null,
"e": 26047,
"s": 26036,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>:only-child selector</title> <style> h1 { color: green; text-align: center; } h2 { text-align: center; } li:only-child { color: green; } li { font-size: 20px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:only-child selector</h2> <ol> <li>Data Structures</li> <ul> <li>Arrays </li> </ul> <li>Languages</li> <ul> <li>C++ </li> <li>Python</li> </ul> <li>Algorithms</li> <ul> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <ul> <li>Bubble sort </li> </ul> </ul> </ol> </body></html>",
"e": 27025,
"s": 26047,
"text": null
},
{
"code": null,
"e": 27033,
"s": 27025,
"text": "Output:"
},
{
"code": null,
"e": 27116,
"s": 27033,
"text": "Supported Browser: The browser supported by :only-child selector are listed below:"
},
{
"code": null,
"e": 27134,
"s": 27116,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 27156,
"s": 27134,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 27168,
"s": 27156,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 27179,
"s": 27168,
"text": "Safari 3.2"
},
{
"code": null,
"e": 27189,
"s": 27179,
"text": "Opera 9.6"
},
{
"code": null,
"e": 27203,
"s": 27189,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 27207,
"s": 27203,
"text": "CSS"
},
{
"code": null,
"e": 27224,
"s": 27207,
"text": "Web Technologies"
},
{
"code": null,
"e": 27322,
"s": 27224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27384,
"s": 27322,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27434,
"s": 27384,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27482,
"s": 27434,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27540,
"s": 27482,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27595,
"s": 27540,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 27635,
"s": 27595,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27668,
"s": 27635,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27713,
"s": 27668,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27756,
"s": 27713,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference between sh and bash - GeeksforGeeks | 21 Feb, 2022
bash and sh are two different shells of the Unix operating system. bash is sh, but with more features and better syntax. Bash is “Bourne Again SHell”, and is an improvement of the sh (original Bourne shell). Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems. sh provides some built-in commands. bash is a superset of sh. Shell is a command-line interface to run commands and shell scripts. Shells come in a variety of flavors, much as operating systems come in a variety of flavors. So, Shell is an interface between the user and the operating system, which helps the user to interact with the device.
#!/bin/sh
#!/bin/bash
Shell is an interface between the user and the operating system.
sh implements the shell interface.
bash is a superset of sh.
sh is also called Bourne Shell. sh is a command programming language described by POSIX standard. It is for UNIX or UNIX-like operating systems. It has many implementations. On most operating systems, sh is implemented by programs like dash, kash, and original Bourne Shell. sh is a Predecessor of bash. /bin/sh is an actual link to main implementations. It is a symlink in most POSIX systems.
sh is not a programming language itself. It is just a specification. sh is a detailed description of the syntax and semantics of the language. It doesn’t include an implementation. sh is written as a replacement for earlier UNIX shells. It’s most of the syntax is the same as the syntax of the ALGOL68 programming language.
We should use sh if we want our language to be compatible with multiple systems. The sh script will most like run on bash also without modifications as bash is backward compatible with sh. sh is the most portable scripting language that works on most POSIX/Unix/Linux systems. One advantage of sh is that it is guaranteed to exist on everything that purports to Unix system.
bash is also a command programming language like sh. Nowadays, bash is a default login shell on most Linux-based operating systems. It is an extended version of the sh system for GNU replacement for the Bourne shell. We can also say bash is a programming language. Here think like python, we can start python in interactive mode and it behaves like a shell but we can also run python program on any IDE.
bash is a superset of sh. This means that bash supports features of sh and provides more functionality than sh. Although most commands do the same thing as sh. bash is not a POSIX compliant shell. It is a dialect of the POSIX shell language. Bash can run in a text window and allows the user to interpret commands to do various tasks. It has the best and most useful features of the Korn and C shells, such as directory manipulation, job control, aliases, and many others.
Like GNU software bash provides other shells, including a version of csh, Bash is the default shell. bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1). Like other GNU, bash is also quite portable. This works on any Linux/Unix-based system which has bash in the expected location. bash is more functional than sh in terms of programming and interactive use.
bash
sh
Bourne Again SHell
SHell
Developed by Brain Fox
Developed by Stephen R. Bourne
Successor of sh
Predecessor of bash
bash is the default SHELL
sh is the not default SHELL
#!/bin/bash
#!/bin/sh
It has more Functionality with up-gradation.
It has less functionality.
supports job controls.
does not support job control.
bash is not a valid POSIX shell.
sh is a valid POSIX shell.
Easy to use
not as easy as bash
less portable than sh.
more portable than bash.
Extended version of language
Original language
Bash scripting is scripting specifically for Bash
Shell scripting is scripting in any shell
supports command history.
does not supports command history.
jivendrasah
Picked
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation | [
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 26484,
"s": 25755,
"text": "bash and sh are two different shells of the Unix operating system. bash is sh, but with more features and better syntax. Bash is “Bourne Again SHell”, and is an improvement of the sh (original Bourne shell). Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems. sh provides some built-in commands. bash is a superset of sh. Shell is a command-line interface to run commands and shell scripts. Shells come in a variety of flavors, much as operating systems come in a variety of flavors. So, Shell is an interface between the user and the operating system, which helps the user to interact with the device."
},
{
"code": null,
"e": 26494,
"s": 26484,
"text": "#!/bin/sh"
},
{
"code": null,
"e": 26506,
"s": 26494,
"text": "#!/bin/bash"
},
{
"code": null,
"e": 26571,
"s": 26506,
"text": "Shell is an interface between the user and the operating system."
},
{
"code": null,
"e": 26606,
"s": 26571,
"text": "sh implements the shell interface."
},
{
"code": null,
"e": 26632,
"s": 26606,
"text": "bash is a superset of sh."
},
{
"code": null,
"e": 27026,
"s": 26632,
"text": "sh is also called Bourne Shell. sh is a command programming language described by POSIX standard. It is for UNIX or UNIX-like operating systems. It has many implementations. On most operating systems, sh is implemented by programs like dash, kash, and original Bourne Shell. sh is a Predecessor of bash. /bin/sh is an actual link to main implementations. It is a symlink in most POSIX systems."
},
{
"code": null,
"e": 27350,
"s": 27026,
"text": "sh is not a programming language itself. It is just a specification. sh is a detailed description of the syntax and semantics of the language. It doesn’t include an implementation. sh is written as a replacement for earlier UNIX shells. It’s most of the syntax is the same as the syntax of the ALGOL68 programming language."
},
{
"code": null,
"e": 27726,
"s": 27350,
"text": "We should use sh if we want our language to be compatible with multiple systems. The sh script will most like run on bash also without modifications as bash is backward compatible with sh. sh is the most portable scripting language that works on most POSIX/Unix/Linux systems. One advantage of sh is that it is guaranteed to exist on everything that purports to Unix system. "
},
{
"code": null,
"e": 28130,
"s": 27726,
"text": "bash is also a command programming language like sh. Nowadays, bash is a default login shell on most Linux-based operating systems. It is an extended version of the sh system for GNU replacement for the Bourne shell. We can also say bash is a programming language. Here think like python, we can start python in interactive mode and it behaves like a shell but we can also run python program on any IDE."
},
{
"code": null,
"e": 28603,
"s": 28130,
"text": "bash is a superset of sh. This means that bash supports features of sh and provides more functionality than sh. Although most commands do the same thing as sh. bash is not a POSIX compliant shell. It is a dialect of the POSIX shell language. Bash can run in a text window and allows the user to interpret commands to do various tasks. It has the best and most useful features of the Korn and C shells, such as directory manipulation, job control, aliases, and many others."
},
{
"code": null,
"e": 29058,
"s": 28603,
"text": "Like GNU software bash provides other shells, including a version of csh, Bash is the default shell. bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1). Like other GNU, bash is also quite portable. This works on any Linux/Unix-based system which has bash in the expected location. bash is more functional than sh in terms of programming and interactive use."
},
{
"code": null,
"e": 29063,
"s": 29058,
"text": "bash"
},
{
"code": null,
"e": 29071,
"s": 29063,
"text": "sh "
},
{
"code": null,
"e": 29090,
"s": 29071,
"text": "Bourne Again SHell"
},
{
"code": null,
"e": 29096,
"s": 29090,
"text": "SHell"
},
{
"code": null,
"e": 29119,
"s": 29096,
"text": "Developed by Brain Fox"
},
{
"code": null,
"e": 29150,
"s": 29119,
"text": "Developed by Stephen R. Bourne"
},
{
"code": null,
"e": 29166,
"s": 29150,
"text": "Successor of sh"
},
{
"code": null,
"e": 29186,
"s": 29166,
"text": "Predecessor of bash"
},
{
"code": null,
"e": 29212,
"s": 29186,
"text": "bash is the default SHELL"
},
{
"code": null,
"e": 29240,
"s": 29212,
"text": "sh is the not default SHELL"
},
{
"code": null,
"e": 29252,
"s": 29240,
"text": "#!/bin/bash"
},
{
"code": null,
"e": 29262,
"s": 29252,
"text": "#!/bin/sh"
},
{
"code": null,
"e": 29307,
"s": 29262,
"text": "It has more Functionality with up-gradation."
},
{
"code": null,
"e": 29334,
"s": 29307,
"text": "It has less functionality."
},
{
"code": null,
"e": 29357,
"s": 29334,
"text": "supports job controls."
},
{
"code": null,
"e": 29387,
"s": 29357,
"text": "does not support job control."
},
{
"code": null,
"e": 29420,
"s": 29387,
"text": "bash is not a valid POSIX shell."
},
{
"code": null,
"e": 29447,
"s": 29420,
"text": "sh is a valid POSIX shell."
},
{
"code": null,
"e": 29459,
"s": 29447,
"text": "Easy to use"
},
{
"code": null,
"e": 29479,
"s": 29459,
"text": "not as easy as bash"
},
{
"code": null,
"e": 29502,
"s": 29479,
"text": "less portable than sh."
},
{
"code": null,
"e": 29527,
"s": 29502,
"text": "more portable than bash."
},
{
"code": null,
"e": 29556,
"s": 29527,
"text": "Extended version of language"
},
{
"code": null,
"e": 29574,
"s": 29556,
"text": "Original language"
},
{
"code": null,
"e": 29624,
"s": 29574,
"text": "Bash scripting is scripting specifically for Bash"
},
{
"code": null,
"e": 29666,
"s": 29624,
"text": "Shell scripting is scripting in any shell"
},
{
"code": null,
"e": 29692,
"s": 29666,
"text": "supports command history."
},
{
"code": null,
"e": 29727,
"s": 29692,
"text": "does not supports command history."
},
{
"code": null,
"e": 29739,
"s": 29727,
"text": "jivendrasah"
},
{
"code": null,
"e": 29746,
"s": 29739,
"text": "Picked"
},
{
"code": null,
"e": 29764,
"s": 29746,
"text": "Computer Networks"
},
{
"code": null,
"e": 29783,
"s": 29764,
"text": "Difference Between"
},
{
"code": null,
"e": 29801,
"s": 29783,
"text": "Computer Networks"
},
{
"code": null,
"e": 29899,
"s": 29801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29934,
"s": 29899,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 29967,
"s": 29934,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 30005,
"s": 29967,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 30031,
"s": 30005,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 30058,
"s": 30031,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 30089,
"s": 30058,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 30129,
"s": 30089,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 30190,
"s": 30129,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30258,
"s": 30190,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Find the Kth position element of the given sequence - GeeksforGeeks | 07 Mar, 2022
Given two integers N and K, the task is to find the element at the Kth position if all odd numbers from 1 to N are written down in increasing order followed by all the even numbers from 1 to N in increasing order.Examples:
Input: N = 10, K = 3 Output: 5 The required sequence is 1, 3, 5, 7, 9, 2, 4, 6, 8 and 10.Input: N = 7, K = 7 Output: 6
Approach: It is known that the Nth even number is given by 2 * K and the Nth odd number is given by 2 * K – 1. But since the even numbers are written after (N + 1) / 2 odd numbers here. Therefore, Kth even number is given by 2 * (K – (N + 1) / 2) and the odd numbers will remain the same as 2 * K – 1Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the kth number// from the required sequenceint kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codeint main(){ int n = 7, k = 7; cout << kthNum(n, k); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the kth number// from the required sequencestatic int kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codepublic static void main(String []args){ int n = 7, k = 7; System.out.println(kthNum(n, k));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the kth number# from the required sequencedef kthNum(n, k) : # Count of odd integers # in the sequence a = (n + 1) // 2; # kth number is even if (k > a) : return (2 * (k - a)); # It is odd return (2 * k - 1); # Driver codeif __name__ == "__main__" : n = 7; k = 7; print(kthNum(n, k)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the kth number// from the required sequencestatic int kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codepublic static void Main(String []args){ int n = 7, k = 7; Console.WriteLine(kthNum(n, k));}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach // Function to return the kth number// from the required sequencefunction kthNum(n, k){ // Count of odd integers // in the sequence var a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codevar n = 7, k = 7;document.write(kthNum(n, k)); </script>
6
Time Complexity: O(1)
Auxiliary Space: O(1)
ankthon
Rajput-Ji
princiraj1992
noob2000
adnanirshad158
subham348
Constructive Algorithms
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Count all possible paths from top left to bottom right of a mXn matrix
Modular multiplicative inverse
Program to multiply two matrices
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Min Cost Path | DP-6 | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26162,
"s": 25937,
"text": "Given two integers N and K, the task is to find the element at the Kth position if all odd numbers from 1 to N are written down in increasing order followed by all the even numbers from 1 to N in increasing order.Examples: "
},
{
"code": null,
"e": 26283,
"s": 26162,
"text": "Input: N = 10, K = 3 Output: 5 The required sequence is 1, 3, 5, 7, 9, 2, 4, 6, 8 and 10.Input: N = 7, K = 7 Output: 6 "
},
{
"code": null,
"e": 26638,
"s": 26285,
"text": "Approach: It is known that the Nth even number is given by 2 * K and the Nth odd number is given by 2 * K – 1. But since the even numbers are written after (N + 1) / 2 odd numbers here. Therefore, Kth even number is given by 2 * (K – (N + 1) / 2) and the odd numbers will remain the same as 2 * K – 1Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26642,
"s": 26638,
"text": "C++"
},
{
"code": null,
"e": 26647,
"s": 26642,
"text": "Java"
},
{
"code": null,
"e": 26655,
"s": 26647,
"text": "Python3"
},
{
"code": null,
"e": 26658,
"s": 26655,
"text": "C#"
},
{
"code": null,
"e": 26669,
"s": 26658,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the kth number// from the required sequenceint kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codeint main(){ int n = 7, k = 7; cout << kthNum(n, k); return 0;}",
"e": 27115,
"s": 26669,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the kth number// from the required sequencestatic int kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codepublic static void main(String []args){ int n = 7, k = 7; System.out.println(kthNum(n, k));}} // This code is contributed by Rajput-Ji",
"e": 27603,
"s": 27115,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the kth number# from the required sequencedef kthNum(n, k) : # Count of odd integers # in the sequence a = (n + 1) // 2; # kth number is even if (k > a) : return (2 * (k - a)); # It is odd return (2 * k - 1); # Driver codeif __name__ == \"__main__\" : n = 7; k = 7; print(kthNum(n, k)); # This code is contributed by AnkitRai01",
"e": 28030,
"s": 27603,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the kth number// from the required sequencestatic int kthNum(int n, int k){ // Count of odd integers // in the sequence int a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codepublic static void Main(String []args){ int n = 7, k = 7; Console.WriteLine(kthNum(n, k));}} // This code is contributed by PrinciRaj1992",
"e": 28537,
"s": 28030,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the kth number// from the required sequencefunction kthNum(n, k){ // Count of odd integers // in the sequence var a = (n + 1) / 2; // kth number is even if (k > a) return (2 * (k - a)); // It is odd return (2 * k - 1);} // Driver codevar n = 7, k = 7;document.write(kthNum(n, k)); </script>",
"e": 28934,
"s": 28537,
"text": null
},
{
"code": null,
"e": 28936,
"s": 28934,
"text": "6"
},
{
"code": null,
"e": 28960,
"s": 28938,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28983,
"s": 28960,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 28991,
"s": 28983,
"text": "ankthon"
},
{
"code": null,
"e": 29001,
"s": 28991,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29015,
"s": 29001,
"text": "princiraj1992"
},
{
"code": null,
"e": 29024,
"s": 29015,
"text": "noob2000"
},
{
"code": null,
"e": 29039,
"s": 29024,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29049,
"s": 29039,
"text": "subham348"
},
{
"code": null,
"e": 29073,
"s": 29049,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 29080,
"s": 29073,
"text": "series"
},
{
"code": null,
"e": 29093,
"s": 29080,
"text": "Mathematical"
},
{
"code": null,
"e": 29106,
"s": 29093,
"text": "Mathematical"
},
{
"code": null,
"e": 29113,
"s": 29106,
"text": "series"
},
{
"code": null,
"e": 29211,
"s": 29113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29255,
"s": 29211,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29297,
"s": 29255,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 29368,
"s": 29297,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 29399,
"s": 29368,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 29432,
"s": 29399,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29457,
"s": 29432,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 29489,
"s": 29457,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29524,
"s": 29489,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 29570,
"s": 29524,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Cisco ASA Redistribution example - GeeksforGeeks | 22 Nov, 2021
Prerequisite – Adaptive security appliance (ASA) In real scenarios, a condition can occur where an organization routes are using more than one routing protocol (EIGRP, OSPF, or RIP). Also, static or default routing is being used. Now, the routes learned by one means (dynamic or static routing) should be redistributed to other means (dynamic routing protocol). This process is called Redistribution.
For example, If a router is operating EIGRP at one interface and RIP at another then the routes learned by EIGRP should be redistributed in RIP and vice versa.
Redistribution – It is a process of advertising a route learned by method of static routing, directly connected route, or a dynamic routing protocol into another routing protocol.
For example, Here, router2 one interface (fa0/0) is running EIGRP and another interface (fa0/1) is running OSPF then we have to advertise the routes of OSPF into EIGRP and vice-versa so that the routes learned by these routing protocols are advertised with each other. This process is called redistribution. Otherwise, router1 will not be able to learn the routes of router3 and router3 will not be able to learn routes of Router1 therefore not reachable.
Redistribution (in ASA) – We know that Cisco ASA can operate in two modes: Routed mode and transparent mode.
Routed firewall mode – By default, ASA is in routed firewall mode. In this mode, Cisco ASA behaves as router hop therefore routing can be performed in this mode. Transparent Firewall mode – In this mode, the firewall behaves as a layer 2 device. Routing and Redistribution on ASA, in routed firewall mode, is performed in the same way as it is performed on the Cisco router.
Routed firewall mode – By default, ASA is in routed firewall mode. In this mode, Cisco ASA behaves as router hop therefore routing can be performed in this mode.
Transparent Firewall mode – In this mode, the firewall behaves as a layer 2 device. Routing and Redistribution on ASA, in routed firewall mode, is performed in the same way as it is performed on the Cisco router.
Configuration example – Before getting into the configuration, remember these things:
By default, The traffic will be allowed from higher security level to lower security level but it will be denied if initiated from lower security level for higher security level. By default, the traffic allowed from higher to lower security levels will be TCP and UDP.
By default, The traffic will be allowed from higher security level to lower security level but it will be denied if initiated from lower security level for higher security level.
By default, the traffic allowed from higher to lower security levels will be TCP and UDP.
There are 4 routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address-10.1.2.1/24), Router3 (IP address-10.1.3.1/24), Router4(IP address-10.1.4.1/24) and ASA(IP address-10.1.1.2/24 and Name- INSIDE on e0, 10.1.2.2/24 and Name- OUTSIDE on e1, 10.1.3.2/24 and name -DMZ2 on e2, 10.1.4.2/24 and name -DMZ1 on e3. In this task, we will inspect ICMP from INSIDE to OUTSIDE.
Note that traffic can be allowed from lower to higher security levels either by inspection or by using an access list. Configuring IP address on Router1:
Router1(config)#int fa0/0
Router1(config-if)#ip address 10.1.1.1 255.255.255.0
Router1(config-if)#no shut
Configuring IP address on Router2.
Router2(config)#int fa0/0
Router2(config-if)#ip address 10.1.2.1 255.255.255.0
Router2(config-if)#no shut
Configuring IP address on Router3.
Router3(config)#int fa0/0
Router3(config-if)#ip address 10.1.3.1 255.255.255.0
Router3(config-if)#no shut
Configuring IP address on Router2.
Router4(config)#int fa0/0
Router4(config-if)#ip address 10.1.4.1 255.255.255.0
Router4(config-if)#no shut
Now, configuring IP addresses and names on the interfaces of ASA.
asa(config)#int e0
asa(config-if)#no shut
asa(config-if)#ip address 10.1.1.2 255.255.255.0
asa(config-if)#nameif INSIDE
asa(config-if)#security level 100
asa(config-if)#exit
asa(config)#int e1
asa(config-if)#no shut
asa(config-if)#ip address 10.1.2.2 255.255.255.0
asa(config-if)#nameif OUTSIDE
asa(config-if)#security level 0
asa(config-if)#exit
asa(config)#int e2
asa(config-if)#no shut
asa(config-if)#ip address 10.1.3.2 255.255.255.0
asa(config-if)#nameif DMZ2
asa(config-if)#security level 60
asa(config-if)#exit
asa(config)#int e3
asa(config-if)#no shut
asa(config-if)#ip address 10.1.4.2 255.255.255.0
asa(config-if)#nameif DMZ1
asa(config-if)#security level 50
Now, configuring EIGRP on Router1
Router1(config)#router eigrp 100
Router1(config-router)#network 10.1.1.0
Router1(config-router)#no auto-summary
Now, configure the default route on Router2.
Router2(config)#ip route 0.0.0.0 0.0.0.0 10.1.2.2
Configuring RIP on Router3.
Router3(config)#router rip
Router3(config-router)#network 10.1.3.0
Router3(config-router)#no auto-summary
Configuring OSPF on Router4.
Router4(config)#router OSPF 1
Router4(config-router)#network 10.1.4.0 0.0.0.255 area 0
Now, we have to enable routing on ASA.
asa(config)#router rip
asa(config-router)#network 10.1.3.0
asa(config-router)#no auto-summary
asa(config-router)#exit
asa(config)#router OSPF 1
asa(config-router)#network 10.1.4.0 0.0.0.255 area 0
asa(config-router)#exit
asa(config)#router eigrp 100
asa(config-router)#network 10.1.1.0
asa(config-router)#exit
Giving default route on ASA
asa(config)#route outside 0 0 10.1.2.1
here, OUTSIDE is the interface name and 0 0 means any IP any mask, and 10.1.2.1 is the next-hop IP address. Now, redistributing routes, in eigrp, on ASA.
asa(config)#router eigrp 100
asa(config-router)#redistribute ospf 1 metric 1 1 1 1 1
asa(config-router)#redistribute rip metric 1 1 1 1 1
asa(config-router)#redistribute static metric 1 1 1 1 1
Now, redistributing routes in OSPF.
asa(config)#router ospf 1
asa(config-router)#redistribute rip subnets
asa(config-router)#redistribute eigrp 100 subnets
asa(config-router)#default-information originate
Redistributing routes in RIP.
asa(config)#router rip
asa(config-router)#redistribute eigrp 100 metric 1
asa(config-router)#redistribute ospf 1 metric 1
asa(config-router)#default-information originate
As we have done routing, now we will inspect ICMP.
asa(config)#fixup protocol ICMP
Now, the firewall will be able to allow the ICMP echo reply coming from a lower security level for the higher security level.
Router1#ping 10.1.2.1
Not only from outside, it will allow replies (for INSIDE) from DMZ1 and DMZ2 also if the traffic is initiated from INSIDE.
tanwarsinghvaibhav
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data encryption standard (DES) | Set 1
Differences between IPv4 and IPv6
Types of Network Topology
Socket Programming in Python
TCP 3-Way Handshake Process
Implementation of Diffie-Hellman Algorithm
Types of Transmission Media
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
Hamming Code in Computer Network | [
{
"code": null,
"e": 26101,
"s": 26073,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 26503,
"s": 26101,
"text": "Prerequisite – Adaptive security appliance (ASA) In real scenarios, a condition can occur where an organization routes are using more than one routing protocol (EIGRP, OSPF, or RIP). Also, static or default routing is being used. Now, the routes learned by one means (dynamic or static routing) should be redistributed to other means (dynamic routing protocol). This process is called Redistribution. "
},
{
"code": null,
"e": 26664,
"s": 26503,
"text": "For example, If a router is operating EIGRP at one interface and RIP at another then the routes learned by EIGRP should be redistributed in RIP and vice versa. "
},
{
"code": null,
"e": 26845,
"s": 26664,
"text": "Redistribution – It is a process of advertising a route learned by method of static routing, directly connected route, or a dynamic routing protocol into another routing protocol. "
},
{
"code": null,
"e": 27302,
"s": 26845,
"text": "For example, Here, router2 one interface (fa0/0) is running EIGRP and another interface (fa0/1) is running OSPF then we have to advertise the routes of OSPF into EIGRP and vice-versa so that the routes learned by these routing protocols are advertised with each other. This process is called redistribution. Otherwise, router1 will not be able to learn the routes of router3 and router3 will not be able to learn routes of Router1 therefore not reachable. "
},
{
"code": null,
"e": 27412,
"s": 27302,
"text": "Redistribution (in ASA) – We know that Cisco ASA can operate in two modes: Routed mode and transparent mode. "
},
{
"code": null,
"e": 27789,
"s": 27412,
"text": "Routed firewall mode – By default, ASA is in routed firewall mode. In this mode, Cisco ASA behaves as router hop therefore routing can be performed in this mode. Transparent Firewall mode – In this mode, the firewall behaves as a layer 2 device. Routing and Redistribution on ASA, in routed firewall mode, is performed in the same way as it is performed on the Cisco router. "
},
{
"code": null,
"e": 27953,
"s": 27789,
"text": "Routed firewall mode – By default, ASA is in routed firewall mode. In this mode, Cisco ASA behaves as router hop therefore routing can be performed in this mode. "
},
{
"code": null,
"e": 28167,
"s": 27953,
"text": "Transparent Firewall mode – In this mode, the firewall behaves as a layer 2 device. Routing and Redistribution on ASA, in routed firewall mode, is performed in the same way as it is performed on the Cisco router. "
},
{
"code": null,
"e": 28255,
"s": 28167,
"text": "Configuration example – Before getting into the configuration, remember these things: "
},
{
"code": null,
"e": 28526,
"s": 28255,
"text": "By default, The traffic will be allowed from higher security level to lower security level but it will be denied if initiated from lower security level for higher security level. By default, the traffic allowed from higher to lower security levels will be TCP and UDP. "
},
{
"code": null,
"e": 28707,
"s": 28526,
"text": "By default, The traffic will be allowed from higher security level to lower security level but it will be denied if initiated from lower security level for higher security level. "
},
{
"code": null,
"e": 28798,
"s": 28707,
"text": "By default, the traffic allowed from higher to lower security levels will be TCP and UDP. "
},
{
"code": null,
"e": 29181,
"s": 28798,
"text": "There are 4 routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address-10.1.2.1/24), Router3 (IP address-10.1.3.1/24), Router4(IP address-10.1.4.1/24) and ASA(IP address-10.1.1.2/24 and Name- INSIDE on e0, 10.1.2.2/24 and Name- OUTSIDE on e1, 10.1.3.2/24 and name -DMZ2 on e2, 10.1.4.2/24 and name -DMZ1 on e3. In this task, we will inspect ICMP from INSIDE to OUTSIDE. "
},
{
"code": null,
"e": 29336,
"s": 29181,
"text": "Note that traffic can be allowed from lower to higher security levels either by inspection or by using an access list. Configuring IP address on Router1: "
},
{
"code": null,
"e": 29444,
"s": 29336,
"text": "Router1(config)#int fa0/0\nRouter1(config-if)#ip address 10.1.1.1 255.255.255.0 \nRouter1(config-if)#no shut "
},
{
"code": null,
"e": 29480,
"s": 29444,
"text": "Configuring IP address on Router2. "
},
{
"code": null,
"e": 29588,
"s": 29480,
"text": "Router2(config)#int fa0/0\nRouter2(config-if)#ip address 10.1.2.1 255.255.255.0 \nRouter2(config-if)#no shut "
},
{
"code": null,
"e": 29625,
"s": 29588,
"text": "Configuring IP address on Router3. "
},
{
"code": null,
"e": 29733,
"s": 29625,
"text": "Router3(config)#int fa0/0\nRouter3(config-if)#ip address 10.1.3.1 255.255.255.0 \nRouter3(config-if)#no shut "
},
{
"code": null,
"e": 29770,
"s": 29733,
"text": "Configuring IP address on Router2. "
},
{
"code": null,
"e": 29878,
"s": 29770,
"text": "Router4(config)#int fa0/0\nRouter4(config-if)#ip address 10.1.4.1 255.255.255.0 \nRouter4(config-if)#no shut "
},
{
"code": null,
"e": 29946,
"s": 29878,
"text": "Now, configuring IP addresses and names on the interfaces of ASA. "
},
{
"code": null,
"e": 30615,
"s": 29946,
"text": "asa(config)#int e0\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.1.2 255.255.255.0\nasa(config-if)#nameif INSIDE\nasa(config-if)#security level 100\nasa(config-if)#exit\nasa(config)#int e1\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.2.2 255.255.255.0\nasa(config-if)#nameif OUTSIDE\nasa(config-if)#security level 0\nasa(config-if)#exit\nasa(config)#int e2\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.3.2 255.255.255.0\nasa(config-if)#nameif DMZ2\nasa(config-if)#security level 60\nasa(config-if)#exit\nasa(config)#int e3\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.4.2 255.255.255.0\nasa(config-if)#nameif DMZ1\nasa(config-if)#security level 50"
},
{
"code": null,
"e": 30651,
"s": 30615,
"text": "Now, configuring EIGRP on Router1 "
},
{
"code": null,
"e": 30763,
"s": 30651,
"text": "Router1(config)#router eigrp 100\nRouter1(config-router)#network 10.1.1.0\nRouter1(config-router)#no auto-summary"
},
{
"code": null,
"e": 30810,
"s": 30763,
"text": "Now, configure the default route on Router2. "
},
{
"code": null,
"e": 30860,
"s": 30810,
"text": "Router2(config)#ip route 0.0.0.0 0.0.0.0 10.1.2.2"
},
{
"code": null,
"e": 30890,
"s": 30860,
"text": "Configuring RIP on Router3. "
},
{
"code": null,
"e": 30996,
"s": 30890,
"text": "Router3(config)#router rip\nRouter3(config-router)#network 10.1.3.0\nRouter3(config-router)#no auto-summary"
},
{
"code": null,
"e": 31027,
"s": 30996,
"text": "Configuring OSPF on Router4. "
},
{
"code": null,
"e": 31114,
"s": 31027,
"text": "Router4(config)#router OSPF 1\nRouter4(config-router)#network 10.1.4.0 0.0.0.255 area 0"
},
{
"code": null,
"e": 31155,
"s": 31114,
"text": "Now, we have to enable routing on ASA. "
},
{
"code": null,
"e": 31466,
"s": 31155,
"text": "asa(config)#router rip \nasa(config-router)#network 10.1.3.0\nasa(config-router)#no auto-summary\nasa(config-router)#exit\nasa(config)#router OSPF 1\nasa(config-router)#network 10.1.4.0 0.0.0.255 area 0\nasa(config-router)#exit\nasa(config)#router eigrp 100\nasa(config-router)#network 10.1.1.0\nasa(config-router)#exit"
},
{
"code": null,
"e": 31496,
"s": 31466,
"text": "Giving default route on ASA "
},
{
"code": null,
"e": 31535,
"s": 31496,
"text": "asa(config)#route outside 0 0 10.1.2.1"
},
{
"code": null,
"e": 31691,
"s": 31535,
"text": "here, OUTSIDE is the interface name and 0 0 means any IP any mask, and 10.1.2.1 is the next-hop IP address. Now, redistributing routes, in eigrp, on ASA. "
},
{
"code": null,
"e": 31886,
"s": 31691,
"text": "asa(config)#router eigrp 100\nasa(config-router)#redistribute ospf 1 metric 1 1 1 1 1\nasa(config-router)#redistribute rip metric 1 1 1 1 1 \nasa(config-router)#redistribute static metric 1 1 1 1 1"
},
{
"code": null,
"e": 31924,
"s": 31886,
"text": "Now, redistributing routes in OSPF. "
},
{
"code": null,
"e": 32094,
"s": 31924,
"text": "asa(config)#router ospf 1\nasa(config-router)#redistribute rip subnets\nasa(config-router)#redistribute eigrp 100 subnets\nasa(config-router)#default-information originate "
},
{
"code": null,
"e": 32126,
"s": 32094,
"text": "Redistributing routes in RIP. "
},
{
"code": null,
"e": 32298,
"s": 32126,
"text": "asa(config)#router rip\nasa(config-router)#redistribute eigrp 100 metric 1\nasa(config-router)#redistribute ospf 1 metric 1\nasa(config-router)#default-information originate "
},
{
"code": null,
"e": 32351,
"s": 32298,
"text": "As we have done routing, now we will inspect ICMP. "
},
{
"code": null,
"e": 32384,
"s": 32351,
"text": "asa(config)#fixup protocol ICMP "
},
{
"code": null,
"e": 32512,
"s": 32384,
"text": "Now, the firewall will be able to allow the ICMP echo reply coming from a lower security level for the higher security level. "
},
{
"code": null,
"e": 32534,
"s": 32512,
"text": "Router1#ping 10.1.2.1"
},
{
"code": null,
"e": 32658,
"s": 32534,
"text": "Not only from outside, it will allow replies (for INSIDE) from DMZ1 and DMZ2 also if the traffic is initiated from INSIDE. "
},
{
"code": null,
"e": 32677,
"s": 32658,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 32695,
"s": 32677,
"text": "Computer Networks"
},
{
"code": null,
"e": 32713,
"s": 32695,
"text": "Computer Networks"
},
{
"code": null,
"e": 32811,
"s": 32713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32850,
"s": 32811,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 32884,
"s": 32850,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 32910,
"s": 32884,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 32939,
"s": 32910,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 32967,
"s": 32939,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 33010,
"s": 32967,
"text": "Implementation of Diffie-Hellman Algorithm"
},
{
"code": null,
"e": 33038,
"s": 33010,
"text": "Types of Transmission Media"
},
{
"code": null,
"e": 33076,
"s": 33038,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 33105,
"s": 33076,
"text": "User Datagram Protocol (UDP)"
}
] |
What are transmission and propagation delay? | Network delay is defined as how much time will take a bit of data to travel from one node to another node.
Network delay can be divided into following ways −
Transmission delay
Propagation delay
Let us learn about both of them in detail.
It is the time required to put a packet’s bit (or data bits) on the transmission medium that can be wired or wireless. Transmission delay depends on the length of the packet and bandwidth of the network.
Transmission delay can be calculated as follows −
Transmission delay = Packet size / bandwidth
packet
Destination
Data line ( 1 bit per second)
We have 12,000 bits Ethernet packet being sent out on a 100mbps = 100 * 106 bps link. So the transmission delay can be calculated as − 12000/100*106 = 0.12 milliseconds
Or
Consider, bandwidth of data line = 1 bit per second
Length of package = 10 bit
Transmission delay = 10/1= 10 seconds.
It is the time required for bits to reach its destination from the start point. A propagation delay depends on the distance and propagation speed.
Consider a sender S and a receiver D, it is not necessary that the receiver receives data as soon as the sender has finished sending, therefore when the sender sends some data it reaches the receiver only after a certain amount of time and that time is called propagation delay.
data
Propagation delay
Propagation delay depends on some factors which are mentioned below −
distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)
distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)
speed of data line(v)
speed of data line(v)
Propagation delay can be calculated as follows −
Propagation delay = distance / transmission speed
We have a copper wires and optical fibres media to travel, these media have a speed about 2/3 the speed of light (i.e. speed of light = 3 * 108 m/s so speed of media = 2 * 108 m/s). We have a single wire around 5000km i.e. 5 * 106 meters. So the propagation delay can be calculated as: 5 * 106 / 2 * 108 = 0.25 milliseconds.
Or
Consider an optical fibre network where data needs to be carried along a distance of 2.1 km.
Here the speed is not mentioned, but we know the speed of data transfer in an optical fibre is 70% of the speed of light hence
Speed= velocity of light * 70%
Speed= ( 3*10^8 )*70%= 2.1 * 10^8
i.e.
Propagation delay = distance/speed=(2.1*10^3)/(2.1*10^8)
[Note 10^3 is used to convert km to m]
Propagation delay= 10^-5 sec | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "Network delay is defined as how much time will take a bit of data to travel from one node to another node."
},
{
"code": null,
"e": 1220,
"s": 1169,
"text": "Network delay can be divided into following ways −"
},
{
"code": null,
"e": 1239,
"s": 1220,
"text": "Transmission delay"
},
{
"code": null,
"e": 1257,
"s": 1239,
"text": "Propagation delay"
},
{
"code": null,
"e": 1300,
"s": 1257,
"text": "Let us learn about both of them in detail."
},
{
"code": null,
"e": 1504,
"s": 1300,
"text": "It is the time required to put a packet’s bit (or data bits) on the transmission medium that can be wired or wireless. Transmission delay depends on the length of the packet and bandwidth of the network."
},
{
"code": null,
"e": 1554,
"s": 1504,
"text": "Transmission delay can be calculated as follows −"
},
{
"code": null,
"e": 1681,
"s": 1554,
"text": "Transmission delay = Packet size / bandwidth\n packet\n Destination\n Data line ( 1 bit per second)"
},
{
"code": null,
"e": 1850,
"s": 1681,
"text": "We have 12,000 bits Ethernet packet being sent out on a 100mbps = 100 * 106 bps link. So the transmission delay can be calculated as − 12000/100*106 = 0.12 milliseconds"
},
{
"code": null,
"e": 1853,
"s": 1850,
"text": "Or"
},
{
"code": null,
"e": 1905,
"s": 1853,
"text": "Consider, bandwidth of data line = 1 bit per second"
},
{
"code": null,
"e": 1932,
"s": 1905,
"text": "Length of package = 10 bit"
},
{
"code": null,
"e": 1971,
"s": 1932,
"text": "Transmission delay = 10/1= 10 seconds."
},
{
"code": null,
"e": 2118,
"s": 1971,
"text": "It is the time required for bits to reach its destination from the start point. A propagation delay depends on the distance and propagation speed."
},
{
"code": null,
"e": 2397,
"s": 2118,
"text": "Consider a sender S and a receiver D, it is not necessary that the receiver receives data as soon as the sender has finished sending, therefore when the sender sends some data it reaches the receiver only after a certain amount of time and that time is called propagation delay."
},
{
"code": null,
"e": 2423,
"s": 2397,
"text": "data\n Propagation delay"
},
{
"code": null,
"e": 2493,
"s": 2423,
"text": "Propagation delay depends on some factors which are mentioned below −"
},
{
"code": null,
"e": 2595,
"s": 2493,
"text": "distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)"
},
{
"code": null,
"e": 2697,
"s": 2595,
"text": "distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)"
},
{
"code": null,
"e": 2719,
"s": 2697,
"text": "speed of data line(v)"
},
{
"code": null,
"e": 2741,
"s": 2719,
"text": "speed of data line(v)"
},
{
"code": null,
"e": 2790,
"s": 2741,
"text": "Propagation delay can be calculated as follows −"
},
{
"code": null,
"e": 2840,
"s": 2790,
"text": "Propagation delay = distance / transmission speed"
},
{
"code": null,
"e": 3165,
"s": 2840,
"text": "We have a copper wires and optical fibres media to travel, these media have a speed about 2/3 the speed of light (i.e. speed of light = 3 * 108 m/s so speed of media = 2 * 108 m/s). We have a single wire around 5000km i.e. 5 * 106 meters. So the propagation delay can be calculated as: 5 * 106 / 2 * 108 = 0.25 milliseconds."
},
{
"code": null,
"e": 3168,
"s": 3165,
"text": "Or"
},
{
"code": null,
"e": 3261,
"s": 3168,
"text": "Consider an optical fibre network where data needs to be carried along a distance of 2.1 km."
},
{
"code": null,
"e": 3388,
"s": 3261,
"text": "Here the speed is not mentioned, but we know the speed of data transfer in an optical fibre is 70% of the speed of light hence"
},
{
"code": null,
"e": 3583,
"s": 3388,
"text": "Speed= velocity of light * 70%\nSpeed= ( 3*10^8 )*70%= 2.1 * 10^8\ni.e.\nPropagation delay = distance/speed=(2.1*10^3)/(2.1*10^8)\n[Note 10^3 is used to convert km to m]\nPropagation delay= 10^-5 sec"
}
] |
Determining If an Object Is an Array in Java | In order to determine if an object is an Object is an array in Java, we use the isArray() and getClass() methods.
The isArray() method checks whether the passed argument is an array. It returns a boolean value, either true or false
Syntax - The isArray() method has the following syntax -
Array.isArray(obj)
The getClass() method method returns the runtime class of an object. The getClass() method is a part of the java.lang.Object class.
Declaration − The java.lang.Object.getClass() method is declared as follows −
public final Class getClass()
The getClass() method acts as the intermediate method which returns an runtime class of the object, which enables the terminal method, isArray() to verify it.
Let us see a program to check if an object is an array or not −
Live Demo
public class Example {
public static void main(String[] args) throws Exception {
String str = "Hello";
String atr[][]= new String[10][20];
System.out.println("Checking for str...");
checkArray(str);
System.out.println("Checking for atr...");
checkArray(atr);
}
public static void checkArray( Object abc) {
boolean x = abc.getClass().isArray();
if(x == true)
System.out.println("The Object is an Array");
else
System.out.println("The Object is not an Array");
}
}
Checking for str...
The Object is not an Array
Checking for atr...
The Object is an Array | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "In order to determine if an object is an Object is an array in Java, we use the isArray() and getClass() methods."
},
{
"code": null,
"e": 1294,
"s": 1176,
"text": "The isArray() method checks whether the passed argument is an array. It returns a boolean value, either true or false"
},
{
"code": null,
"e": 1351,
"s": 1294,
"text": "Syntax - The isArray() method has the following syntax -"
},
{
"code": null,
"e": 1370,
"s": 1351,
"text": "Array.isArray(obj)"
},
{
"code": null,
"e": 1502,
"s": 1370,
"text": "The getClass() method method returns the runtime class of an object. The getClass() method is a part of the java.lang.Object class."
},
{
"code": null,
"e": 1580,
"s": 1502,
"text": "Declaration − The java.lang.Object.getClass() method is declared as follows −"
},
{
"code": null,
"e": 1610,
"s": 1580,
"text": "public final Class getClass()"
},
{
"code": null,
"e": 1769,
"s": 1610,
"text": "The getClass() method acts as the intermediate method which returns an runtime class of the object, which enables the terminal method, isArray() to verify it."
},
{
"code": null,
"e": 1833,
"s": 1769,
"text": "Let us see a program to check if an object is an array or not −"
},
{
"code": null,
"e": 1844,
"s": 1833,
"text": " Live Demo"
},
{
"code": null,
"e": 2391,
"s": 1844,
"text": "public class Example {\n public static void main(String[] args) throws Exception {\n String str = \"Hello\";\n String atr[][]= new String[10][20];\n System.out.println(\"Checking for str...\");\n checkArray(str);\n System.out.println(\"Checking for atr...\");\n checkArray(atr);\n }\n public static void checkArray( Object abc) {\n boolean x = abc.getClass().isArray();\n if(x == true)\n System.out.println(\"The Object is an Array\");\n else\n System.out.println(\"The Object is not an Array\");\n }\n}"
},
{
"code": null,
"e": 2481,
"s": 2391,
"text": "Checking for str...\nThe Object is not an Array\nChecking for atr...\nThe Object is an Array"
}
] |
How to get all properties and methods available for the service in PowerShell? | To display all the properties and methods available for the get-service cmdlet you need to pipeline Get-Member (alias gm). MemberType ‘Property’ is to display the specific property like machinename, servicename, etc. and with the MemberType ‘Method’ you can perform specific operations on the object, for example, Start, Stop, Pause the service, etc.
The below command is to display all the members (properties, methods) the Get-Service.
Get-Service | Get-Member
Name MemberType
---- ----------
Name AliasProperty
RequiredServices AliasProperty
Disposed Event
Close Method
Continue Method
CreateObjRef Method
Dispose Method
Equals Method
ExecuteCommand Method
GetHashCode Method
GetLifetimeService Method
GetType Method
InitializeLifetimeService Method
Pause Method
Refresh Method
Start Method
Stop Method
WaitForStatus Method
CanPauseAndContinue Property
CanShutdown Property
CanStop Property
Container Property
DependentServices Property
DisplayName Property
MachineName Property
ServiceHandle Property
ServiceName Property
ServicesDependedOn Property
ServiceType Property
Site Property
StartType Property
Status Property
ToString ScriptMethod
To get the properties only.
Get-Service | Get-Member | where{$_.MemberType -eq "Property"}
Name MemberType
---- ----------
CanPauseAndContinue Property
CanShutdown Property
CanStop Property
Container Property
DependentServices Property
DisplayName Property
MachineName Property
ServiceHandle Property
ServiceName Property
ServicesDependedOn Property
ServiceType Property
Site Property
StartType Property
Status Property
To get the methods only.
Get-Service | Get-Member | where{$_.MemberType -eq "Method"}
Name MemberType
---- ----------
Close Method
Continue Method
CreateObjRef Method
Dispose Method
Equals Method
ExecuteCommand Method
GetHashCode Method
GetLifetimeService Method
GetType Method
InitializeLifetimeService Method
Pause Method
Refresh Method
Start Method
Stop Method
WaitForStatus Method | [
{
"code": null,
"e": 1413,
"s": 1062,
"text": "To display all the properties and methods available for the get-service cmdlet you need to pipeline Get-Member (alias gm). MemberType ‘Property’ is to display the specific property like machinename, servicename, etc. and with the MemberType ‘Method’ you can perform specific operations on the object, for example, Start, Stop, Pause the service, etc."
},
{
"code": null,
"e": 1500,
"s": 1413,
"text": "The below command is to display all the members (properties, methods) the Get-Service."
},
{
"code": null,
"e": 1525,
"s": 1500,
"text": "Get-Service | Get-Member"
},
{
"code": null,
"e": 2925,
"s": 1525,
"text": "Name MemberType\n---- ----------\nName AliasProperty\nRequiredServices AliasProperty\nDisposed Event\nClose Method\nContinue Method\nCreateObjRef Method\nDispose Method\nEquals Method\nExecuteCommand Method\nGetHashCode Method\nGetLifetimeService Method\nGetType Method\nInitializeLifetimeService Method\nPause Method\nRefresh Method\nStart Method\nStop Method\nWaitForStatus Method\nCanPauseAndContinue Property\nCanShutdown Property\nCanStop Property\nContainer Property\nDependentServices Property\nDisplayName Property\nMachineName Property\nServiceHandle Property\nServiceName Property\nServicesDependedOn Property\nServiceType Property\nSite Property\nStartType Property\nStatus Property\nToString ScriptMethod"
},
{
"code": null,
"e": 2953,
"s": 2925,
"text": "To get the properties only."
},
{
"code": null,
"e": 3017,
"s": 2953,
"text": "Get-Service | Get-Member | where{$_.MemberType -eq \"Property\"}\n"
},
{
"code": null,
"e": 3513,
"s": 3017,
"text": "Name MemberType\n---- ----------\nCanPauseAndContinue Property\nCanShutdown Property\nCanStop Property\nContainer Property\nDependentServices Property\nDisplayName Property\nMachineName Property\nServiceHandle Property\nServiceName Property\nServicesDependedOn Property\nServiceType Property\nSite Property\nStartType Property\nStatus Property"
},
{
"code": null,
"e": 3538,
"s": 3513,
"text": "To get the methods only."
},
{
"code": null,
"e": 3600,
"s": 3538,
"text": "Get-Service | Get-Member | where{$_.MemberType -eq \"Method\"}\n"
},
{
"code": null,
"e": 4229,
"s": 3600,
"text": "Name MemberType\n---- ----------\nClose Method\nContinue Method\nCreateObjRef Method\nDispose Method\nEquals Method\nExecuteCommand Method\nGetHashCode Method\nGetLifetimeService Method\nGetType Method\nInitializeLifetimeService Method\nPause Method\nRefresh Method\nStart Method\nStop Method\nWaitForStatus Method"
}
] |
How to reset or clear an edit box in Selenium? | We can reset or clear an edit box in Selenium with the help of clear() method.
Code Implementation with clear().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ResetText {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//entering text in the edit box
driver.findElement(By.cssSelector("#gsc-i- id1")).sendKeys("Selenium");
Thread.sleep(1000);
// resetting text from the edit box with clear()
driver.findElement(By.cssSelector("#gsc-i-id1")).clear();
driver.close();
}
} | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "We can reset or clear an edit box in Selenium with the help of clear() method."
},
{
"code": null,
"e": 1175,
"s": 1141,
"text": "Code Implementation with clear()."
},
{
"code": null,
"e": 2074,
"s": 1175,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ResetText {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n //entering text in the edit box\n driver.findElement(By.cssSelector(\"#gsc-i- id1\")).sendKeys(\"Selenium\");\n Thread.sleep(1000);\n // resetting text from the edit box with clear()\n driver.findElement(By.cssSelector(\"#gsc-i-id1\")).clear();\n driver.close();\n }\n}"
}
] |
Maximum sum combination from the given array - GeeksforGeeks | 20 Jul, 2021
Given an array arr[] of N integers and three integers X, Y and Z. The task is to find the maximum value of (arr[i] * X) + (arr[j] * Y) + (arr[k] * Z) where 0 ≤ i ≤ j ≤ k ≤ N – 1.
Examples:
Input: arr[] = {1, 5, -3, 4, -2}, X = 2, Y = 1, Z = -1 Output: 18 (2 * 5) + (1 * 5) + (-1 * -3) = 18 is the maximum possible sum.
Input: arr[] = {2, 4, -9, -64, 7, 3}, X = -1, Y = 1, Z = 1 Output: 78
Approach: Find the maximum and the minimum negative and positive values from the array. Also, check whether 0 is present in the array or not. Now, for the given values of X, Y and Z. Choose the values found previously from the array which maximizes the overall sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum possible// value of the given equationint maxSum(int arr[], int n, int x, int y, int z){ // To store the minimum and the maximum negative // and positive values from the array int minNeg = INT_MAX, maxNeg = INT_MAX; int minPos = INT_MIN, maxPos = INT_MIN; // To store whether 0 is present in the array bool isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = min(minNeg, arr[i]); maxNeg = max(maxNeg, arr[i]); } else { minPos = min(minPos, arr[i]); maxPos = max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != INT_MAX) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != INT_MIN) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != INT_MAX) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != INT_MIN) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != INT_MAX) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != INT_MIN) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver codeint main(){ int arr[] = { 2, 4, -9, -64, 7, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = -1, y = 1, z = 1; cout << maxSum(arr, n, x, y, z); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the maximum possible// value of the given equationstatic int maxSum(int arr[], int n, int x, int y, int z){ // To store the minimum and the maximum negative // and positive values from the array int minNeg = Integer.MAX_VALUE, maxNeg = Integer.MAX_VALUE; int minPos = Integer.MIN_VALUE, maxPos = Integer.MIN_VALUE; // To store whether 0 is present in the array boolean isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.min(minNeg, arr[i]); maxNeg = Math.max(maxNeg, arr[i]); } else { minPos = Math.min(minPos, arr[i]); maxPos = Math.max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != Integer.MAX_VALUE) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != Integer.MIN_VALUE) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != Integer.MAX_VALUE) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != Integer.MIN_VALUE) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != Integer.MAX_VALUE) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != Integer.MIN_VALUE) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 4, -9, -64, 7, 3 }; int n = arr.length; int x = -1, y = 1, z = 1; System.out.print(maxSum(arr, n, x, y, z));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # Function to return the maximum possible# value of the given equationdef maxSum(arr, n, x, y, z): # To store the minimum and the maximum negative # and positive values from the array minNeg = 10**9 maxNeg = 10**9 minPos = -10**9 maxPos = -10**9 # To store whether 0 is present in the array isZeroPresent = False # Update the values of the # above defined variables for i in range(n): if (arr[i] == 0): isZeroPresent = True elif (arr[i] < 0): minNeg = min(minNeg, arr[i]) maxNeg = max(maxNeg, arr[i]) else: minPos = min(minPos, arr[i]) maxPos = max(maxPos, arr[i]) # To store the resultant summ summ = 0 # x will not contribute to the # summ if it is equal to 0 if (x != 0): # If x is negative if (x < 0): # Either multiply it with the minimum # negative number from the array if (minNeg != 10**9): summ += (x * minNeg) # Or multiply it with the minimum # positive element if zero is # not present in the array elif (isZeroPresent == False): summ += (x * minPos) # If x is positive else: # Multiply it with the maximum # positive value from the array if (maxPos != -10**9): summ += (x * maxPos) # Or multiply it with the maximum # negative element if zero is # not present in the array elif (isZeroPresent == False): summ += (x * maxPos) # Same as x if (y != 0): if (y < 0): if (minNeg != 10**9): summ += (y * minNeg) elif (isZeroPresent == False): summ += (y * minPos) else: if (maxPos != -10**9): summ += (y * maxPos) elif (isZeroPresent == False): summ += (y * maxPos) # Same as x if (z != 0): if (z < 0): if (minNeg != 10**9): summ += (z * minNeg) elif (isZeroPresent == False): summ += (z * minPos) else: if (maxPos != -10**9): summ += (z * maxPos) elif (isZeroPresent == False): summ += (z * maxPos) return summ # Driver codearr = [2, 4, -9, -64, 7, 3]n = len(arr)x = -1y = 1z = 1 print(maxSum(arr, n, x, y, z)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the maximum possible // value of the given equation static int maxSum(int []arr, int n, int x, int y, int z) { int INT_MAX = int.MaxValue; int INT_MIN = int.MinValue; // To store the minimum and the maximum negative // and positive values from the array int minNeg = INT_MAX, maxNeg = INT_MAX; int minPos = INT_MIN, maxPos = INT_MIN; // To store whether 0 is present in the array bool isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.Min(minNeg, arr[i]); maxNeg = Math.Max(maxNeg, arr[i]); } else { minPos = Math.Min(minPos, arr[i]); maxPos = Math.Max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != INT_MAX) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != INT_MIN) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != INT_MAX) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != INT_MIN) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != INT_MAX) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != INT_MIN) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum; } // Driver code static public void Main () { int []arr = { 2, 4, -9, -64, 7, 3 }; int n = arr.Length; int x = -1, y = 1, z = 1; Console.Write(maxSum(arr, n, x, y, z)); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach // Function to return the maximum possible// value of the given equationfunction maxSum(arr, n, x, y, z) { // To store the minimum and the maximum negative // and positive values from the array let minNeg = Number.MAX_SAFE_INTEGER, maxNeg = Number.MAX_SAFE_INTEGER; let minPos = Number.MIN_SAFE_INTEGER, maxPos = Number.MIN_SAFE_INTEGER; // To store whether 0 is present in the array let isZeroPresent = false; // Update the values of the // above defined variables for (let i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.min(minNeg, arr[i]); maxNeg = Math.max(maxNeg, arr[i]); } else { minPos = Math.min(minPos, arr[i]); maxPos = Math.max(maxPos, arr[i]); } } // To store the resultant sum let sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != Number.MAX_SAFE_INTEGER) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != Number.MIN_SAFE_INTEGER) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != Number.MAX_SAFE_INTEGER) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != Number.MIN_SAFE_INTEGER) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != Number.MAX_SAFE_INTEGER) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != Number.MIN_SAFE_INTEGER) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver code let arr = [2, 4, -9, -64, 7, 3];let n = arr.length;let x = -1, y = 1, z = 1; document.write(maxSum(arr, n, x, y, z)); </script>
78
mohit kumar 29
ankthon
29AjayKumar
_saurabh_jaiswal
anikakapoor
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Building Heap from Array
Window Sliding Technique
Reversal algorithm for array rotation
1's and 2's complement of a Binary Number
Priority Queue using Binary Heap
Find duplicates in O(n) time and O(1) extra space | Set 1
Two Pointers Technique
Trapping Rain Water
Binary Tree (Array implementation) | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 24608,
"s": 24429,
"text": "Given an array arr[] of N integers and three integers X, Y and Z. The task is to find the maximum value of (arr[i] * X) + (arr[j] * Y) + (arr[k] * Z) where 0 ≤ i ≤ j ≤ k ≤ N – 1."
},
{
"code": null,
"e": 24619,
"s": 24608,
"text": "Examples: "
},
{
"code": null,
"e": 24749,
"s": 24619,
"text": "Input: arr[] = {1, 5, -3, 4, -2}, X = 2, Y = 1, Z = -1 Output: 18 (2 * 5) + (1 * 5) + (-1 * -3) = 18 is the maximum possible sum."
},
{
"code": null,
"e": 24820,
"s": 24749,
"text": "Input: arr[] = {2, 4, -9, -64, 7, 3}, X = -1, Y = 1, Z = 1 Output: 78 "
},
{
"code": null,
"e": 25086,
"s": 24820,
"text": "Approach: Find the maximum and the minimum negative and positive values from the array. Also, check whether 0 is present in the array or not. Now, for the given values of X, Y and Z. Choose the values found previously from the array which maximizes the overall sum."
},
{
"code": null,
"e": 25139,
"s": 25086,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25143,
"s": 25139,
"text": "C++"
},
{
"code": null,
"e": 25148,
"s": 25143,
"text": "Java"
},
{
"code": null,
"e": 25156,
"s": 25148,
"text": "Python3"
},
{
"code": null,
"e": 25159,
"s": 25156,
"text": "C#"
},
{
"code": null,
"e": 25170,
"s": 25159,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum possible// value of the given equationint maxSum(int arr[], int n, int x, int y, int z){ // To store the minimum and the maximum negative // and positive values from the array int minNeg = INT_MAX, maxNeg = INT_MAX; int minPos = INT_MIN, maxPos = INT_MIN; // To store whether 0 is present in the array bool isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = min(minNeg, arr[i]); maxNeg = max(maxNeg, arr[i]); } else { minPos = min(minPos, arr[i]); maxPos = max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != INT_MAX) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != INT_MIN) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != INT_MAX) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != INT_MIN) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != INT_MAX) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != INT_MIN) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver codeint main(){ int arr[] = { 2, 4, -9, -64, 7, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = -1, y = 1, z = 1; cout << maxSum(arr, n, x, y, z); return 0;}",
"e": 27955,
"s": 25170,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the maximum possible// value of the given equationstatic int maxSum(int arr[], int n, int x, int y, int z){ // To store the minimum and the maximum negative // and positive values from the array int minNeg = Integer.MAX_VALUE, maxNeg = Integer.MAX_VALUE; int minPos = Integer.MIN_VALUE, maxPos = Integer.MIN_VALUE; // To store whether 0 is present in the array boolean isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.min(minNeg, arr[i]); maxNeg = Math.max(maxNeg, arr[i]); } else { minPos = Math.min(minPos, arr[i]); maxPos = Math.max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != Integer.MAX_VALUE) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != Integer.MIN_VALUE) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != Integer.MAX_VALUE) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != Integer.MIN_VALUE) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != Integer.MAX_VALUE) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != Integer.MIN_VALUE) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 4, -9, -64, 7, 3 }; int n = arr.length; int x = -1, y = 1, z = 1; System.out.print(maxSum(arr, n, x, y, z));}} // This code is contributed by 29AjayKumar",
"e": 30975,
"s": 27955,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the maximum possible# value of the given equationdef maxSum(arr, n, x, y, z): # To store the minimum and the maximum negative # and positive values from the array minNeg = 10**9 maxNeg = 10**9 minPos = -10**9 maxPos = -10**9 # To store whether 0 is present in the array isZeroPresent = False # Update the values of the # above defined variables for i in range(n): if (arr[i] == 0): isZeroPresent = True elif (arr[i] < 0): minNeg = min(minNeg, arr[i]) maxNeg = max(maxNeg, arr[i]) else: minPos = min(minPos, arr[i]) maxPos = max(maxPos, arr[i]) # To store the resultant summ summ = 0 # x will not contribute to the # summ if it is equal to 0 if (x != 0): # If x is negative if (x < 0): # Either multiply it with the minimum # negative number from the array if (minNeg != 10**9): summ += (x * minNeg) # Or multiply it with the minimum # positive element if zero is # not present in the array elif (isZeroPresent == False): summ += (x * minPos) # If x is positive else: # Multiply it with the maximum # positive value from the array if (maxPos != -10**9): summ += (x * maxPos) # Or multiply it with the maximum # negative element if zero is # not present in the array elif (isZeroPresent == False): summ += (x * maxPos) # Same as x if (y != 0): if (y < 0): if (minNeg != 10**9): summ += (y * minNeg) elif (isZeroPresent == False): summ += (y * minPos) else: if (maxPos != -10**9): summ += (y * maxPos) elif (isZeroPresent == False): summ += (y * maxPos) # Same as x if (z != 0): if (z < 0): if (minNeg != 10**9): summ += (z * minNeg) elif (isZeroPresent == False): summ += (z * minPos) else: if (maxPos != -10**9): summ += (z * maxPos) elif (isZeroPresent == False): summ += (z * maxPos) return summ # Driver codearr = [2, 4, -9, -64, 7, 3]n = len(arr)x = -1y = 1z = 1 print(maxSum(arr, n, x, y, z)) # This code is contributed by Mohit Kumar",
"e": 33537,
"s": 30975,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum possible // value of the given equation static int maxSum(int []arr, int n, int x, int y, int z) { int INT_MAX = int.MaxValue; int INT_MIN = int.MinValue; // To store the minimum and the maximum negative // and positive values from the array int minNeg = INT_MAX, maxNeg = INT_MAX; int minPos = INT_MIN, maxPos = INT_MIN; // To store whether 0 is present in the array bool isZeroPresent = false; // Update the values of the // above defined variables for (int i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.Min(minNeg, arr[i]); maxNeg = Math.Max(maxNeg, arr[i]); } else { minPos = Math.Min(minPos, arr[i]); maxPos = Math.Max(maxPos, arr[i]); } } // To store the resultant sum int sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != INT_MAX) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != INT_MIN) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != INT_MAX) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != INT_MIN) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != INT_MAX) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != INT_MIN) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum; } // Driver code static public void Main () { int []arr = { 2, 4, -9, -64, 7, 3 }; int n = arr.Length; int x = -1, y = 1, z = 1; Console.Write(maxSum(arr, n, x, y, z)); }} // This code is contributed by AnkitRai01",
"e": 37032,
"s": 33537,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the maximum possible// value of the given equationfunction maxSum(arr, n, x, y, z) { // To store the minimum and the maximum negative // and positive values from the array let minNeg = Number.MAX_SAFE_INTEGER, maxNeg = Number.MAX_SAFE_INTEGER; let minPos = Number.MIN_SAFE_INTEGER, maxPos = Number.MIN_SAFE_INTEGER; // To store whether 0 is present in the array let isZeroPresent = false; // Update the values of the // above defined variables for (let i = 0; i < n; i++) { if (arr[i] == 0) { isZeroPresent = true; } else if (arr[i] < 0) { minNeg = Math.min(minNeg, arr[i]); maxNeg = Math.max(maxNeg, arr[i]); } else { minPos = Math.min(minPos, arr[i]); maxPos = Math.max(maxPos, arr[i]); } } // To store the resultant sum let sum = 0; // x will not contribute to the // sum if it is equal to 0 if (x != 0) { // If x is negative if (x < 0) { // Either multiply it with the minimum // negative number from the array if (minNeg != Number.MAX_SAFE_INTEGER) sum += (x * minNeg); // Or multiply it with the minimum // positive element if zero is // not present in the array else if (!isZeroPresent) sum += (x * minPos); } // If x is positive else { // Multiply it with the maximum // positive value from the array if (maxPos != Number.MIN_SAFE_INTEGER) sum += (x * maxPos); // Or multiply it with the maximum // negative element if zero is // not present in the array else if (!isZeroPresent) sum += (x * maxPos); } } // Same as x if (y != 0) { if (y < 0) { if (minNeg != Number.MAX_SAFE_INTEGER) sum += (y * minNeg); else if (!isZeroPresent) sum += (y * minPos); } else { if (maxPos != Number.MIN_SAFE_INTEGER) sum += (y * maxPos); else if (!isZeroPresent) sum += (y * maxPos); } } // Same as x if (z != 0) { if (z < 0) { if (minNeg != Number.MAX_SAFE_INTEGER) sum += (z * minNeg); else if (!isZeroPresent) sum += (z * minPos); } else { if (maxPos != Number.MIN_SAFE_INTEGER) sum += (z * maxPos); else if (!isZeroPresent) sum += (z * maxPos); } } return sum;} // Driver code let arr = [2, 4, -9, -64, 7, 3];let n = arr.length;let x = -1, y = 1, z = 1; document.write(maxSum(arr, n, x, y, z)); </script>",
"e": 39918,
"s": 37032,
"text": null
},
{
"code": null,
"e": 39921,
"s": 39918,
"text": "78"
},
{
"code": null,
"e": 39938,
"s": 39923,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 39946,
"s": 39938,
"text": "ankthon"
},
{
"code": null,
"e": 39958,
"s": 39946,
"text": "29AjayKumar"
},
{
"code": null,
"e": 39975,
"s": 39958,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 39987,
"s": 39975,
"text": "anikakapoor"
},
{
"code": null,
"e": 39994,
"s": 39987,
"text": "Arrays"
},
{
"code": null,
"e": 40001,
"s": 39994,
"text": "Arrays"
},
{
"code": null,
"e": 40099,
"s": 40001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40108,
"s": 40099,
"text": "Comments"
},
{
"code": null,
"e": 40121,
"s": 40108,
"text": "Old Comments"
},
{
"code": null,
"e": 40170,
"s": 40121,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 40195,
"s": 40170,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 40220,
"s": 40195,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 40258,
"s": 40220,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 40300,
"s": 40258,
"text": "1's and 2's complement of a Binary Number"
},
{
"code": null,
"e": 40333,
"s": 40300,
"text": "Priority Queue using Binary Heap"
},
{
"code": null,
"e": 40391,
"s": 40333,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 40414,
"s": 40391,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 40434,
"s": 40414,
"text": "Trapping Rain Water"
}
] |
Time Series Anomaly Detection with PyCaret | by Moez Ali | Towards Data Science | This is a step-by-step, beginner-friendly tutorial on detecting anomalies in time series data using PyCaret’s Unsupervised Anomaly Detection Module.
What is Anomaly Detection? Types of Anomaly Detection.
Anomaly Detection use-case in business.
Training and evaluating anomaly detection model using PyCaret.
Label anomalies and analyze the results.
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently.
PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes the experiment cycle exponentially fast and efficient.
PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it.
To learn more about PyCaret, check out their GitHub.
Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries.
PyCaret’s default installation is a slim version of pycaret which only installs hard dependencies that are listed here.
# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]
When you install the full version of pycaret, all the optional dependencies as listed here are also installed.
Anomaly Detection is a technique used for identifying rare items, events, or observations that raise suspicions by differing significantly from the majority of the data.
Typically, the anomalous items will translate to some kind of problem such as:
bank fraud,
structural defect,
medical problem,
Error, etc.
Anomaly detection algorithms can broadly be categorized into these groups:
(a) Supervised: Used when the data set has labels identifying which transactions are an anomaly and which are normal. (this is similar to a supervised classification problem).
(b) Unsupervised: Unsupervised means no labels and a model is trained on the complete data and assumes that the majority of the instances are normal.
(c) Semi-Supervised: A model is trained on normal data only (without any anomalies). When the trained model used on the new data points, it can predict whether the new data point is normal or not (based on the distribution of the data in the trained model).
PyCaret’s Anomaly Detection Module is an unsupervised machine learning module that is used for identifying rare items, events, or observations. It provides over 15 algorithms and several plots to analyze the results of trained models.
I will be using the NYC taxi passengers dataset that contains the number of taxi passengers from July 2014 to January 2015 at half-hourly intervals. You can download the dataset from here.
import pandas as pddata = pd.read_csv('https://raw.githubusercontent.com/numenta/NAB/master/data/realKnownCause/nyc_taxi.csv')data['timestamp'] = pd.to_datetime(data['timestamp'])data.head()
# create moving-averagesdata['MA48'] = data['value'].rolling(48).mean()data['MA336'] = data['value'].rolling(336).mean()# plot import plotly.express as pxfig = px.line(data, x="timestamp", y=['value', 'MA48', 'MA336'], title='NYC Taxi Trips', template = 'plotly_dark')fig.show()
Since algorithms cannot directly consume date or timestamp data, we will extract the features from the timestamp and will drop the actual timestamp column before training models.
# drop moving-average columnsdata.drop(['MA48', 'MA336'], axis=1, inplace=True)# set timestamp to indexdata.set_index('timestamp', drop=True, inplace=True)# resample timeseries to hourly data = data.resample('H').sum()# creature features from datedata['day'] = [i.day for i in data.index]data['day_name'] = [i.day_name() for i in data.index]data['day_of_year'] = [i.dayofyear for i in data.index]data['week_of_year'] = [i.weekofyear for i in data.index]data['hour'] = [i.hour for i in data.index]data['is_weekday'] = [i.isoweekday() for i in data.index]data.head()
Common to all modules in PyCaret, the setup function is the first and the only mandatory step to start any machine learning experiment in PyCaret. Besides performing some basic processing tasks by default, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link.
# init setupfrom pycaret.anomaly import *s = setup(data, session_id = 123)
Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see day_name and is_weekday is inferred as categorical and remaining as numeric. You can press enter to continue.
To check the list of all available algorithms:
# check list of available modelsmodels()
In this tutorial, I am using Isolation Forest, but you can replace the ID ‘iforest’ in the code below with any other model ID to change the algorithm. If you want to learn more about the Isolation Forest algorithm, you can refer to this.
# train modeliforest = create_model('iforest', fraction = 0.1)iforest_results = assign_model(iforest)iforest_results.head()
Notice that two new columns are appended i.e. Anomaly that contains value 1 for outlier and 0 for inlier and Anomaly_Score which is a continuous value a.k.a as decision function (internally, the algorithm calculates the score based on which the anomaly is determined).
# check anomaliesiforest_results[iforest_results['Anomaly'] == 1].head()
We can now plot anomalies on the graph to visualize.
import plotly.graph_objects as go# plot value on y-axis and date on x-axisfig = px.line(iforest_results, x=iforest_results.index, y="value", title='NYC TAXI TRIPS - UNSUPERVISED ANOMALY DETECTION', template = 'plotly_dark')# create list of outlier_datesoutlier_dates = iforest_results[iforest_results['Anomaly'] == 1].index# obtain y value of anomalies to ploty_values = [iforest_results.loc[i]['value'] for i in outlier_dates]fig.add_trace(go.Scatter(x=outlier_dates, y=y_values, mode = 'markers', name = 'Anomaly', marker=dict(color='red',size=10))) fig.show()
Notice that the model has picked several anomalies around Jan 1st which is a new year eve. The model has also detected a couple of anomalies around Jan 18— Jan 22 which is when the North American blizzard (a fast-moving disruptive blizzard) moved through the Northeast dumping 30 cm in areas around the New York City area.
If you google the dates around the other red points on the graph, you will probably be able to find the leads on why those points were picked up as anomalous by the model (hopefully).
I hope you will appreciate the ease of use and simplicity in PyCaret. In just a few lines of code and few minutes of experimentation, I have trained an unsupervised anomaly detection model and have labeled the dataset to detect anomalies on a time series data.
Next week I will be writing a tutorial on training custom models in PyCaret using PyCaret Regression Module. You can follow me on Medium, LinkedIn, and Twitter to get instant notifications whenever a new tutorial is released.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
Click on the links below to see the documentation and working examples.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining | [
{
"code": null,
"e": 196,
"s": 47,
"text": "This is a step-by-step, beginner-friendly tutorial on detecting anomalies in time series data using PyCaret’s Unsupervised Anomaly Detection Module."
},
{
"code": null,
"e": 251,
"s": 196,
"text": "What is Anomaly Detection? Types of Anomaly Detection."
},
{
"code": null,
"e": 291,
"s": 251,
"text": "Anomaly Detection use-case in business."
},
{
"code": null,
"e": 354,
"s": 291,
"text": "Training and evaluating anomaly detection model using PyCaret."
},
{
"code": null,
"e": 395,
"s": 354,
"text": "Label anomalies and analyze the results."
},
{
"code": null,
"e": 692,
"s": 395,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently."
},
{
"code": null,
"e": 874,
"s": 692,
"text": "PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes the experiment cycle exponentially fast and efficient."
},
{
"code": null,
"e": 1195,
"s": 874,
"text": "PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it."
},
{
"code": null,
"e": 1248,
"s": 1195,
"text": "To learn more about PyCaret, check out their GitHub."
},
{
"code": null,
"e": 1411,
"s": 1248,
"text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries."
},
{
"code": null,
"e": 1531,
"s": 1411,
"text": "PyCaret’s default installation is a slim version of pycaret which only installs hard dependencies that are listed here."
},
{
"code": null,
"e": 1634,
"s": 1531,
"text": "# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]"
},
{
"code": null,
"e": 1745,
"s": 1634,
"text": "When you install the full version of pycaret, all the optional dependencies as listed here are also installed."
},
{
"code": null,
"e": 1915,
"s": 1745,
"text": "Anomaly Detection is a technique used for identifying rare items, events, or observations that raise suspicions by differing significantly from the majority of the data."
},
{
"code": null,
"e": 1994,
"s": 1915,
"text": "Typically, the anomalous items will translate to some kind of problem such as:"
},
{
"code": null,
"e": 2006,
"s": 1994,
"text": "bank fraud,"
},
{
"code": null,
"e": 2025,
"s": 2006,
"text": "structural defect,"
},
{
"code": null,
"e": 2042,
"s": 2025,
"text": "medical problem,"
},
{
"code": null,
"e": 2054,
"s": 2042,
"text": "Error, etc."
},
{
"code": null,
"e": 2129,
"s": 2054,
"text": "Anomaly detection algorithms can broadly be categorized into these groups:"
},
{
"code": null,
"e": 2305,
"s": 2129,
"text": "(a) Supervised: Used when the data set has labels identifying which transactions are an anomaly and which are normal. (this is similar to a supervised classification problem)."
},
{
"code": null,
"e": 2455,
"s": 2305,
"text": "(b) Unsupervised: Unsupervised means no labels and a model is trained on the complete data and assumes that the majority of the instances are normal."
},
{
"code": null,
"e": 2713,
"s": 2455,
"text": "(c) Semi-Supervised: A model is trained on normal data only (without any anomalies). When the trained model used on the new data points, it can predict whether the new data point is normal or not (based on the distribution of the data in the trained model)."
},
{
"code": null,
"e": 2948,
"s": 2713,
"text": "PyCaret’s Anomaly Detection Module is an unsupervised machine learning module that is used for identifying rare items, events, or observations. It provides over 15 algorithms and several plots to analyze the results of trained models."
},
{
"code": null,
"e": 3137,
"s": 2948,
"text": "I will be using the NYC taxi passengers dataset that contains the number of taxi passengers from July 2014 to January 2015 at half-hourly intervals. You can download the dataset from here."
},
{
"code": null,
"e": 3328,
"s": 3137,
"text": "import pandas as pddata = pd.read_csv('https://raw.githubusercontent.com/numenta/NAB/master/data/realKnownCause/nyc_taxi.csv')data['timestamp'] = pd.to_datetime(data['timestamp'])data.head()"
},
{
"code": null,
"e": 3607,
"s": 3328,
"text": "# create moving-averagesdata['MA48'] = data['value'].rolling(48).mean()data['MA336'] = data['value'].rolling(336).mean()# plot import plotly.express as pxfig = px.line(data, x=\"timestamp\", y=['value', 'MA48', 'MA336'], title='NYC Taxi Trips', template = 'plotly_dark')fig.show()"
},
{
"code": null,
"e": 3786,
"s": 3607,
"text": "Since algorithms cannot directly consume date or timestamp data, we will extract the features from the timestamp and will drop the actual timestamp column before training models."
},
{
"code": null,
"e": 4351,
"s": 3786,
"text": "# drop moving-average columnsdata.drop(['MA48', 'MA336'], axis=1, inplace=True)# set timestamp to indexdata.set_index('timestamp', drop=True, inplace=True)# resample timeseries to hourly data = data.resample('H').sum()# creature features from datedata['day'] = [i.day for i in data.index]data['day_name'] = [i.day_name() for i in data.index]data['day_of_year'] = [i.dayofyear for i in data.index]data['week_of_year'] = [i.weekofyear for i in data.index]data['hour'] = [i.hour for i in data.index]data['is_weekday'] = [i.isoweekday() for i in data.index]data.head()"
},
{
"code": null,
"e": 4711,
"s": 4351,
"text": "Common to all modules in PyCaret, the setup function is the first and the only mandatory step to start any machine learning experiment in PyCaret. Besides performing some basic processing tasks by default, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link."
},
{
"code": null,
"e": 4786,
"s": 4711,
"text": "# init setupfrom pycaret.anomaly import *s = setup(data, session_id = 123)"
},
{
"code": null,
"e": 5051,
"s": 4786,
"text": "Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see day_name and is_weekday is inferred as categorical and remaining as numeric. You can press enter to continue."
},
{
"code": null,
"e": 5098,
"s": 5051,
"text": "To check the list of all available algorithms:"
},
{
"code": null,
"e": 5139,
"s": 5098,
"text": "# check list of available modelsmodels()"
},
{
"code": null,
"e": 5377,
"s": 5139,
"text": "In this tutorial, I am using Isolation Forest, but you can replace the ID ‘iforest’ in the code below with any other model ID to change the algorithm. If you want to learn more about the Isolation Forest algorithm, you can refer to this."
},
{
"code": null,
"e": 5501,
"s": 5377,
"text": "# train modeliforest = create_model('iforest', fraction = 0.1)iforest_results = assign_model(iforest)iforest_results.head()"
},
{
"code": null,
"e": 5770,
"s": 5501,
"text": "Notice that two new columns are appended i.e. Anomaly that contains value 1 for outlier and 0 for inlier and Anomaly_Score which is a continuous value a.k.a as decision function (internally, the algorithm calculates the score based on which the anomaly is determined)."
},
{
"code": null,
"e": 5843,
"s": 5770,
"text": "# check anomaliesiforest_results[iforest_results['Anomaly'] == 1].head()"
},
{
"code": null,
"e": 5896,
"s": 5843,
"text": "We can now plot anomalies on the graph to visualize."
},
{
"code": null,
"e": 6498,
"s": 5896,
"text": "import plotly.graph_objects as go# plot value on y-axis and date on x-axisfig = px.line(iforest_results, x=iforest_results.index, y=\"value\", title='NYC TAXI TRIPS - UNSUPERVISED ANOMALY DETECTION', template = 'plotly_dark')# create list of outlier_datesoutlier_dates = iforest_results[iforest_results['Anomaly'] == 1].index# obtain y value of anomalies to ploty_values = [iforest_results.loc[i]['value'] for i in outlier_dates]fig.add_trace(go.Scatter(x=outlier_dates, y=y_values, mode = 'markers', name = 'Anomaly', marker=dict(color='red',size=10))) fig.show()"
},
{
"code": null,
"e": 6821,
"s": 6498,
"text": "Notice that the model has picked several anomalies around Jan 1st which is a new year eve. The model has also detected a couple of anomalies around Jan 18— Jan 22 which is when the North American blizzard (a fast-moving disruptive blizzard) moved through the Northeast dumping 30 cm in areas around the New York City area."
},
{
"code": null,
"e": 7005,
"s": 6821,
"text": "If you google the dates around the other red points on the graph, you will probably be able to find the leads on why those points were picked up as anomalous by the model (hopefully)."
},
{
"code": null,
"e": 7266,
"s": 7005,
"text": "I hope you will appreciate the ease of use and simplicity in PyCaret. In just a few lines of code and few minutes of experimentation, I have trained an unsupervised anomaly detection model and have labeled the dataset to detect anomalies on a time series data."
},
{
"code": null,
"e": 7492,
"s": 7266,
"text": "Next week I will be writing a tutorial on training custom models in PyCaret using PyCaret Regression Module. You can follow me on Medium, LinkedIn, and Twitter to get instant notifications whenever a new tutorial is released."
},
{
"code": null,
"e": 7682,
"s": 7492,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 7744,
"s": 7682,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 7792,
"s": 7744,
"text": "Join us on our slack channel. Invite link here."
},
{
"code": null,
"e": 8255,
"s": 7792,
"text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE"
},
{
"code": null,
"e": 8346,
"s": 8255,
"text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 8418,
"s": 8346,
"text": "Click on the links below to see the documentation and working examples."
}
] |
How to keep your PC awake automatically using Python? - GeeksforGeeks | 03 Jan, 2021
In this article, we are going to discuss how to keep your PC awake using Python. In order to perform this task, we are going to use an external Python module.
Here we will be using a python package PyAutoGUI (cross-platform GUI automation Python module used to programmatically control the mouse & keyboard. ) This will keep your PC awake forever till you close the program. Use the below command to install this module:
pip install pyautogui
After installing the module execute the below program:
Python3
# Import required modulesimport pyautoguiimport time # FAILSAFE to FALSE feature is enabled by default # so that you can easily stop execution of # your pyautogui program by manually moving the # mouse to the upper left corner of the screen. # Once the mouse is in this location,# pyautogui will throw an exception and exit.pyautogui.FAILSAFE = False # We want to run this code for infinite # time till we stop it so we use infinite loop nowwhile True: # time.sleep(t) is used to give a break of # specified time t seconds so that its not # too frequent time.sleep(15) # This for loop is used to move the mouse # pointer to 500 pixels in this case(5*100) for i in range(0, 100): pyautogui.moveTo(0, i * 5) # This for loop is used to press keyboard keys, # in this case the harmless key shift key is # used. You can change it according to your # requirement. This works with all keys. for i in range(0, 3): pyautogui.press('shift')
On executing the above program, you will see that after the specified time in time.sleep() the mouse pointer moves to extreme left corner (can customize this too by mentioning the co-ordinates inside pyautogui.moveTo() to your preferred x co-ordinate and y co-ordinate of the screen and starts moving down.
Python-PyAutoGUI
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 24061,
"s": 23901,
"text": "In this article, we are going to discuss how to keep your PC awake using Python. In order to perform this task, we are going to use an external Python module. "
},
{
"code": null,
"e": 24323,
"s": 24061,
"text": "Here we will be using a python package PyAutoGUI (cross-platform GUI automation Python module used to programmatically control the mouse & keyboard. ) This will keep your PC awake forever till you close the program. Use the below command to install this module:"
},
{
"code": null,
"e": 24345,
"s": 24323,
"text": "pip install pyautogui"
},
{
"code": null,
"e": 24400,
"s": 24345,
"text": "After installing the module execute the below program:"
},
{
"code": null,
"e": 24408,
"s": 24400,
"text": "Python3"
},
{
"code": "# Import required modulesimport pyautoguiimport time # FAILSAFE to FALSE feature is enabled by default # so that you can easily stop execution of # your pyautogui program by manually moving the # mouse to the upper left corner of the screen. # Once the mouse is in this location,# pyautogui will throw an exception and exit.pyautogui.FAILSAFE = False # We want to run this code for infinite # time till we stop it so we use infinite loop nowwhile True: # time.sleep(t) is used to give a break of # specified time t seconds so that its not # too frequent time.sleep(15) # This for loop is used to move the mouse # pointer to 500 pixels in this case(5*100) for i in range(0, 100): pyautogui.moveTo(0, i * 5) # This for loop is used to press keyboard keys, # in this case the harmless key shift key is # used. You can change it according to your # requirement. This works with all keys. for i in range(0, 3): pyautogui.press('shift')",
"e": 25412,
"s": 24408,
"text": null
},
{
"code": null,
"e": 25719,
"s": 25412,
"text": "On executing the above program, you will see that after the specified time in time.sleep() the mouse pointer moves to extreme left corner (can customize this too by mentioning the co-ordinates inside pyautogui.moveTo() to your preferred x co-ordinate and y co-ordinate of the screen and starts moving down."
},
{
"code": null,
"e": 25736,
"s": 25719,
"text": "Python-PyAutoGUI"
},
{
"code": null,
"e": 25760,
"s": 25736,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25767,
"s": 25760,
"text": "Python"
},
{
"code": null,
"e": 25786,
"s": 25767,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25884,
"s": 25786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25893,
"s": 25884,
"text": "Comments"
},
{
"code": null,
"e": 25906,
"s": 25893,
"text": "Old Comments"
},
{
"code": null,
"e": 25938,
"s": 25906,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25994,
"s": 25938,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26036,
"s": 25994,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26078,
"s": 26036,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26114,
"s": 26078,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26136,
"s": 26114,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26175,
"s": 26136,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26202,
"s": 26175,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26233,
"s": 26202,
"text": "Python | os.path.join() method"
}
] |
Count number of substrings with numeric value greater than X - GeeksforGeeks | 25 May, 2021
Given a string ‘S’ (composed of digits) and an integer ‘X”, the task is to count all the sub-strings of ‘S’ that satisfy the following conditions:
The sub-string must not begin with the digit ‘0’.
And the numeric number it represents must be greater than ‘X’.
Note: Two ways of selecting a sub-string are different if they begin or end at different indices.
Examples:
Input: S = "471", X = 47
Output: 2
Only the sub-strings "471" and "71"
satisfy the given conditions.
Input: S = "2222", X = 97
Output: 3
Valid strings are "222", "222" and "2222".
Approach:
Iterate over each digit of the string ‘S’ and choose the digits which are greater than ‘0’.
Now, take all possible sub-strings starting from the character chosen in the previous step and convert each sub-string to an integer.
Compare the integer from the previous step to ‘X’. If the number is greater than ‘X’, then increment the count variable.
Finally, print the value of the count variable.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that counts// valid sub-stringsint count(string S, int X){ int count = 0; const int N = S.length(); for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not if (stoi(S.substr(i, len)) > X) count++; } } } return count;} // Driver codeint main(){ string S = "2222"; int X = 97; cout << count(S, X); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{// Function that counts// valid sub-stringsstatic int count(String S, int X){ int count = 0; int N = S.length(); for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S.charAt(i) != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to // int and checking if it is // greater than X or not int num = Integer.parseInt(S.substring(i, i + len)); if (num > X) count++; } } } return count;} // Driver codepublic static void main(String []args){ String S = "2222"; int X = 97; System.out.println(count(S, X));}} // This code is contributed by ihritik
# Python3 implementation of# the approach # Function that counts# valid sub-stringsdef countSubStr(S, X): cnt = 0 N = len(S) for i in range(0, N): # Only take those numbers # that do not start with '0'. if (S[i] != '0'): j = 1 while((j + i) <= N): # converting the sub-string # starting from index 'i' # and having length 'len' to # int and checking if it is # greater than X or not num = int(S[i : i + j]) if (num > X): cnt = cnt + 1 j = j + 1 return cnt; # Driver codeS = "2222";X = 97;print(countSubStr(S, X)) # This code is contributed by ihritik
// C# implementation of the approachusing System; class GFG{// Function that counts// valid sub-stringsstatic int count(string S, int X){ int count = 0; int N = S.Length; for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not int num = Int32.Parse(S.Substring(i, len)); if (num > X) count++; } } } return count;} // Driver codepublic static void Main(String []args){ string S = "2222"; int X = 97; Console.WriteLine(count(S, X));}} // This code is contributed by ihritik
<?php// PHP implementation of the approach // Function that counts// valid sub-stringsfunction countSubStr($S, $X){ $cnt = 0; $N = strlen($S); for ($i = 0; $i < $N; ++$i) { // Only take those numbers // that do not start w$ith '0'. if ($S[$i] != '0') { for ($len = 1; ($i + $len) <= $N; ++$len) { // converting the sub-str$ing // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not $num = intval(substr($S, $i, $len)); if ($num > $X) $cnt++; } } } return $cnt;} // Driver code$S = "2222";$X = 97;echo countSubStr($S, $X); // This code is contributed by ihritik?>
<script> // Javascript implementation of the approach // Function that counts// valid sub-stringsfunction count(S, X){ var count = 0; var N = S.length; for (var i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (var len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not if (parseInt(S.substring(i, i+len)) > X) count++; } } } return count;} // Driver codevar S = "2222";var X = 97;document.write( count(S, X)); </script>
3
ihritik
importantly
substring
Competitive Programming
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 15 Websites for Coding Challenges and Competitions
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Runtime Errors
Multistage Graph (Shortest Path)
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": 25127,
"s": 25099,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 25276,
"s": 25127,
"text": "Given a string ‘S’ (composed of digits) and an integer ‘X”, the task is to count all the sub-strings of ‘S’ that satisfy the following conditions: "
},
{
"code": null,
"e": 25326,
"s": 25276,
"text": "The sub-string must not begin with the digit ‘0’."
},
{
"code": null,
"e": 25389,
"s": 25326,
"text": "And the numeric number it represents must be greater than ‘X’."
},
{
"code": null,
"e": 25487,
"s": 25389,
"text": "Note: Two ways of selecting a sub-string are different if they begin or end at different indices."
},
{
"code": null,
"e": 25499,
"s": 25487,
"text": "Examples: "
},
{
"code": null,
"e": 25682,
"s": 25499,
"text": "Input: S = \"471\", X = 47\nOutput: 2\nOnly the sub-strings \"471\" and \"71\" \nsatisfy the given conditions.\n\nInput: S = \"2222\", X = 97\nOutput: 3\nValid strings are \"222\", \"222\" and \"2222\". "
},
{
"code": null,
"e": 25694,
"s": 25682,
"text": "Approach: "
},
{
"code": null,
"e": 25786,
"s": 25694,
"text": "Iterate over each digit of the string ‘S’ and choose the digits which are greater than ‘0’."
},
{
"code": null,
"e": 25920,
"s": 25786,
"text": "Now, take all possible sub-strings starting from the character chosen in the previous step and convert each sub-string to an integer."
},
{
"code": null,
"e": 26041,
"s": 25920,
"text": "Compare the integer from the previous step to ‘X’. If the number is greater than ‘X’, then increment the count variable."
},
{
"code": null,
"e": 26089,
"s": 26041,
"text": "Finally, print the value of the count variable."
},
{
"code": null,
"e": 26142,
"s": 26089,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26146,
"s": 26142,
"text": "C++"
},
{
"code": null,
"e": 26151,
"s": 26146,
"text": "Java"
},
{
"code": null,
"e": 26159,
"s": 26151,
"text": "Python3"
},
{
"code": null,
"e": 26162,
"s": 26159,
"text": "C#"
},
{
"code": null,
"e": 26166,
"s": 26162,
"text": "PHP"
},
{
"code": null,
"e": 26177,
"s": 26166,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that counts// valid sub-stringsint count(string S, int X){ int count = 0; const int N = S.length(); for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not if (stoi(S.substr(i, len)) > X) count++; } } } return count;} // Driver codeint main(){ string S = \"2222\"; int X = 97; cout << count(S, X); return 0;}",
"e": 27002,
"s": 26177,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{// Function that counts// valid sub-stringsstatic int count(String S, int X){ int count = 0; int N = S.length(); for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S.charAt(i) != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to // int and checking if it is // greater than X or not int num = Integer.parseInt(S.substring(i, i + len)); if (num > X) count++; } } } return count;} // Driver codepublic static void main(String []args){ String S = \"2222\"; int X = 97; System.out.println(count(S, X));}} // This code is contributed by ihritik",
"e": 27971,
"s": 27002,
"text": null
},
{
"code": "# Python3 implementation of# the approach # Function that counts# valid sub-stringsdef countSubStr(S, X): cnt = 0 N = len(S) for i in range(0, N): # Only take those numbers # that do not start with '0'. if (S[i] != '0'): j = 1 while((j + i) <= N): # converting the sub-string # starting from index 'i' # and having length 'len' to # int and checking if it is # greater than X or not num = int(S[i : i + j]) if (num > X): cnt = cnt + 1 j = j + 1 return cnt; # Driver codeS = \"2222\";X = 97;print(countSubStr(S, X)) # This code is contributed by ihritik",
"e": 28776,
"s": 27971,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{// Function that counts// valid sub-stringsstatic int count(string S, int X){ int count = 0; int N = S.Length; for (int i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (int len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not int num = Int32.Parse(S.Substring(i, len)); if (num > X) count++; } } } return count;} // Driver codepublic static void Main(String []args){ string S = \"2222\"; int X = 97; Console.WriteLine(count(S, X));}} // This code is contributed by ihritik",
"e": 29718,
"s": 28776,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function that counts// valid sub-stringsfunction countSubStr($S, $X){ $cnt = 0; $N = strlen($S); for ($i = 0; $i < $N; ++$i) { // Only take those numbers // that do not start w$ith '0'. if ($S[$i] != '0') { for ($len = 1; ($i + $len) <= $N; ++$len) { // converting the sub-str$ing // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not $num = intval(substr($S, $i, $len)); if ($num > $X) $cnt++; } } } return $cnt;} // Driver code$S = \"2222\";$X = 97;echo countSubStr($S, $X); // This code is contributed by ihritik?>",
"e": 30582,
"s": 29718,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that counts// valid sub-stringsfunction count(S, X){ var count = 0; var N = S.length; for (var i = 0; i < N; ++i) { // Only take those numbers // that do not start with '0'. if (S[i] != '0') { for (var len = 1; (i + len) <= N; ++len) { // converting the sub-string // starting from index 'i' // and having length 'len' to int // and checking if it is greater // than X or not if (parseInt(S.substring(i, i+len)) > X) count++; } } } return count;} // Driver codevar S = \"2222\";var X = 97;document.write( count(S, X)); </script>",
"e": 31351,
"s": 30582,
"text": null
},
{
"code": null,
"e": 31353,
"s": 31351,
"text": "3"
},
{
"code": null,
"e": 31363,
"s": 31355,
"text": "ihritik"
},
{
"code": null,
"e": 31375,
"s": 31363,
"text": "importantly"
},
{
"code": null,
"e": 31385,
"s": 31375,
"text": "substring"
},
{
"code": null,
"e": 31409,
"s": 31385,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31422,
"s": 31409,
"text": "Mathematical"
},
{
"code": null,
"e": 31430,
"s": 31422,
"text": "Strings"
},
{
"code": null,
"e": 31438,
"s": 31430,
"text": "Strings"
},
{
"code": null,
"e": 31451,
"s": 31438,
"text": "Mathematical"
},
{
"code": null,
"e": 31549,
"s": 31451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31604,
"s": 31549,
"text": "Top 15 Websites for Coding Challenges and Competitions"
},
{
"code": null,
"e": 31650,
"s": 31604,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 31708,
"s": 31650,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 31723,
"s": 31708,
"text": "Runtime Errors"
},
{
"code": null,
"e": 31756,
"s": 31723,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 31786,
"s": 31756,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31846,
"s": 31786,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31861,
"s": 31846,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31904,
"s": 31861,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to compare attributes of different objects in MongoDB object array? | To compare attributes, use letalongwithindexOfArray. Let us first create a collection with documents −
> db.demo366.insertOne(
... {
...
... "Name" : "Chris",
... "details" : [
... {
... "Id" : "John1",
... "value" : "test"
... },
... {
... "Id" : "John2",
... "value" : 18
... },
... {
... "Id" : "John3",
... "value" : 20
... }
... ]}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57ddd92ae06a1609a00ae7")
}
Display all documents from a collection with the help of find() method −
> db.demo366.find();
This will produce the following output −
{
"_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
{ "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
{ "Id" : "John3", "value" : 20 }
]
}
Following is the query to compare attributes of different objects in the MongoDB object array −
> db.demo366.find(
... {"$expr":{
... "$let":{
... "vars":{
... "john2":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John2"]}]},
... "john3":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John3"]}]}
... },
... "in":{"$lt":["$$john2.value","$$john3.value"]}}
... }})
This will produce the following output −
{
"_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
{ "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
{ "Id" : "John3", "value" : 20 }
]
} | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To compare attributes, use letalongwithindexOfArray. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1599,
"s": 1165,
"text": "> db.demo366.insertOne(\n... {\n...\n... \"Name\" : \"Chris\",\n... \"details\" : [\n... {\n... \"Id\" : \"John1\",\n... \"value\" : \"test\"\n... },\n... {\n... \"Id\" : \"John2\",\n... \"value\" : 18\n... },\n... {\n... \"Id\" : \"John3\",\n... \"value\" : 20\n... }\n... ]}\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e57ddd92ae06a1609a00ae7\")\n}"
},
{
"code": null,
"e": 1672,
"s": 1599,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1693,
"s": 1672,
"text": "> db.demo366.find();"
},
{
"code": null,
"e": 1734,
"s": 1693,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1941,
"s": 1734,
"text": "{\n \"_id\" : ObjectId(\"5e57ddd92ae06a1609a00ae7\"), \"Name\" : \"Chris\", \"details\" : [\n { \"Id\" : \"John1\", \"value\" : \"test\" }, { \"Id\" : \"John2\", \"value\" : 18 },\n { \"Id\" : \"John3\", \"value\" : 20 }\n ]\n}"
},
{
"code": null,
"e": 2037,
"s": 1941,
"text": "Following is the query to compare attributes of different objects in the MongoDB object array −"
},
{
"code": null,
"e": 2381,
"s": 2037,
"text": "> db.demo366.find(\n... {\"$expr\":{\n... \"$let\":{\n... \"vars\":{\n... \"john2\":{\"$arrayElemAt\":[\"$details\",{\"$indexOfArray\":[\"$details.Id\",\"John2\"]}]},\n... \"john3\":{\"$arrayElemAt\":[\"$details\",{\"$indexOfArray\":[\"$details.Id\",\"John3\"]}]}\n... },\n... \"in\":{\"$lt\":[\"$$john2.value\",\"$$john3.value\"]}}\n... }})"
},
{
"code": null,
"e": 2422,
"s": 2381,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2630,
"s": 2422,
"text": "{\n \"_id\" : ObjectId(\"5e57ddd92ae06a1609a00ae7\"), \"Name\" : \"Chris\", \"details\" : [\n { \"Id\" : \"John1\", \"value\" : \"test\" }, { \"Id\" : \"John2\", \"value\" : 18 },\n { \"Id\" : \"John3\", \"value\" : 20 }\n ] \n}"
}
] |
4 Libraries that can perform EDA in one line of python code | by Satyam Kumar | Towards Data Science | Exploratory data analysis (EDA) is an approach to analyze the data and find patterns, visual insights, etc. that the data set is having, before proceeding to model. One spends a lot of time doing EDA to get a better understanding of data, that can be minimized by using auto visualizations tools such as Pandas-profiling, Sweetviz, Autoviz, or D-Tale
EDA involves a lot of steps including some statistical tests, visualization of data using different kinds of plots, and many more. Some of the steps of EDA are discussed below:
Data Quality Check: Can be done using pandas library functions like describe(), info(), dtypes(), etc. It is used to find several features, its datatypes, duplicate values, missing value, etc.
Statistical Test: Some statistical tests like Pearson correlation, Spearman correlation, Kendall test, etc are done to get a correlation between the features. It can be implemented in python using the stats library.
Quantitative Test: Some quantitative test is used to find the spread of numerical features, count of categorical features. It can be implemented in python using the functions of the pandas library.
Visualization: Feature visualization is very essential to get an understanding of the data. Graphical techniques like bar plots, pie charts are used to get an understanding of categorical features, whereas scatter plots, histograms are used for numerical features.
To perform the above-mentioned tasks we need to type several lines of code. Here auto-visualization library comes into the play, which can perform all these tasks using just 1 line of code. Some of these auto-visualization tools we will discuss in this article:
Pandas-Profiling
Sweetviz
Autoviz
D-Tale
The dataset used for exploratory data analysis using the pandas-profiling library is the Titanic dataset downloaded from Kaggle.
Pandas profiling is an open-source python library that automates the EDA process and creates a detailed report. Pandas Profiling can be used easily for large datasets as it is blazingly fast and creates reports in a few seconds.
You can install pandas-profiling using PyPl:
pip install pandas-profiling
GitHub repository for pandas profiling.
The pandas-profiling library generates a report having:
An overview of the dataset
Variable properties
Interaction of variables
Correlation of variables
Missing values
Sample data
Sweetviz is an open-source python auto-visualization library that generates a report, exploring the data with the help of high-density plots. It not only automates the EDA but is also used for comparing datasets and drawing inferences from it. A comparison of two datasets can be done by treating one as training and the other as testing.
You can install Sweetviz using PyPl:
pip install sweetviz
GitHub repository for Sweetviz.
The Sweetviz library generates a report having:
An overview of the dataset
Variable properties
Categorical associations
Numerical associations
Most frequent, smallest, largest values for numerical features
Autoviz is an open-source python auto visualization library that mainly focuses on visualizing the relationship of the data by generating different types of plot.
You can install Autoviz using PyPl:
pip install autoviz
GitHub repository for Autoviz.
The Autoviz library generates a report having:
An overview of the dataset
Pairwise scatter plot of continuous variables
Distribution of categorical variables
Heatmaps of continuous variables
Average numerical variable by each categorical variable
D-Tale is an open-source python auto-visualization library. It is one of the best auto data-visualization libraries. D-Tale helps you to get a detailed EDA of the data. It also has a feature of code export, for every plot or analysis in the report.
You can install D-Tale using PyPl:
pip install dtale
GitHub repository for D-Tale.
The dtale library generates a report having:
An overview of the dataset
Custom filters
Correlation, Charts, and Heatmaps
Highlight datatypes, missing values, ranges
Code export
I prefer to do my EDA with self-defined functions using several python libraries. The above-discussed libraries should be used to speed up your work.
For beginners, it is good to start doing EDA using the pandas' library and writing python code before trying these libraries, as it is more important to be equipped with the fundamental knowledge and programming practices.
The best data auto-visualization amongst the above discussed is the DTale library, as it reports with detailed EDA, custom filters, and code export. Code export is the main highlight of this library that makes it better than others.
[1] Towards Data Science (Aug 30, 2020): EDA with 1 line of python code
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you.
satyam-kumar.medium.com
Thank You for Reading | [
{
"code": null,
"e": 522,
"s": 171,
"text": "Exploratory data analysis (EDA) is an approach to analyze the data and find patterns, visual insights, etc. that the data set is having, before proceeding to model. One spends a lot of time doing EDA to get a better understanding of data, that can be minimized by using auto visualizations tools such as Pandas-profiling, Sweetviz, Autoviz, or D-Tale"
},
{
"code": null,
"e": 699,
"s": 522,
"text": "EDA involves a lot of steps including some statistical tests, visualization of data using different kinds of plots, and many more. Some of the steps of EDA are discussed below:"
},
{
"code": null,
"e": 892,
"s": 699,
"text": "Data Quality Check: Can be done using pandas library functions like describe(), info(), dtypes(), etc. It is used to find several features, its datatypes, duplicate values, missing value, etc."
},
{
"code": null,
"e": 1108,
"s": 892,
"text": "Statistical Test: Some statistical tests like Pearson correlation, Spearman correlation, Kendall test, etc are done to get a correlation between the features. It can be implemented in python using the stats library."
},
{
"code": null,
"e": 1306,
"s": 1108,
"text": "Quantitative Test: Some quantitative test is used to find the spread of numerical features, count of categorical features. It can be implemented in python using the functions of the pandas library."
},
{
"code": null,
"e": 1571,
"s": 1306,
"text": "Visualization: Feature visualization is very essential to get an understanding of the data. Graphical techniques like bar plots, pie charts are used to get an understanding of categorical features, whereas scatter plots, histograms are used for numerical features."
},
{
"code": null,
"e": 1833,
"s": 1571,
"text": "To perform the above-mentioned tasks we need to type several lines of code. Here auto-visualization library comes into the play, which can perform all these tasks using just 1 line of code. Some of these auto-visualization tools we will discuss in this article:"
},
{
"code": null,
"e": 1850,
"s": 1833,
"text": "Pandas-Profiling"
},
{
"code": null,
"e": 1859,
"s": 1850,
"text": "Sweetviz"
},
{
"code": null,
"e": 1867,
"s": 1859,
"text": "Autoviz"
},
{
"code": null,
"e": 1874,
"s": 1867,
"text": "D-Tale"
},
{
"code": null,
"e": 2003,
"s": 1874,
"text": "The dataset used for exploratory data analysis using the pandas-profiling library is the Titanic dataset downloaded from Kaggle."
},
{
"code": null,
"e": 2232,
"s": 2003,
"text": "Pandas profiling is an open-source python library that automates the EDA process and creates a detailed report. Pandas Profiling can be used easily for large datasets as it is blazingly fast and creates reports in a few seconds."
},
{
"code": null,
"e": 2277,
"s": 2232,
"text": "You can install pandas-profiling using PyPl:"
},
{
"code": null,
"e": 2306,
"s": 2277,
"text": "pip install pandas-profiling"
},
{
"code": null,
"e": 2346,
"s": 2306,
"text": "GitHub repository for pandas profiling."
},
{
"code": null,
"e": 2402,
"s": 2346,
"text": "The pandas-profiling library generates a report having:"
},
{
"code": null,
"e": 2429,
"s": 2402,
"text": "An overview of the dataset"
},
{
"code": null,
"e": 2449,
"s": 2429,
"text": "Variable properties"
},
{
"code": null,
"e": 2474,
"s": 2449,
"text": "Interaction of variables"
},
{
"code": null,
"e": 2499,
"s": 2474,
"text": "Correlation of variables"
},
{
"code": null,
"e": 2514,
"s": 2499,
"text": "Missing values"
},
{
"code": null,
"e": 2526,
"s": 2514,
"text": "Sample data"
},
{
"code": null,
"e": 2865,
"s": 2526,
"text": "Sweetviz is an open-source python auto-visualization library that generates a report, exploring the data with the help of high-density plots. It not only automates the EDA but is also used for comparing datasets and drawing inferences from it. A comparison of two datasets can be done by treating one as training and the other as testing."
},
{
"code": null,
"e": 2902,
"s": 2865,
"text": "You can install Sweetviz using PyPl:"
},
{
"code": null,
"e": 2923,
"s": 2902,
"text": "pip install sweetviz"
},
{
"code": null,
"e": 2955,
"s": 2923,
"text": "GitHub repository for Sweetviz."
},
{
"code": null,
"e": 3003,
"s": 2955,
"text": "The Sweetviz library generates a report having:"
},
{
"code": null,
"e": 3030,
"s": 3003,
"text": "An overview of the dataset"
},
{
"code": null,
"e": 3050,
"s": 3030,
"text": "Variable properties"
},
{
"code": null,
"e": 3075,
"s": 3050,
"text": "Categorical associations"
},
{
"code": null,
"e": 3098,
"s": 3075,
"text": "Numerical associations"
},
{
"code": null,
"e": 3161,
"s": 3098,
"text": "Most frequent, smallest, largest values for numerical features"
},
{
"code": null,
"e": 3324,
"s": 3161,
"text": "Autoviz is an open-source python auto visualization library that mainly focuses on visualizing the relationship of the data by generating different types of plot."
},
{
"code": null,
"e": 3360,
"s": 3324,
"text": "You can install Autoviz using PyPl:"
},
{
"code": null,
"e": 3380,
"s": 3360,
"text": "pip install autoviz"
},
{
"code": null,
"e": 3411,
"s": 3380,
"text": "GitHub repository for Autoviz."
},
{
"code": null,
"e": 3458,
"s": 3411,
"text": "The Autoviz library generates a report having:"
},
{
"code": null,
"e": 3485,
"s": 3458,
"text": "An overview of the dataset"
},
{
"code": null,
"e": 3531,
"s": 3485,
"text": "Pairwise scatter plot of continuous variables"
},
{
"code": null,
"e": 3569,
"s": 3531,
"text": "Distribution of categorical variables"
},
{
"code": null,
"e": 3602,
"s": 3569,
"text": "Heatmaps of continuous variables"
},
{
"code": null,
"e": 3658,
"s": 3602,
"text": "Average numerical variable by each categorical variable"
},
{
"code": null,
"e": 3907,
"s": 3658,
"text": "D-Tale is an open-source python auto-visualization library. It is one of the best auto data-visualization libraries. D-Tale helps you to get a detailed EDA of the data. It also has a feature of code export, for every plot or analysis in the report."
},
{
"code": null,
"e": 3942,
"s": 3907,
"text": "You can install D-Tale using PyPl:"
},
{
"code": null,
"e": 3960,
"s": 3942,
"text": "pip install dtale"
},
{
"code": null,
"e": 3990,
"s": 3960,
"text": "GitHub repository for D-Tale."
},
{
"code": null,
"e": 4035,
"s": 3990,
"text": "The dtale library generates a report having:"
},
{
"code": null,
"e": 4062,
"s": 4035,
"text": "An overview of the dataset"
},
{
"code": null,
"e": 4077,
"s": 4062,
"text": "Custom filters"
},
{
"code": null,
"e": 4111,
"s": 4077,
"text": "Correlation, Charts, and Heatmaps"
},
{
"code": null,
"e": 4155,
"s": 4111,
"text": "Highlight datatypes, missing values, ranges"
},
{
"code": null,
"e": 4167,
"s": 4155,
"text": "Code export"
},
{
"code": null,
"e": 4317,
"s": 4167,
"text": "I prefer to do my EDA with self-defined functions using several python libraries. The above-discussed libraries should be used to speed up your work."
},
{
"code": null,
"e": 4540,
"s": 4317,
"text": "For beginners, it is good to start doing EDA using the pandas' library and writing python code before trying these libraries, as it is more important to be equipped with the fundamental knowledge and programming practices."
},
{
"code": null,
"e": 4773,
"s": 4540,
"text": "The best data auto-visualization amongst the above discussed is the DTale library, as it reports with detailed EDA, custom filters, and code export. Code export is the main highlight of this library that makes it better than others."
},
{
"code": null,
"e": 4845,
"s": 4773,
"text": "[1] Towards Data Science (Aug 30, 2020): EDA with 1 line of python code"
},
{
"code": null,
"e": 5034,
"s": 4845,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 5058,
"s": 5034,
"text": "satyam-kumar.medium.com"
}
] |
Find root of the tree where children id sum for every node is given - GeeksforGeeks | 25 May, 2021
Consider a binary tree whose nodes have ids from 1 to n where n is number of nodes in the tree. The tree is given as a collection of n pairs, where every pair represents node id and sum of children ids.Examples:
Input : 1 5
2 0
3 0
4 0
5 5
6 5
Output: 6
Explanation: In this case, two trees can
be made as follows and 6 is the root node.
6 6
\ / \
5 1 4
/ \ \
1 4 5
/ \ / \
2 3 2 3
Input : 4 0
Output: 4
Explanation: Clearly 4 does
not have any children and is the
only node i.e., the root node.
At first sight, this question appears to be a typical question of tree data structure but it can be solved as follows.Every node id appears in children sum except root. So if we do sum of all ids and subtract it from sum of all children sums, we get root.
C++
Java
Python3
C#
Javascript
// Find root of tree where children// sum for every node id is given.#include<bits/stdc++.h>using namespace std; int findRoot(pair<int, int> arr[], int n){ // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i=0; i<n; i++) root += (arr[i].first - arr[i].second); return root;} // Driver codeint main(){ pair<int, int> arr[] = {{1, 5}, {2, 0}, {3, 0}, {4, 0}, {5, 5}, {6, 5}}; int n = sizeof(arr)/sizeof(arr[0]); printf("%d\n", findRoot(arr, n)); return 0;}
// Find root of tree where children// sum for every node id is given. class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int findRoot(pair arr[], int n) { // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i = 0; i < n; i++) { root += (arr[i].first - arr[i].second); } return root; } // Driver code public static void main(String[] args) { pair arr[] = {new pair(1, 5), new pair(2, 0), new pair(3, 0), new pair(4, 0), new pair(5, 5), new pair(6, 5)}; int n = arr.length; System.out.printf("%d\n", findRoot(arr, n)); } } /* This code is contributed by PrinciRaj1992 */
"""Find root of tree where childrensum for every node id is given""" def findRoot(arr, n) : # Every node appears once as an id, and # every node except for the root appears # once in a sum. So if we subtract all # the sums from all the ids, we're left # with the root id. root = 0 for i in range(n): root += (arr[i][0] - arr[i][1]) return root # Driver Codeif __name__ == '__main__': arr = [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]] n = len(arr) print(findRoot(arr, n)) # This code is contributed# by SHUBHAMSINGH10
// C# Find root of tree where children// sum for every node id is given.using System; class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int findRoot(pair []arr, int n) { // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i = 0; i < n; i++) { root += (arr[i].first - arr[i].second); } return root; } // Driver code public static void Main(String[] args) { pair []arr = {new pair(1, 5), new pair(2, 0), new pair(3, 0), new pair(4, 0), new pair(5, 5), new pair(6, 5)}; int n = arr.Length; Console.Write("{0}\n", findRoot(arr, n)); } } /* This code is contributed by PrinciRaj1992 */
<script> // Javascript: Find root of tree where children// sum for every node id is given. /*Every node appears once as an id, andevery node except for the root appearsonce in a sum. So if we subtract allthe sums from all the ids, we're leftwith the root id. */ const findRoot = (nodeList) => { let root = 0; nodeList.forEach(element => root+=(Number(element[0]) - Number(element[1]))); return root ;} let nodeList = [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]];let root = findRoot(nodeList);document.write(root); // This code is contributed by bharathmkulkarni </script>
Output:
6
This article is contributed by Sunidhi Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHUBHAMSINGH10
princiraj1992
bharathmkulkarni
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not | [
{
"code": null,
"e": 35455,
"s": 35427,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 35669,
"s": 35455,
"text": "Consider a binary tree whose nodes have ids from 1 to n where n is number of nodes in the tree. The tree is given as a collection of n pairs, where every pair represents node id and sum of children ids.Examples: "
},
{
"code": null,
"e": 36069,
"s": 35669,
"text": "Input : 1 5\n 2 0\n 3 0\n 4 0\n 5 5\n 6 5\nOutput: 6\nExplanation: In this case, two trees can \nbe made as follows and 6 is the root node.\n 6 6\n \\ / \\\n 5 1 4\n / \\ \\\n 1 4 5\n / \\ / \\\n2 3 2 3\n\nInput : 4 0\nOutput: 4\nExplanation: Clearly 4 does \nnot have any children and is the\nonly node i.e., the root node."
},
{
"code": null,
"e": 36328,
"s": 36071,
"text": "At first sight, this question appears to be a typical question of tree data structure but it can be solved as follows.Every node id appears in children sum except root. So if we do sum of all ids and subtract it from sum of all children sums, we get root. "
},
{
"code": null,
"e": 36332,
"s": 36328,
"text": "C++"
},
{
"code": null,
"e": 36337,
"s": 36332,
"text": "Java"
},
{
"code": null,
"e": 36345,
"s": 36337,
"text": "Python3"
},
{
"code": null,
"e": 36348,
"s": 36345,
"text": "C#"
},
{
"code": null,
"e": 36359,
"s": 36348,
"text": "Javascript"
},
{
"code": "// Find root of tree where children// sum for every node id is given.#include<bits/stdc++.h>using namespace std; int findRoot(pair<int, int> arr[], int n){ // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i=0; i<n; i++) root += (arr[i].first - arr[i].second); return root;} // Driver codeint main(){ pair<int, int> arr[] = {{1, 5}, {2, 0}, {3, 0}, {4, 0}, {5, 5}, {6, 5}}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"%d\\n\", findRoot(arr, n)); return 0;}",
"e": 37016,
"s": 36359,
"text": null
},
{
"code": "// Find root of tree where children// sum for every node id is given. class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int findRoot(pair arr[], int n) { // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i = 0; i < n; i++) { root += (arr[i].first - arr[i].second); } return root; } // Driver code public static void main(String[] args) { pair arr[] = {new pair(1, 5), new pair(2, 0), new pair(3, 0), new pair(4, 0), new pair(5, 5), new pair(6, 5)}; int n = arr.length; System.out.printf(\"%d\\n\", findRoot(arr, n)); } } /* This code is contributed by PrinciRaj1992 */",
"e": 38057,
"s": 37016,
"text": null
},
{
"code": "\"\"\"Find root of tree where childrensum for every node id is given\"\"\" def findRoot(arr, n) : # Every node appears once as an id, and # every node except for the root appears # once in a sum. So if we subtract all # the sums from all the ids, we're left # with the root id. root = 0 for i in range(n): root += (arr[i][0] - arr[i][1]) return root # Driver Codeif __name__ == '__main__': arr = [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]] n = len(arr) print(findRoot(arr, n)) # This code is contributed# by SHUBHAMSINGH10",
"e": 38665,
"s": 38057,
"text": null
},
{
"code": "// C# Find root of tree where children// sum for every node id is given.using System; class GFG{ public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static int findRoot(pair []arr, int n) { // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i = 0; i < n; i++) { root += (arr[i].first - arr[i].second); } return root; } // Driver code public static void Main(String[] args) { pair []arr = {new pair(1, 5), new pair(2, 0), new pair(3, 0), new pair(4, 0), new pair(5, 5), new pair(6, 5)}; int n = arr.Length; Console.Write(\"{0}\\n\", findRoot(arr, n)); } } /* This code is contributed by PrinciRaj1992 */",
"e": 39730,
"s": 38665,
"text": null
},
{
"code": "<script> // Javascript: Find root of tree where children// sum for every node id is given. /*Every node appears once as an id, andevery node except for the root appearsonce in a sum. So if we subtract allthe sums from all the ids, we're leftwith the root id. */ const findRoot = (nodeList) => { let root = 0; nodeList.forEach(element => root+=(Number(element[0]) - Number(element[1]))); return root ;} let nodeList = [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]];let root = findRoot(nodeList);document.write(root); // This code is contributed by bharathmkulkarni </script>",
"e": 40350,
"s": 39730,
"text": null
},
{
"code": null,
"e": 40360,
"s": 40350,
"text": "Output: "
},
{
"code": null,
"e": 40362,
"s": 40360,
"text": "6"
},
{
"code": null,
"e": 40787,
"s": 40362,
"text": "This article is contributed by Sunidhi Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40802,
"s": 40787,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 40816,
"s": 40802,
"text": "princiraj1992"
},
{
"code": null,
"e": 40833,
"s": 40816,
"text": "bharathmkulkarni"
},
{
"code": null,
"e": 40838,
"s": 40833,
"text": "Tree"
},
{
"code": null,
"e": 40843,
"s": 40838,
"text": "Tree"
},
{
"code": null,
"e": 40941,
"s": 40843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40950,
"s": 40941,
"text": "Comments"
},
{
"code": null,
"e": 40963,
"s": 40950,
"text": "Old Comments"
},
{
"code": null,
"e": 41013,
"s": 40963,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 41048,
"s": 41013,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 41082,
"s": 41048,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 41111,
"s": 41082,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 41152,
"s": 41111,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 41195,
"s": 41152,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 41257,
"s": 41195,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 41290,
"s": 41257,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
Scala Iterator slice() method with example - GeeksforGeeks | 06 Jun, 2019
The slice() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class Iterator. It creates a new iterator for the interval given in the slice. The first value present in the slice indicates the start of the element in the new iterator and the second value present in the slice indicates the end.
Method Definition:def slice(from: Int, until: Int): Iterator[A]Where, from implies index of the first element and until implies index of the first element following the slice.
def slice(from: Int, until: Int): Iterator[A]
Where, from implies index of the first element and until implies index of the first element following the slice.
Return Type:It returns a new iterator with elements from from until until.
Example :
// Scala program of slice()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring a iterator val iter = Iterator(1, 2, 3, 4, 5) // Applying slice method val iter1 = iter.slice(1, 4) // Using while loop to print the // elements of new iterator while(iter1.hasNext) { // Displays output println(iter1.next()) } }}
2
3
4
Here, if the interval present in the slice is like (n, m) then the elements will be printed from the nth index till (m-1)th index. The functions hasNext and next are used here to print the elements of the new iterator.Example :
// Scala program of slice()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring a iterator val iter = Iterator(2, 4, 5, 6) // Applying slice method val iter1 = iter.slice(0, 3) // Using while loop to print the // elements of new iterator while(iter1.hasNext) { // Displays output println(iter1.next()) } }}
2
4
5
Here, the elements are printed from the index zero till the second index.
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Class and Object in Scala
Break statement in Scala
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays
Scala Constructors
How to get the first element of List in Scala | [
{
"code": null,
"e": 23637,
"s": 23609,
"text": "\n06 Jun, 2019"
},
{
"code": null,
"e": 23978,
"s": 23637,
"text": "The slice() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class Iterator. It creates a new iterator for the interval given in the slice. The first value present in the slice indicates the start of the element in the new iterator and the second value present in the slice indicates the end."
},
{
"code": null,
"e": 24154,
"s": 23978,
"text": "Method Definition:def slice(from: Int, until: Int): Iterator[A]Where, from implies index of the first element and until implies index of the first element following the slice."
},
{
"code": null,
"e": 24200,
"s": 24154,
"text": "def slice(from: Int, until: Int): Iterator[A]"
},
{
"code": null,
"e": 24313,
"s": 24200,
"text": "Where, from implies index of the first element and until implies index of the first element following the slice."
},
{
"code": null,
"e": 24388,
"s": 24313,
"text": "Return Type:It returns a new iterator with elements from from until until."
},
{
"code": null,
"e": 24398,
"s": 24388,
"text": "Example :"
},
{
"code": "// Scala program of slice()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring a iterator val iter = Iterator(1, 2, 3, 4, 5) // Applying slice method val iter1 = iter.slice(1, 4) // Using while loop to print the // elements of new iterator while(iter1.hasNext) { // Displays output println(iter1.next()) } }}",
"e": 24906,
"s": 24398,
"text": null
},
{
"code": null,
"e": 24913,
"s": 24906,
"text": "2\n3\n4\n"
},
{
"code": null,
"e": 25141,
"s": 24913,
"text": "Here, if the interval present in the slice is like (n, m) then the elements will be printed from the nth index till (m-1)th index. The functions hasNext and next are used here to print the elements of the new iterator.Example :"
},
{
"code": "// Scala program of slice()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring a iterator val iter = Iterator(2, 4, 5, 6) // Applying slice method val iter1 = iter.slice(0, 3) // Using while loop to print the // elements of new iterator while(iter1.hasNext) { // Displays output println(iter1.next()) } }}",
"e": 25642,
"s": 25141,
"text": null
},
{
"code": null,
"e": 25649,
"s": 25642,
"text": "2\n4\n5\n"
},
{
"code": null,
"e": 25723,
"s": 25649,
"text": "Here, the elements are printed from the index zero till the second index."
},
{
"code": null,
"e": 25729,
"s": 25723,
"text": "Scala"
},
{
"code": null,
"e": 25742,
"s": 25729,
"text": "Scala-Method"
},
{
"code": null,
"e": 25748,
"s": 25742,
"text": "Scala"
},
{
"code": null,
"e": 25846,
"s": 25748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25855,
"s": 25846,
"text": "Comments"
},
{
"code": null,
"e": 25868,
"s": 25855,
"text": "Old Comments"
},
{
"code": null,
"e": 25921,
"s": 25868,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 25933,
"s": 25921,
"text": "Scala Lists"
},
{
"code": null,
"e": 25959,
"s": 25933,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 25984,
"s": 25959,
"text": "Break statement in Scala"
},
{
"code": null,
"e": 26011,
"s": 25984,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 26054,
"s": 26011,
"text": "Scala String replace() method with example"
},
{
"code": null,
"e": 26073,
"s": 26054,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26088,
"s": 26073,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 26107,
"s": 26088,
"text": "Scala Constructors"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.