title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to use your own color palettes with Seaborn | by Carolina Bento | Towards Data Science
The other day I was putting together a few visualizations with seaborn, which is a great, super easy-to-use library based on Matplotlib. Even though I like seaborn’s default styles a lot, because their aesthetics are very clean, one thing I usually like to customize are the colors on the data points. I tried looking around for an end-to-end example of how to use or create a custom color palette in seaborn, but was having a hard time finding one. So I decided to use my matplotlib knowledge and gather all the information I could find about seaborn color palettes, to create my own code example/template. Hope you find it useful. As usual, you start off with beautiful dummy data 😀 import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdata = np.array([[1, 3, 'weekday'], [2, 2.5, 'weekday'],[3, 2.7, 'weekend'], [4, 2.8, 'weekend'], [5, 3, 'weekday'], [6, 3.1, 'weekday'], [7, 3, 'weekday'], [8, 3.1, 'weekday'], [9, 3.1, 'weekday'], [10, 3.1, 'weekend']])# Creating a data frame with the raw datadataset = pd.DataFrame(data, columns=['day', 'miles_walked', 'day_category']) If you want to take a peek at the dataset print(dataset) And you’ll see something like this seaborn and matplotlib have a lot of different color palettes to choose from. In this example I’m going to use the Paired palette. # Set the color palettesns.set_palette(sns.color_palette("Paired"))# Plot the data, specifying a different color for data points in# each of the day categories (weekday and weekend)ax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category')# Customize the axes and titleax.set_title("Miles walked")ax.set_xlabel("day")ax.set_ylabel("total miles")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show() Using an existing color palette, the only thing you need to do is to set it before calling the plot methods, and any other customization you’d like. If you’d like to use a particular set of colors, either because they’re your favorite colors or are part of a style-guide you’re using, you can do that too! # Create an array with the colors you want to usecolors = ["#FF0B04", "#4374B3"]# Set your custom color palettesns.set_palette(sns.color_palette(colors))# And then, from here onwards, it's exactly like the previous example# Plot the data, specifying a different color for data points in# each of the day categories (weekday and weekend)ax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category')# Customize the axes and titleax.set_title("Miles walked")ax.set_xlabel("day")ax.set_ylabel("total miles")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show() If you’d like to use your own color palette across multiple plots you can also use the parameter palette in the seaborn plots, and refer to your custom palette throughout your code. # Create an array with the colors you want to usecolors = ["#FF0B04", "#4374B3"]# Set your custom color palettecustomPalette = sns.set_palette(sns.color_palette(colors))# Use the parameter palette and use your own palette across all your# plotsax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category', palette=customPalette)# Customize the axes and titleax.set_title("Miles walked")ax.set_xlabel("day")ax.set_ylabel("total miles")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show() This will result in the same plot as above! But now you can use the same color palette by referring to customPalette in any of your seaborn plots. That’s it! A nice way to customize your plots and make your visualizations more insightful. Thanks for reading!
[ { "code": null, "e": 309, "s": 172, "text": "The other day I was putting together a few visualizations with seaborn, which is a great, super easy-to-use library based on Matplotlib." }, { "code": null, "e": 474, "s": 309, "text": "Even though I like seaborn’s default styles a lot, because their aesthetics are very clean, one thing I usually like to customize are the colors on the data points." }, { "code": null, "e": 622, "s": 474, "text": "I tried looking around for an end-to-end example of how to use or create a custom color palette in seaborn, but was having a hard time finding one." }, { "code": null, "e": 780, "s": 622, "text": "So I decided to use my matplotlib knowledge and gather all the information I could find about seaborn color palettes, to create my own code example/template." }, { "code": null, "e": 805, "s": 780, "text": "Hope you find it useful." }, { "code": null, "e": 857, "s": 805, "text": "As usual, you start off with beautiful dummy data 😀" }, { "code": null, "e": 1286, "s": 857, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdata = np.array([[1, 3, 'weekday'], [2, 2.5, 'weekday'],[3, 2.7, 'weekend'], [4, 2.8, 'weekend'], [5, 3, 'weekday'], [6, 3.1, 'weekday'], [7, 3, 'weekday'], [8, 3.1, 'weekday'], [9, 3.1, 'weekday'], [10, 3.1, 'weekend']])# Creating a data frame with the raw datadataset = pd.DataFrame(data, columns=['day', 'miles_walked', 'day_category'])" }, { "code": null, "e": 1328, "s": 1286, "text": "If you want to take a peek at the dataset" }, { "code": null, "e": 1343, "s": 1328, "text": "print(dataset)" }, { "code": null, "e": 1378, "s": 1343, "text": "And you’ll see something like this" }, { "code": null, "e": 1509, "s": 1378, "text": "seaborn and matplotlib have a lot of different color palettes to choose from. In this example I’m going to use the Paired palette." }, { "code": null, "e": 1990, "s": 1509, "text": "# Set the color palettesns.set_palette(sns.color_palette(\"Paired\"))# Plot the data, specifying a different color for data points in# each of the day categories (weekday and weekend)ax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category')# Customize the axes and titleax.set_title(\"Miles walked\")ax.set_xlabel(\"day\")ax.set_ylabel(\"total miles\")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show()" }, { "code": null, "e": 2139, "s": 1990, "text": "Using an existing color palette, the only thing you need to do is to set it before calling the plot methods, and any other customization you’d like." }, { "code": null, "e": 2296, "s": 2139, "text": "If you’d like to use a particular set of colors, either because they’re your favorite colors or are part of a style-guide you’re using, you can do that too!" }, { "code": null, "e": 2932, "s": 2296, "text": "# Create an array with the colors you want to usecolors = [\"#FF0B04\", \"#4374B3\"]# Set your custom color palettesns.set_palette(sns.color_palette(colors))# And then, from here onwards, it's exactly like the previous example# Plot the data, specifying a different color for data points in# each of the day categories (weekday and weekend)ax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category')# Customize the axes and titleax.set_title(\"Miles walked\")ax.set_xlabel(\"day\")ax.set_ylabel(\"total miles\")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show()" }, { "code": null, "e": 3114, "s": 2932, "text": "If you’d like to use your own color palette across multiple plots you can also use the parameter palette in the seaborn plots, and refer to your custom palette throughout your code." }, { "code": null, "e": 3681, "s": 3114, "text": "# Create an array with the colors you want to usecolors = [\"#FF0B04\", \"#4374B3\"]# Set your custom color palettecustomPalette = sns.set_palette(sns.color_palette(colors))# Use the parameter palette and use your own palette across all your# plotsax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category', palette=customPalette)# Customize the axes and titleax.set_title(\"Miles walked\")ax.set_xlabel(\"day\")ax.set_ylabel(\"total miles\")# Remove top and right bordersax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)plt.show()" }, { "code": null, "e": 3828, "s": 3681, "text": "This will result in the same plot as above! But now you can use the same color palette by referring to customPalette in any of your seaborn plots." }, { "code": null, "e": 3920, "s": 3828, "text": "That’s it! A nice way to customize your plots and make your visualizations more insightful." } ]
How to get the width of the Tkinter widget?
Tkinter widgets are supposed to be present in the Tkinter application window. All the widgets can be configured and customized by using predefined properties or functions. To get the width of a widget in a Tkinter application, we can use winfo_width() method. It returns the width of the widget which can be printed later as the output. #Import the required libraries from tkinter import * #Create an instance of Tkinter Frame win = Tk() #Set the geometry win.geometry("700x350") #Set the default color of the window win.config(bg='#aad5df') #Create a Label to display the text label=Label(win, text= "Hello World!",font= ('Helvetica 18 bold'), background= 'white', foreground='purple1') label.pack(pady = 50) win.update() #Return and print the width of label widget width = label.winfo_width() print("The width of the label is:", width, "pixels") win.mainloop() Running the above code will display a window that contains a Label widget. When we compile the code, it will print the width of the label widget on the console. The width of the label is: 148 pixels
[ { "code": null, "e": 1234, "s": 1062, "text": "Tkinter widgets are supposed to be present in the Tkinter application window. All the widgets can be configured and customized by using predefined properties or functions." }, { "code": null, "e": 1399, "s": 1234, "text": "To get the width of a widget in a Tkinter application, we can use winfo_width() method. It returns the width of the widget which can be printed later as the output." }, { "code": null, "e": 1932, "s": 1399, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry\nwin.geometry(\"700x350\")\n\n#Set the default color of the window\nwin.config(bg='#aad5df')\n\n#Create a Label to display the text\nlabel=Label(win, text= \"Hello World!\",font= ('Helvetica 18 bold'), background= 'white', foreground='purple1')\nlabel.pack(pady = 50)\n\nwin.update()\n\n#Return and print the width of label widget\nwidth = label.winfo_width()\nprint(\"The width of the label is:\", width, \"pixels\")\n\nwin.mainloop()" }, { "code": null, "e": 2007, "s": 1932, "text": "Running the above code will display a window that contains a Label widget." }, { "code": null, "e": 2093, "s": 2007, "text": "When we compile the code, it will print the width of the label widget on the console." }, { "code": null, "e": 2131, "s": 2093, "text": "The width of the label is: 148 pixels" } ]
Python Interactive Network Visualization Using NetworkX, Plotly, and Dash | by Jiahui Wang | Towards Data Science
They say a graph is more than a thousand words. I totally agree with it. I would prefer to look at a network graph, rather than reading through lengthy documents, to understand a complicated network pattern. This post is about a Python interactive network visualization application. In the first half, it covers the network visualization application features and a introduction of the tools I used for developing this application. In the second half, technical details on how to use NetworkX, Plotly, and Dash are discussed. A network graph reveals patterns and helps to detect anomalies. There is huge potential for network visualization applications in finance, and examples include fraud surveillance and money laundry monitoring. For this project, I will create a dummy dataset of transactions, and build a network visualization application to interactively plot graphs showing these transactions. Firstly, this application will read in the dummy transaction dataset, and generate graphical representation of the transaction network. Here, I want to customize the graphical representation, such as the edges are color-coded according to transaction time, and the edge width are varied according to transaction amount. In this way, it is easy to quickly understand the transaction network graph. Secondly, it will be an interactive application. When the user hovers on a node or edge, rich information will show. In addition, the user should be able to type in the account to search and the time range to show. Then, in response to the user’s input, the application will show transaction network graph accordingly. I find several useful python packages to enable the development of this application, including NetworkX, Plotly, and Dash. This session will cover a brief introduction of these libraries, as well as discuss about how they are useful for the development of this application. 2.1 Graph Theory and NetworkX To represent a transaction network, a graph consists of nodes and edges. Here, the nodes represent accounts, and the associated attributes include customer name and account type. The edges are transactions with associated attributes of transaction date and transaction amount. The transaction network is a directed graph, with each edge pointing from the source account to the target account. NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It allows quick building and visualization of a graph with just a few lines of codes: import networkx as nximport matplotlib.pyplot as pltG = nx.Graph()G.add_edge(1,2)G.add_edge(1,3)nx.draw(G, with_labels=True)plt.show() Apart from building a simple graph with the inline data, NetworkX also supports more complicated graph with dataset imported from csv or database. Here, I import the dummy csv files containing the transaction records, and built transaction network using NetworkX. 2.2 Interactive Figure and Plotly Python comes with several useful plotting libraries. Unlike the static Matplotlib and Seaborn libraries, Plotly makes interactive graphs. It supports many common chart types, including line plots, scatter plots, bar charts, histograms and heatmaps. Together with ipywidgets, it allows interactive data analysis in Jupyter notebook. 2.3 Reactive Web Applications and Dash Jupyter notebook is popular among data scientists. But I want to move one step further, to make the application accessible to other stackholders, who may not neccessarily have the background of data analytics. Web application becomes a good choice, as everyone can easily access the web applications using just the browser. Then, I find Dash, which is a open source Python library for creating reactive web applications. Dash allows seamless integration of Python data analysis code with front-end HTML, CSS, and Javascript. With the Python interface and reactive decorators provided by Dash, the Python data analysis code is binded to the interactive web-based components. Since Dash is built on Flask framework and React.js for frontend rendering, I can easily access massive support from the open source community. Last but not least, Dash is fully compatible with Plotly, which means I can integrate the network graph created with Plotly as a component in the Dash application and further add other web-based components to interact with my data analysis code. Now, let’s move on to the real coding! 3.1 Initialize The Dash App Since Dash is built on Flask framework, it is not surprising to see almost the same syntax to start a Dash application as to start a Flask application. 3.2 Define The Layout With the Python interface dash_html_components and dash_core_components, HTML and interactive web-based components are easily integrated to the Python analysis code. Here, the layout design follows Bootstrap grid system. This transaction network visualization app includes components of RangeSlider (to define time range), Input box (to type in the account to search), Plotly graph (to show the transaction network according to the user input), Hover box (to display the detailed information when the user hover on the graph), and Click box(to display the detailed information when the user click on the graph). 3.3 Bind to The Analysis Code When the user makes changes to the RangeSlider or the Input box, the Plotly figure will change accordingly. When the user hovers or clicks on the node or edge in the Plotly figure, the Hover box and the Click box display the detailed information associated with the node or edge. 3.4 Define The Plotly Graph Here, the code defines how to build the transaction network, initiate the Plotly graph, as well as how to change the Plotly graph in response to the user’s input. Basically, the code here define the logic of the network graph. Firstly, import the dataset and transform date string to Datetime object which Python understands. Then, build the network using NetworkX. Define node with Plotly. Define edge with Plotly. Here, to define the customized edge is not as straight-forward as defining the node. The edges are customized in two ways: the color of the edge represents the time of the transaction, the early the transaction, the lighter the edge color; In addition, the width of the edge represents transaction amount, where wider edges have larger transaction amount. Define the invisible middle point on the edge, to allow hover effect on the edge. Since Dash only allows hover effect on data points, I add an invisible middle point on the edge to create an additional data point on the edge. Finally, define the layout of the Plotly graph. The final transaction network visualization app works like: If you are interested in the code, please check it out on Github.
[ { "code": null, "e": 380, "s": 172, "text": "They say a graph is more than a thousand words. I totally agree with it. I would prefer to look at a network graph, rather than reading through lengthy documents, to understand a complicated network pattern." }, { "code": null, "e": 697, "s": 380, "text": "This post is about a Python interactive network visualization application. In the first half, it covers the network visualization application features and a introduction of the tools I used for developing this application. In the second half, technical details on how to use NetworkX, Plotly, and Dash are discussed." }, { "code": null, "e": 1074, "s": 697, "text": "A network graph reveals patterns and helps to detect anomalies. There is huge potential for network visualization applications in finance, and examples include fraud surveillance and money laundry monitoring. For this project, I will create a dummy dataset of transactions, and build a network visualization application to interactively plot graphs showing these transactions." }, { "code": null, "e": 1471, "s": 1074, "text": "Firstly, this application will read in the dummy transaction dataset, and generate graphical representation of the transaction network. Here, I want to customize the graphical representation, such as the edges are color-coded according to transaction time, and the edge width are varied according to transaction amount. In this way, it is easy to quickly understand the transaction network graph." }, { "code": null, "e": 1790, "s": 1471, "text": "Secondly, it will be an interactive application. When the user hovers on a node or edge, rich information will show. In addition, the user should be able to type in the account to search and the time range to show. Then, in response to the user’s input, the application will show transaction network graph accordingly." }, { "code": null, "e": 2064, "s": 1790, "text": "I find several useful python packages to enable the development of this application, including NetworkX, Plotly, and Dash. This session will cover a brief introduction of these libraries, as well as discuss about how they are useful for the development of this application." }, { "code": null, "e": 2094, "s": 2064, "text": "2.1 Graph Theory and NetworkX" }, { "code": null, "e": 2487, "s": 2094, "text": "To represent a transaction network, a graph consists of nodes and edges. Here, the nodes represent accounts, and the associated attributes include customer name and account type. The edges are transactions with associated attributes of transaction date and transaction amount. The transaction network is a directed graph, with each edge pointing from the source account to the target account." }, { "code": null, "e": 2707, "s": 2487, "text": "NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It allows quick building and visualization of a graph with just a few lines of codes:" }, { "code": null, "e": 2842, "s": 2707, "text": "import networkx as nximport matplotlib.pyplot as pltG = nx.Graph()G.add_edge(1,2)G.add_edge(1,3)nx.draw(G, with_labels=True)plt.show()" }, { "code": null, "e": 3106, "s": 2842, "text": "Apart from building a simple graph with the inline data, NetworkX also supports more complicated graph with dataset imported from csv or database. Here, I import the dummy csv files containing the transaction records, and built transaction network using NetworkX." }, { "code": null, "e": 3140, "s": 3106, "text": "2.2 Interactive Figure and Plotly" }, { "code": null, "e": 3472, "s": 3140, "text": "Python comes with several useful plotting libraries. Unlike the static Matplotlib and Seaborn libraries, Plotly makes interactive graphs. It supports many common chart types, including line plots, scatter plots, bar charts, histograms and heatmaps. Together with ipywidgets, it allows interactive data analysis in Jupyter notebook." }, { "code": null, "e": 3511, "s": 3472, "text": "2.3 Reactive Web Applications and Dash" }, { "code": null, "e": 3835, "s": 3511, "text": "Jupyter notebook is popular among data scientists. But I want to move one step further, to make the application accessible to other stackholders, who may not neccessarily have the background of data analytics. Web application becomes a good choice, as everyone can easily access the web applications using just the browser." }, { "code": null, "e": 4575, "s": 3835, "text": "Then, I find Dash, which is a open source Python library for creating reactive web applications. Dash allows seamless integration of Python data analysis code with front-end HTML, CSS, and Javascript. With the Python interface and reactive decorators provided by Dash, the Python data analysis code is binded to the interactive web-based components. Since Dash is built on Flask framework and React.js for frontend rendering, I can easily access massive support from the open source community. Last but not least, Dash is fully compatible with Plotly, which means I can integrate the network graph created with Plotly as a component in the Dash application and further add other web-based components to interact with my data analysis code." }, { "code": null, "e": 4614, "s": 4575, "text": "Now, let’s move on to the real coding!" }, { "code": null, "e": 4642, "s": 4614, "text": "3.1 Initialize The Dash App" }, { "code": null, "e": 4794, "s": 4642, "text": "Since Dash is built on Flask framework, it is not surprising to see almost the same syntax to start a Dash application as to start a Flask application." }, { "code": null, "e": 4816, "s": 4794, "text": "3.2 Define The Layout" }, { "code": null, "e": 5428, "s": 4816, "text": "With the Python interface dash_html_components and dash_core_components, HTML and interactive web-based components are easily integrated to the Python analysis code. Here, the layout design follows Bootstrap grid system. This transaction network visualization app includes components of RangeSlider (to define time range), Input box (to type in the account to search), Plotly graph (to show the transaction network according to the user input), Hover box (to display the detailed information when the user hover on the graph), and Click box(to display the detailed information when the user click on the graph)." }, { "code": null, "e": 5458, "s": 5428, "text": "3.3 Bind to The Analysis Code" }, { "code": null, "e": 5738, "s": 5458, "text": "When the user makes changes to the RangeSlider or the Input box, the Plotly figure will change accordingly. When the user hovers or clicks on the node or edge in the Plotly figure, the Hover box and the Click box display the detailed information associated with the node or edge." }, { "code": null, "e": 5766, "s": 5738, "text": "3.4 Define The Plotly Graph" }, { "code": null, "e": 5993, "s": 5766, "text": "Here, the code defines how to build the transaction network, initiate the Plotly graph, as well as how to change the Plotly graph in response to the user’s input. Basically, the code here define the logic of the network graph." }, { "code": null, "e": 6092, "s": 5993, "text": "Firstly, import the dataset and transform date string to Datetime object which Python understands." }, { "code": null, "e": 6132, "s": 6092, "text": "Then, build the network using NetworkX." }, { "code": null, "e": 6157, "s": 6132, "text": "Define node with Plotly." }, { "code": null, "e": 6538, "s": 6157, "text": "Define edge with Plotly. Here, to define the customized edge is not as straight-forward as defining the node. The edges are customized in two ways: the color of the edge represents the time of the transaction, the early the transaction, the lighter the edge color; In addition, the width of the edge represents transaction amount, where wider edges have larger transaction amount." }, { "code": null, "e": 6764, "s": 6538, "text": "Define the invisible middle point on the edge, to allow hover effect on the edge. Since Dash only allows hover effect on data points, I add an invisible middle point on the edge to create an additional data point on the edge." }, { "code": null, "e": 6812, "s": 6764, "text": "Finally, define the layout of the Plotly graph." }, { "code": null, "e": 6872, "s": 6812, "text": "The final transaction network visualization app works like:" } ]
Express.js | app.param() Function - GeeksforGeeks
18 Jun, 2020 The app.param() function is used to add the callback triggers to route parameters. It is commonly used to check for the existence of the data requested related to the route parameter. Syntax: app.param([name], callback) Parameters: name: It is the name of the parameter or an array of them.callback: It is a function that is passed as a parameter. name: It is the name of the parameter or an array of them. callback: It is a function that is passed as a parameter. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.param('id', function (req, res, next, id) { console.log('CALLED ONLY ONCE'); next();}); app.get('/user/:id', function (req, res, next) { console.log('Greetings from geeksforgeeks'); next();}); app.get('/user/:id', function (req, res) { console.log('Once again greetings from geeksforgeeks'); res.end();}); app.listen(PORT, function(err){ if (err) console.log("Error in server setup"); console.log("Server listening on Port", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on Port 3000 Open browser and go to http://localhost:3000/user/42. Now check your console, following will be the output:Server listening on Port 3000 CALLED ONLY ONCE Greetings from geeksforgeeks Once again greetings from geeksforgeeks The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on Port 3000 node index.js Output: Server listening on Port 3000 Open browser and go to http://localhost:3000/user/42. Now check your console, following will be the output:Server listening on Port 3000 CALLED ONLY ONCE Greetings from geeksforgeeks Once again greetings from geeksforgeeks Server listening on Port 3000 CALLED ONLY ONCE Greetings from geeksforgeeks Once again greetings from geeksforgeeks So this is how you can use the express app.param() function to add callback triggers to route parameters. Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to read and write Excel file in Node.js ? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25092, "s": 25064, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25276, "s": 25092, "text": "The app.param() function is used to add the callback triggers to route parameters. It is commonly used to check for the existence of the data requested related to the route parameter." }, { "code": null, "e": 25284, "s": 25276, "text": "Syntax:" }, { "code": null, "e": 25312, "s": 25284, "text": "app.param([name], callback)" }, { "code": null, "e": 25324, "s": 25312, "text": "Parameters:" }, { "code": null, "e": 25440, "s": 25324, "text": "name: It is the name of the parameter or an array of them.callback: It is a function that is passed as a parameter." }, { "code": null, "e": 25499, "s": 25440, "text": "name: It is the name of the parameter or an array of them." }, { "code": null, "e": 25557, "s": 25499, "text": "callback: It is a function that is passed as a parameter." }, { "code": null, "e": 25589, "s": 25557, "text": "Installation of express module:" }, { "code": null, "e": 25984, "s": 25589, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26105, "s": 25984, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 26125, "s": 26105, "text": "npm install express" }, { "code": null, "e": 26253, "s": 26125, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 26273, "s": 26253, "text": "npm version express" }, { "code": null, "e": 26421, "s": 26273, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 26435, "s": 26421, "text": "node index.js" }, { "code": null, "e": 26454, "s": 26435, "text": "Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.param('id', function (req, res, next, id) { console.log('CALLED ONLY ONCE'); next();}); app.get('/user/:id', function (req, res, next) { console.log('Greetings from geeksforgeeks'); next();}); app.get('/user/:id', function (req, res) { console.log('Once again greetings from geeksforgeeks'); res.end();}); app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\"); console.log(\"Server listening on Port\", PORT);});", "e": 26995, "s": 26454, "text": null }, { "code": null, "e": 27021, "s": 26995, "text": "Steps to run the program:" }, { "code": null, "e": 27466, "s": 27021, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on Port 3000\nOpen browser and go to http://localhost:3000/user/42. Now check your console, following will be the output:Server listening on Port 3000\nCALLED ONLY ONCE\nGreetings from geeksforgeeks\nOnce again greetings from geeksforgeeks\n" }, { "code": null, "e": 27509, "s": 27466, "text": "The project structure will look like this:" }, { "code": null, "e": 27601, "s": 27509, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 27621, "s": 27601, "text": "npm install express" }, { "code": null, "e": 27710, "s": 27621, "text": "Run index.js file using below command:node index.jsOutput:Server listening on Port 3000\n" }, { "code": null, "e": 27724, "s": 27710, "text": "node index.js" }, { "code": null, "e": 27732, "s": 27724, "text": "Output:" }, { "code": null, "e": 27763, "s": 27732, "text": "Server listening on Port 3000\n" }, { "code": null, "e": 27987, "s": 27763, "text": "Open browser and go to http://localhost:3000/user/42. Now check your console, following will be the output:Server listening on Port 3000\nCALLED ONLY ONCE\nGreetings from geeksforgeeks\nOnce again greetings from geeksforgeeks\n" }, { "code": null, "e": 28104, "s": 27987, "text": "Server listening on Port 3000\nCALLED ONLY ONCE\nGreetings from geeksforgeeks\nOnce again greetings from geeksforgeeks\n" }, { "code": null, "e": 28210, "s": 28104, "text": "So this is how you can use the express app.param() function to add callback triggers to route parameters." }, { "code": null, "e": 28221, "s": 28210, "text": "Express.js" }, { "code": null, "e": 28229, "s": 28221, "text": "Node.js" }, { "code": null, "e": 28246, "s": 28229, "text": "Web Technologies" }, { "code": null, "e": 28344, "s": 28246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28373, "s": 28344, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 28403, "s": 28373, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28460, "s": 28403, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28514, "s": 28460, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28560, "s": 28514, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 28602, "s": 28560, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28645, "s": 28602, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28695, "s": 28645, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28757, "s": 28695, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
PyCaret: Better Machine Learning with Python | by Dario Radečić | Towards Data Science
Pick up any data science book or online course. I’d bet the only machine learning library covered is Scikit-Learn. It’s a great place to start, don’t get me wrong, but in 2020 we need something a bit more automated and time-saving. That’s where PyCaret comes in. It’s a relatively new library, so there are not too many tutorials available — although the official documentation does an amazing job. Here’s a one-sentence summary: PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment.[1] If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included: This article is aimed towards someone familiar with the concepts of machine learning, and also knows how to use various algorithms in libraries like Scikit-Learn. The ideal reader is aware of the need for automation and doesn’t want to spend days or weeks seeking optimal algorithm and its hyperparameters. This will be a rather short and hands-on article, as the aim is only to showcase what the library is capable of doing. Future articles will focus more on regression/classification/clustering tasks. Okay, let’s get started! The installation process varies based on your operating system. I’m on macOS, so some steps were required before the library could be installed. Once done, you’re ready to start. We’ll begin with two imports: from pycaret.classification import * from pycaret.datasets import get_data The first one is a recommended way to get started with classification tasks — although some of you might not be comfortable with the import * syntax. Avoid it if you with. The second import allows us to use built-in datasets. We’ll use the in-built diabetes dataset, and get_data() function to obtain it. Next, we need to do a bit of setup, and tell PyCaret what’s the target variable: diabetes = get_data(‘diabetes’)exp_clf = setup(diabetes, target=’Class variable’) Executing this code will result in the following: This resulting DataFrame is quite long and reports back a lot of information about your data. We can now proceed with the machine learning portion. This step is very simple. Type the following: compare_models() And here’s the result: Yep, the compare_models() function does all that. It also highlights cells with the highest scores in yellow, so it’s easier to see. Logistic regression seems to do the best accuracy-wise, but the XGBoost algorithm performs the best overall — so that’s the one we’ll use. How? Once again, can’t be any simpler: xgb = create_model(‘xgboost’) On this link, you’ll find all model abbreviations, so you can use something other than XGBoost. Up next, let’s see visually how our model performs. We can use the plot_model() function to visualize model performance: plot_model(xgb) It shows the ROC curves plot by default, but that’s easy to change. Here’s the confusion matrix: plot_model(xgb, ‘confusion_matrix’) And the classification report: plot_model(xgb, ‘class_report’) Neat, right? Here’s the link to all of the visualizations you can make. Let’s proceed with model interpretability. SHAP, or SHapley Additive exPlanations, is a way to explain the outputs of a machine learning model. We can use it to see which features are most important by plotting the SHAP values of every feature for every sample. Once again, PyCaret makes it utterly simple to do: interpret_model(xgb) The plot above sorts features by the sum of SHAP value magnitudes over all samples and uses SHAP values to show the distribution of the impacts each feature has on the model output[2]. Quite a long sentence, so read through it a couple of times. The color represents the feature value — red being high and blue being low. In a nutshell, it states that the higher levels of Plasma glucose concentration a 2 hours in an oral glucose tolerance test (whatever that means), leads to higher (due to red color) chances for diabetes. I plan to cover SHAP in much more depth in some other article, so I won’t go too deep here. Let’s proceed with the model evaluation on the test set. PyCaret split the data into training and test portions (70:30) upon loading, so we don’t have to do it manually. We can now evaluate the model on previously unseen data: predictions = predict_model(xgb) The above code yields the following results: Okay, now when that’s covered, let’s see how to save and load the model. Before saving the model, we need to finalize it: finalize_model(xgb) Guess how simple it is to save the model: save_model(xgb, ‘diabetes_xgboost’) The model is saved in the pickle format. Try to guess the name of the function for loading saved models: model = load_model(‘diabetes_xgboost’) And you’re ready to use it again. We’ve covered a lot of things today, so let’s wrap things up in the next section. More articles like this are coming soon, so stay tuned. Today we’ve briefly covered what PyCaret has to offer. My idea is to turn this into a series, both article-based and video-based, and cover the library in much more depth. When working with libraries like this one, the ones like Scikit-Learn quickly become a part of the past. Not because they’re bad, but these ones are just superior in every single way. I hope you’ve liked it and managed to get something useful out of it. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 403, "s": 171, "text": "Pick up any data science book or online course. I’d bet the only machine learning library covered is Scikit-Learn. It’s a great place to start, don’t get me wrong, but in 2020 we need something a bit more automated and time-saving." }, { "code": null, "e": 601, "s": 403, "text": "That’s where PyCaret comes in. It’s a relatively new library, so there are not too many tutorials available — although the official documentation does an amazing job. Here’s a one-sentence summary:" }, { "code": null, "e": 801, "s": 601, "text": "PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment.[1]" }, { "code": null, "e": 945, "s": 801, "text": "If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included:" }, { "code": null, "e": 1252, "s": 945, "text": "This article is aimed towards someone familiar with the concepts of machine learning, and also knows how to use various algorithms in libraries like Scikit-Learn. The ideal reader is aware of the need for automation and doesn’t want to spend days or weeks seeking optimal algorithm and its hyperparameters." }, { "code": null, "e": 1450, "s": 1252, "text": "This will be a rather short and hands-on article, as the aim is only to showcase what the library is capable of doing. Future articles will focus more on regression/classification/clustering tasks." }, { "code": null, "e": 1475, "s": 1450, "text": "Okay, let’s get started!" }, { "code": null, "e": 1620, "s": 1475, "text": "The installation process varies based on your operating system. I’m on macOS, so some steps were required before the library could be installed." }, { "code": null, "e": 1684, "s": 1620, "text": "Once done, you’re ready to start. We’ll begin with two imports:" }, { "code": null, "e": 1759, "s": 1684, "text": "from pycaret.classification import * from pycaret.datasets import get_data" }, { "code": null, "e": 1985, "s": 1759, "text": "The first one is a recommended way to get started with classification tasks — although some of you might not be comfortable with the import * syntax. Avoid it if you with. The second import allows us to use built-in datasets." }, { "code": null, "e": 2145, "s": 1985, "text": "We’ll use the in-built diabetes dataset, and get_data() function to obtain it. Next, we need to do a bit of setup, and tell PyCaret what’s the target variable:" }, { "code": null, "e": 2227, "s": 2145, "text": "diabetes = get_data(‘diabetes’)exp_clf = setup(diabetes, target=’Class variable’)" }, { "code": null, "e": 2277, "s": 2227, "text": "Executing this code will result in the following:" }, { "code": null, "e": 2425, "s": 2277, "text": "This resulting DataFrame is quite long and reports back a lot of information about your data. We can now proceed with the machine learning portion." }, { "code": null, "e": 2471, "s": 2425, "text": "This step is very simple. Type the following:" }, { "code": null, "e": 2488, "s": 2471, "text": "compare_models()" }, { "code": null, "e": 2511, "s": 2488, "text": "And here’s the result:" }, { "code": null, "e": 2783, "s": 2511, "text": "Yep, the compare_models() function does all that. It also highlights cells with the highest scores in yellow, so it’s easier to see. Logistic regression seems to do the best accuracy-wise, but the XGBoost algorithm performs the best overall — so that’s the one we’ll use." }, { "code": null, "e": 2822, "s": 2783, "text": "How? Once again, can’t be any simpler:" }, { "code": null, "e": 2852, "s": 2822, "text": "xgb = create_model(‘xgboost’)" }, { "code": null, "e": 3000, "s": 2852, "text": "On this link, you’ll find all model abbreviations, so you can use something other than XGBoost. Up next, let’s see visually how our model performs." }, { "code": null, "e": 3069, "s": 3000, "text": "We can use the plot_model() function to visualize model performance:" }, { "code": null, "e": 3085, "s": 3069, "text": "plot_model(xgb)" }, { "code": null, "e": 3182, "s": 3085, "text": "It shows the ROC curves plot by default, but that’s easy to change. Here’s the confusion matrix:" }, { "code": null, "e": 3218, "s": 3182, "text": "plot_model(xgb, ‘confusion_matrix’)" }, { "code": null, "e": 3249, "s": 3218, "text": "And the classification report:" }, { "code": null, "e": 3281, "s": 3249, "text": "plot_model(xgb, ‘class_report’)" }, { "code": null, "e": 3396, "s": 3281, "text": "Neat, right? Here’s the link to all of the visualizations you can make. Let’s proceed with model interpretability." }, { "code": null, "e": 3615, "s": 3396, "text": "SHAP, or SHapley Additive exPlanations, is a way to explain the outputs of a machine learning model. We can use it to see which features are most important by plotting the SHAP values of every feature for every sample." }, { "code": null, "e": 3666, "s": 3615, "text": "Once again, PyCaret makes it utterly simple to do:" }, { "code": null, "e": 3687, "s": 3666, "text": "interpret_model(xgb)" }, { "code": null, "e": 4009, "s": 3687, "text": "The plot above sorts features by the sum of SHAP value magnitudes over all samples and uses SHAP values to show the distribution of the impacts each feature has on the model output[2]. Quite a long sentence, so read through it a couple of times. The color represents the feature value — red being high and blue being low." }, { "code": null, "e": 4213, "s": 4009, "text": "In a nutshell, it states that the higher levels of Plasma glucose concentration a 2 hours in an oral glucose tolerance test (whatever that means), leads to higher (due to red color) chances for diabetes." }, { "code": null, "e": 4362, "s": 4213, "text": "I plan to cover SHAP in much more depth in some other article, so I won’t go too deep here. Let’s proceed with the model evaluation on the test set." }, { "code": null, "e": 4475, "s": 4362, "text": "PyCaret split the data into training and test portions (70:30) upon loading, so we don’t have to do it manually." }, { "code": null, "e": 4532, "s": 4475, "text": "We can now evaluate the model on previously unseen data:" }, { "code": null, "e": 4565, "s": 4532, "text": "predictions = predict_model(xgb)" }, { "code": null, "e": 4610, "s": 4565, "text": "The above code yields the following results:" }, { "code": null, "e": 4683, "s": 4610, "text": "Okay, now when that’s covered, let’s see how to save and load the model." }, { "code": null, "e": 4732, "s": 4683, "text": "Before saving the model, we need to finalize it:" }, { "code": null, "e": 4752, "s": 4732, "text": "finalize_model(xgb)" }, { "code": null, "e": 4794, "s": 4752, "text": "Guess how simple it is to save the model:" }, { "code": null, "e": 4830, "s": 4794, "text": "save_model(xgb, ‘diabetes_xgboost’)" }, { "code": null, "e": 4871, "s": 4830, "text": "The model is saved in the pickle format." }, { "code": null, "e": 4935, "s": 4871, "text": "Try to guess the name of the function for loading saved models:" }, { "code": null, "e": 4974, "s": 4935, "text": "model = load_model(‘diabetes_xgboost’)" }, { "code": null, "e": 5008, "s": 4974, "text": "And you’re ready to use it again." }, { "code": null, "e": 5146, "s": 5008, "text": "We’ve covered a lot of things today, so let’s wrap things up in the next section. More articles like this are coming soon, so stay tuned." }, { "code": null, "e": 5318, "s": 5146, "text": "Today we’ve briefly covered what PyCaret has to offer. My idea is to turn this into a series, both article-based and video-based, and cover the library in much more depth." }, { "code": null, "e": 5502, "s": 5318, "text": "When working with libraries like this one, the ones like Scikit-Learn quickly become a part of the past. Not because they’re bad, but these ones are just superior in every single way." }, { "code": null, "e": 5592, "s": 5502, "text": "I hope you’ve liked it and managed to get something useful out of it. Thanks for reading." } ]
wxPython - Dockable Windows
wxAui is an Advanced User Interface library incorporated in wxWidgets API. Wx.aui.AuiManager the central class in AUI framework. AuiManager manages the panes associated with a particular frame using each panel’s information in wx.aui.AuiPanelInfo object. Let us learn about various properties of PanelInfo object control docking and floating behavior. Putting dockable windows in the top level frame involves the following steps − First, create an AuiManager object. self.mgr = wx.aui.AuiManager(self) Then, a panel with required controls is designed. pnl = wx.Panel(self) pbox = wx.BoxSizer(wx.HORIZONTAL) text1 = wx.TextCtrl(pnl, -1, "Dockable", style = wx.NO_BORDER | wx.TE_MULTILINE) pbox.Add(text1, 1, flag = wx.EXPAND) pnl.SetSizer(pbox) The following parameters of AuiPanelInfo are set. Direction − Top, Bottom, Left, Right, or Center Direction − Top, Bottom, Left, Right, or Center Position − More than one pane can be placed inside a dockable region. Each is given a position number. Position − More than one pane can be placed inside a dockable region. Each is given a position number. Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row. Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row. Layer − Panes can be placed in layers. Layer − Panes can be placed in layers. Using this PanelInfo, the designed panel is added into the manager object. info1 = wx.aui.AuiPaneInfo().Bottom() self.mgr.AddPane(pnl,info1) Rest of the top level window may have other controls as usual. The complete code is as follows − import wx import wx.aui class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title, size = (300,300)) self.mgr = wx.aui.AuiManager(self) pnl = wx.Panel(self) pbox = wx.BoxSizer(wx.HORIZONTAL) text1 = wx.TextCtrl(pnl, -1, "Dockable", style = wx.NO_BORDER | wx.TE_MULTILINE) pbox.Add(text1, 1, flag = wx.EXPAND) pnl.SetSizer(pbox) info1 = wx.aui.AuiPaneInfo().Bottom() self.mgr.AddPane(pnl, info1) panel = wx.Panel(self) text2 = wx.TextCtrl(panel, size = (300,200), style = wx.NO_BORDER | wx.TE_MULTILINE) box = wx.BoxSizer(wx.HORIZONTAL) box.Add(text2, 1, flag = wx.EXPAND) panel.SetSizerAndFit(box) self.mgr.Update() self.Bind(wx.EVT_CLOSE, self.OnClose) self.Centre() self.Show(True) def OnClose(self, event): self.mgr.UnInit() self.Destroy() app = wx.App() Mywin(None,"Dock Demo") app.MainLoop() The above code produces the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2011, "s": 1882, "text": "wxAui is an Advanced User Interface library incorporated in wxWidgets API. Wx.aui.AuiManager the central class in AUI framework." }, { "code": null, "e": 2234, "s": 2011, "text": "AuiManager manages the panes associated with a particular frame using each panel’s information in wx.aui.AuiPanelInfo object. Let us learn about various properties of PanelInfo object control docking and floating behavior." }, { "code": null, "e": 2313, "s": 2234, "text": "Putting dockable windows in the top level frame involves the following steps −" }, { "code": null, "e": 2349, "s": 2313, "text": "First, create an AuiManager object." }, { "code": null, "e": 2385, "s": 2349, "text": "self.mgr = wx.aui.AuiManager(self)\n" }, { "code": null, "e": 2435, "s": 2385, "text": "Then, a panel with required controls is designed." }, { "code": null, "e": 2631, "s": 2435, "text": "pnl = wx.Panel(self) \npbox = wx.BoxSizer(wx.HORIZONTAL) \ntext1 = wx.TextCtrl(pnl, -1, \"Dockable\", style = wx.NO_BORDER | wx.TE_MULTILINE) \npbox.Add(text1, 1, flag = wx.EXPAND) \npnl.SetSizer(pbox)" }, { "code": null, "e": 2681, "s": 2631, "text": "The following parameters of AuiPanelInfo are set." }, { "code": null, "e": 2729, "s": 2681, "text": "Direction − Top, Bottom, Left, Right, or Center" }, { "code": null, "e": 2777, "s": 2729, "text": "Direction − Top, Bottom, Left, Right, or Center" }, { "code": null, "e": 2880, "s": 2777, "text": "Position − More than one pane can be placed inside a dockable region. Each is given a position number." }, { "code": null, "e": 2983, "s": 2880, "text": "Position − More than one pane can be placed inside a dockable region. Each is given a position number." }, { "code": null, "e": 3087, "s": 2983, "text": "Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row." }, { "code": null, "e": 3191, "s": 3087, "text": "Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row." }, { "code": null, "e": 3230, "s": 3191, "text": "Layer − Panes can be placed in layers." }, { "code": null, "e": 3269, "s": 3230, "text": "Layer − Panes can be placed in layers." }, { "code": null, "e": 3344, "s": 3269, "text": "Using this PanelInfo, the designed panel is added into the manager object." }, { "code": null, "e": 3412, "s": 3344, "text": "info1 = wx.aui.AuiPaneInfo().Bottom() \nself.mgr.AddPane(pnl,info1)\n" }, { "code": null, "e": 3475, "s": 3412, "text": "Rest of the top level window may have other controls as usual." }, { "code": null, "e": 3509, "s": 3475, "text": "The complete code is as follows −" }, { "code": null, "e": 4547, "s": 3509, "text": "import wx \nimport wx.aui\n \nclass Mywin(wx.Frame):\n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title, size = (300,300)) \n\t\t\n self.mgr = wx.aui.AuiManager(self)\n\t\t\n pnl = wx.Panel(self) \n pbox = wx.BoxSizer(wx.HORIZONTAL)\n text1 = wx.TextCtrl(pnl, -1, \"Dockable\", style = wx.NO_BORDER | wx.TE_MULTILINE) \n pbox.Add(text1, 1, flag = wx.EXPAND) \n pnl.SetSizer(pbox) \n \n info1 = wx.aui.AuiPaneInfo().Bottom() \n self.mgr.AddPane(pnl, info1) \n panel = wx.Panel(self) \n text2 = wx.TextCtrl(panel, size = (300,200), style = wx.NO_BORDER | wx.TE_MULTILINE) \n box = wx.BoxSizer(wx.HORIZONTAL) \n box.Add(text2, 1, flag = wx.EXPAND) \n \n panel.SetSizerAndFit(box) \n self.mgr.Update() \n\t\t\n self.Bind(wx.EVT_CLOSE, self.OnClose) \n self.Centre() \n self.Show(True) \n\t\t\n def OnClose(self, event): \n self.mgr.UnInit() \n self.Destroy() \n\t\t\napp = wx.App()\nMywin(None,\"Dock Demo\") \napp.MainLoop()" }, { "code": null, "e": 4594, "s": 4547, "text": "The above code produces the following output −" }, { "code": null, "e": 4601, "s": 4594, "text": " Print" }, { "code": null, "e": 4612, "s": 4601, "text": " Add Notes" } ]
TypeScript - Union
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars. Type1|Type2|Type3 var val:string|number val = 12 console.log("numeric value of val "+val) val = "This is a string" console.log("string value of val "+val) In the above example, the variable’s type is union. It means that the variable can contain either a number or a string as its value. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var val; val = 12; console.log("numeric value of val " + val); val = "This is a string"; console.log("string value of val " + val); Its output is as follows − numeric value of val 12 string value of val this is a string function disp(name:string|string[]) { if(typeof name == "string") { console.log(name) } else { var i; for(i = 0;i<name.length;i++) { console.log(name[i]) } } } disp("mark") console.log("Printing names array....") disp(["Mark","Tom","Mary","John"]) The function disp() can accept argument either of the type string or a string array. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 function disp(name) { if (typeof name == "string") { console.log(name); } else { var i; for (i = 0; i < name.length; i++) { console.log(name[i]); } } } disp("mark"); console.log("Printing names array...."); disp(["Mark", "Tom", "Mary", "John"]); The output is as follows − Mark Printing names array.... Mark Tom Mary John Union types can also be applied to arrays, properties and interfaces. The following illustrates the use of union type with an array. var arr:number[]|string[]; var i:number; arr = [1,2,4] console.log("**numeric array**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) } arr = ["Mumbai","Pune","Delhi"] console.log("**string array**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) } The program declares an array. The array can represent either a numeric collection or a string collection. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var arr; var i; arr = [1, 2, 4]; console.log("**numeric array**"); for (i = 0; i < arr.length; i++) { console.log(arr[i]); } arr = ["Mumbai", "Pune", "Delhi"]; console.log("**string array**"); for (i = 0; i < arr.length; i++) { console.log(arr[i]); } Its output is as follows − **numeric array** 1 2 4 **string array** Mumbai Pune Delhi 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2048, "text": "TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars." }, { "code": null, "e": 2404, "s": 2384, "text": "Type1|Type2|Type3 \n" }, { "code": null, "e": 2546, "s": 2404, "text": "var val:string|number \nval = 12 \nconsole.log(\"numeric value of val \"+val) \nval = \"This is a string\" \nconsole.log(\"string value of val \"+val)\n" }, { "code": null, "e": 2679, "s": 2546, "text": "In the above example, the variable’s type is union. It means that the variable can contain either a number or a string as its value." }, { "code": null, "e": 2737, "s": 2679, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 2903, "s": 2737, "text": "//Generated by typescript 1.8.10\nvar val;\nval = 12;\nconsole.log(\"numeric value of val \" + val);\nval = \"This is a string\";\nconsole.log(\"string value of val \" + val);\n" }, { "code": null, "e": 2930, "s": 2903, "text": "Its output is as follows −" }, { "code": null, "e": 2995, "s": 2930, "text": "numeric value of val 12 \nstring value of val this is a string \n" }, { "code": null, "e": 3304, "s": 2995, "text": "function disp(name:string|string[]) { \n if(typeof name == \"string\") { \n console.log(name) \n } else { \n var i; \n \n for(i = 0;i<name.length;i++) { \n console.log(name[i])\n } \n } \n} \ndisp(\"mark\") \nconsole.log(\"Printing names array....\") \ndisp([\"Mark\",\"Tom\",\"Mary\",\"John\"])\n" }, { "code": null, "e": 3389, "s": 3304, "text": "The function disp() can accept argument either of the type string or a string array." }, { "code": null, "e": 3447, "s": 3389, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 3770, "s": 3447, "text": "//Generated by typescript 1.8.10\nfunction disp(name) {\n if (typeof name == \"string\") {\n console.log(name);\n } else {\n var i;\n for (i = 0; i < name.length; i++) {\n console.log(name[i]);\n }\n }\n}\n\ndisp(\"mark\");\nconsole.log(\"Printing names array....\");\ndisp([\"Mark\", \"Tom\", \"Mary\", \"John\"]);\n" }, { "code": null, "e": 3797, "s": 3770, "text": "The output is as follows −" }, { "code": null, "e": 3851, "s": 3797, "text": "Mark \nPrinting names array.... \nMark \nTom\nMary\nJohn \n" }, { "code": null, "e": 3984, "s": 3851, "text": "Union types can also be applied to arrays, properties and interfaces. The following illustrates the use of union type with an array." }, { "code": null, "e": 4265, "s": 3984, "text": "var arr:number[]|string[]; \nvar i:number; \narr = [1,2,4] \nconsole.log(\"**numeric array**\") \n\nfor(i = 0;i<arr.length;i++) { \n console.log(arr[i]) \n} \n\narr = [\"Mumbai\",\"Pune\",\"Delhi\"] \nconsole.log(\"**string array**\") \n\nfor(i = 0;i<arr.length;i++) { \n console.log(arr[i]) \n} \n" }, { "code": null, "e": 4372, "s": 4265, "text": "The program declares an array. The array can represent either a numeric collection or a string collection." }, { "code": null, "e": 4430, "s": 4372, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 4723, "s": 4430, "text": "//Generated by typescript 1.8.10\nvar arr;\nvar i;\narr = [1, 2, 4];\nconsole.log(\"**numeric array**\");\n\nfor (i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n}\narr = [\"Mumbai\", \"Pune\", \"Delhi\"];\nconsole.log(\"**string array**\");\n\nfor (i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n}\n" }, { "code": null, "e": 4750, "s": 4723, "text": "Its output is as follows −" }, { "code": null, "e": 4817, "s": 4750, "text": "**numeric array** \n1 \n2 \n4 \n**string array** \nMumbai \nPune \nDelhi\n" }, { "code": null, "e": 4850, "s": 4817, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 4864, "s": 4850, "text": " Antonio Papa" }, { "code": null, "e": 4897, "s": 4864, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 4911, "s": 4897, "text": " Haider Malik" }, { "code": null, "e": 4946, "s": 4911, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4966, "s": 4946, "text": " Skillbakerystudios" }, { "code": null, "e": 4999, "s": 4966, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 5013, "s": 4999, "text": " Sean Bradley" }, { "code": null, "e": 5048, "s": 5013, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5064, "s": 5048, "text": " TELCOMA Global" }, { "code": null, "e": 5097, "s": 5064, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 5117, "s": 5097, "text": " Christopher Frewin" }, { "code": null, "e": 5124, "s": 5117, "text": " Print" }, { "code": null, "e": 5135, "s": 5124, "text": " Add Notes" } ]
From raw data to web app deployment with ATOM and Streamlit | by Marco vd Boom | Towards Data Science
In this article we will show you how to create a simple web app, capable of helping a data scientist to quickly perform a basic analysis on the performance of predictive models on a provided dataset. The user will be able to upload his own dataset (as a .csv file), and tweak the machine learning pipeline in two ways: selecting which data cleaning steps to apply on the raw dataset, and choosing the models to train and evaluate. And we will do all of this in just 50 lines of code! How? Using the right libraries. We will use ATOM for data processing and model training. ATOM is a library designed for fast exploration of machine learning pipelines. Read this story if you want a gentle introduction to the package. We will use Streamlit to create the web app. Streamlit is a popular library to make beautiful data apps in a matter of minutes. Start making the necessary imports and setting up streamlit’s configuration. We select a wide layout to have space to display two plots next to each other. import pandas as pdimport streamlit as stfrom atom import ATOMClassifier# Expand the web app across the whole screenst.set_page_config(layout="wide") The idea is to be able to modify the machine learning pipeline from a menu located on a sidebar. The menu will consist of checkboxes that will decide which elements (data cleaning steps or models) are added to the pipeline, like a recipe where you can choose your own ingredients. Adding objects to a sidebar in streamlit can be achieved using st.sidebar. The data cleaning steps that we are going to implement are: feature scaling, encoding categorical features and the imputation of missing values. st.sidebar.title("Pipeline")# Data cleaning optionsst.sidebar.subheader("Data cleaning")scale = st.sidebar.checkbox("Scale", False, "scale")encode = st.sidebar.checkbox("Encode", False, "encode")impute = st.sidebar.checkbox("Impute", False, "impute") After that, we add the models that can be used to fit the data. This time we wrap the checkboxes in a dictionary to be able to loop over them later (note that we use ATOM’s model acronyms as keys). # Model optionsst.sidebar.subheader("Models")models = { "gnb": st.sidebar.checkbox("Gaussian Naive Bayes", True, "gnb"), "rf": st.sidebar.checkbox("Random Forest", True, "rf"), "et": st.sidebar.checkbox("Extra-Trees", False, "et"), "xgb": st.sidebar.checkbox("XGBoost", False, "xgb"), "lgb": st.sidebar.checkbox("LightGBM", False, "lgb"),} Note: Make sure to have the XGBoost and LightGBM packages installed to be able to use these models. The sidebar menu is done, time to make the body of the app. The first part is the data ingestion, where we can upload the dataset that we want to use. Use streamlit’s file_uploader function for that. st.header("Data")data = st.file_uploader("Upload data:", type="csv")# If a dataset is uploaded, show a previewif data is not None: data = pd.read_csv(data) st.text("Data preview:") st.dataframe(data.head()) Lastly, write the actual pipeline that will process the data, train the models and evaluate the results. Note that this example only works for binary classification tasks. st.header("Results")if st.sidebar.button("Run"): placeholder = st.empty() # Empty to overwrite write statements placeholder.write("Initializing atom...") # Initialize atom atom = ATOMClassifier(data, verbose=2, random_state=1) if scale: placeholder.write("Scaling the data...") atom.scale() if encode: placeholder.write("Encoding the categorical features...") atom.encode(strategy="LeaveOneOut", max_onehot=10) if impute: placeholder.write("Imputing the missing values...") atom.impute(strat_num="median", strat_cat="most_frequent") placeholder.write("Fitting the models...") to_run = [key for key, value in models.items() if value] atom.run(models=to_run, metric="f1") # Display metric results placeholder.write(atom.evaluate()) # Draw plots col1, col2 = st.beta_columns(2) col1.write(atom.plot_roc(title="ROC curve", display=None)) col2.write(atom.plot_prc(title="PR curve", display=None))else: st.write("No results yet. Click the run button!") This is a rather large chunk of code, so let me explain what happens here. The if statement at the start creates a button in the sidebar, that, if clicked, executes the code block inside the if statement. As long as the button is not clicked, the pipeline does not run. This ensures that the pipeline doesn’t start running after every click on one of the checkboxes in the menu. The code block inside the if statement does the following: Create a placeholder text block to write some progress information while the pipeline is running. Initialize an ATOMClassifier instance that will process the pipeline. With this command, the data is automatically split into a training and test set with a 80%-20% ratio. Run the data cleaning step corresponding to every checked checkbox in the sidebar. Use atom’s run method to train all the selected models on the training set. Output the models’ performance on the test set using the scoring method. Display the Receiver Operating Characteristic curve and the Precision-Recall curve for all the trained models. The display=None argument is necessary to return the created matplotlib figure. And just like that, the web app is done! Let’s give it a try. To run the app, open the terminal and go to the directory where the file is located. Run the command streamlit run <name_web_app>.py. The web app will automatically open in your default browser. Follow the steps described here to deploy it. The data used in the example shown is a variation on the Australian weather dataset from Kaggle. It can be downloaded from here. The goal of this dataset is to predict whether or not it will rain tomorrow, training a binary classifier on target column RainTomorrow. The example’s full code can be found here. We have seen how to use ATOM and Streamlit to quickly create a web app capable of exploring a basic machine learning pipeline. Due to the flexibility and ease-of-use of both libraries, it wouldn’t take much effort to improve the web app adding new models, allowing regression pipelines, showing some extra plots or increasing the complexity of the pipeline. Related stories: https://towardsdatascience.com/atom-a-python-package-for-fast-exploration-of-machine-learning-pipelines-653956a16e7b https://towardsdatascience.com/how-to-test-multiple-machine-learning-pipelines-with-just-a-few-lines-of-python-1a16cb4686d For further information about ATOM, check out the project’s GitHub or Documentation page. For bugs or feature requests, don’t hesitate to open an issue on GitHub or send me an email.
[ { "code": null, "e": 688, "s": 172, "text": "In this article we will show you how to create a simple web app, capable of helping a data scientist to quickly perform a basic analysis on the performance of predictive models on a provided dataset. The user will be able to upload his own dataset (as a .csv file), and tweak the machine learning pipeline in two ways: selecting which data cleaning steps to apply on the raw dataset, and choosing the models to train and evaluate. And we will do all of this in just 50 lines of code! How? Using the right libraries." }, { "code": null, "e": 890, "s": 688, "text": "We will use ATOM for data processing and model training. ATOM is a library designed for fast exploration of machine learning pipelines. Read this story if you want a gentle introduction to the package." }, { "code": null, "e": 1018, "s": 890, "text": "We will use Streamlit to create the web app. Streamlit is a popular library to make beautiful data apps in a matter of minutes." }, { "code": null, "e": 1174, "s": 1018, "text": "Start making the necessary imports and setting up streamlit’s configuration. We select a wide layout to have space to display two plots next to each other." }, { "code": null, "e": 1324, "s": 1174, "text": "import pandas as pdimport streamlit as stfrom atom import ATOMClassifier# Expand the web app across the whole screenst.set_page_config(layout=\"wide\")" }, { "code": null, "e": 1605, "s": 1324, "text": "The idea is to be able to modify the machine learning pipeline from a menu located on a sidebar. The menu will consist of checkboxes that will decide which elements (data cleaning steps or models) are added to the pipeline, like a recipe where you can choose your own ingredients." }, { "code": null, "e": 1825, "s": 1605, "text": "Adding objects to a sidebar in streamlit can be achieved using st.sidebar. The data cleaning steps that we are going to implement are: feature scaling, encoding categorical features and the imputation of missing values." }, { "code": null, "e": 2076, "s": 1825, "text": "st.sidebar.title(\"Pipeline\")# Data cleaning optionsst.sidebar.subheader(\"Data cleaning\")scale = st.sidebar.checkbox(\"Scale\", False, \"scale\")encode = st.sidebar.checkbox(\"Encode\", False, \"encode\")impute = st.sidebar.checkbox(\"Impute\", False, \"impute\")" }, { "code": null, "e": 2274, "s": 2076, "text": "After that, we add the models that can be used to fit the data. This time we wrap the checkboxes in a dictionary to be able to loop over them later (note that we use ATOM’s model acronyms as keys)." }, { "code": null, "e": 2629, "s": 2274, "text": "# Model optionsst.sidebar.subheader(\"Models\")models = { \"gnb\": st.sidebar.checkbox(\"Gaussian Naive Bayes\", True, \"gnb\"), \"rf\": st.sidebar.checkbox(\"Random Forest\", True, \"rf\"), \"et\": st.sidebar.checkbox(\"Extra-Trees\", False, \"et\"), \"xgb\": st.sidebar.checkbox(\"XGBoost\", False, \"xgb\"), \"lgb\": st.sidebar.checkbox(\"LightGBM\", False, \"lgb\"),}" }, { "code": null, "e": 2729, "s": 2629, "text": "Note: Make sure to have the XGBoost and LightGBM packages installed to be able to use these models." }, { "code": null, "e": 2929, "s": 2729, "text": "The sidebar menu is done, time to make the body of the app. The first part is the data ingestion, where we can upload the dataset that we want to use. Use streamlit’s file_uploader function for that." }, { "code": null, "e": 3145, "s": 2929, "text": "st.header(\"Data\")data = st.file_uploader(\"Upload data:\", type=\"csv\")# If a dataset is uploaded, show a previewif data is not None: data = pd.read_csv(data) st.text(\"Data preview:\") st.dataframe(data.head())" }, { "code": null, "e": 3317, "s": 3145, "text": "Lastly, write the actual pipeline that will process the data, train the models and evaluate the results. Note that this example only works for binary classification tasks." }, { "code": null, "e": 4366, "s": 3317, "text": "st.header(\"Results\")if st.sidebar.button(\"Run\"): placeholder = st.empty() # Empty to overwrite write statements placeholder.write(\"Initializing atom...\") # Initialize atom atom = ATOMClassifier(data, verbose=2, random_state=1) if scale: placeholder.write(\"Scaling the data...\") atom.scale() if encode: placeholder.write(\"Encoding the categorical features...\") atom.encode(strategy=\"LeaveOneOut\", max_onehot=10) if impute: placeholder.write(\"Imputing the missing values...\") atom.impute(strat_num=\"median\", strat_cat=\"most_frequent\") placeholder.write(\"Fitting the models...\") to_run = [key for key, value in models.items() if value] atom.run(models=to_run, metric=\"f1\") # Display metric results placeholder.write(atom.evaluate()) # Draw plots col1, col2 = st.beta_columns(2) col1.write(atom.plot_roc(title=\"ROC curve\", display=None)) col2.write(atom.plot_prc(title=\"PR curve\", display=None))else: st.write(\"No results yet. Click the run button!\")" }, { "code": null, "e": 4804, "s": 4366, "text": "This is a rather large chunk of code, so let me explain what happens here. The if statement at the start creates a button in the sidebar, that, if clicked, executes the code block inside the if statement. As long as the button is not clicked, the pipeline does not run. This ensures that the pipeline doesn’t start running after every click on one of the checkboxes in the menu. The code block inside the if statement does the following:" }, { "code": null, "e": 4902, "s": 4804, "text": "Create a placeholder text block to write some progress information while the pipeline is running." }, { "code": null, "e": 5074, "s": 4902, "text": "Initialize an ATOMClassifier instance that will process the pipeline. With this command, the data is automatically split into a training and test set with a 80%-20% ratio." }, { "code": null, "e": 5157, "s": 5074, "text": "Run the data cleaning step corresponding to every checked checkbox in the sidebar." }, { "code": null, "e": 5233, "s": 5157, "text": "Use atom’s run method to train all the selected models on the training set." }, { "code": null, "e": 5306, "s": 5233, "text": "Output the models’ performance on the test set using the scoring method." }, { "code": null, "e": 5497, "s": 5306, "text": "Display the Receiver Operating Characteristic curve and the Precision-Recall curve for all the trained models. The display=None argument is necessary to return the created matplotlib figure." }, { "code": null, "e": 5800, "s": 5497, "text": "And just like that, the web app is done! Let’s give it a try. To run the app, open the terminal and go to the directory where the file is located. Run the command streamlit run <name_web_app>.py. The web app will automatically open in your default browser. Follow the steps described here to deploy it." }, { "code": null, "e": 6109, "s": 5800, "text": "The data used in the example shown is a variation on the Australian weather dataset from Kaggle. It can be downloaded from here. The goal of this dataset is to predict whether or not it will rain tomorrow, training a binary classifier on target column RainTomorrow. The example’s full code can be found here." }, { "code": null, "e": 6467, "s": 6109, "text": "We have seen how to use ATOM and Streamlit to quickly create a web app capable of exploring a basic machine learning pipeline. Due to the flexibility and ease-of-use of both libraries, it wouldn’t take much effort to improve the web app adding new models, allowing regression pipelines, showing some extra plots or increasing the complexity of the pipeline." }, { "code": null, "e": 6484, "s": 6467, "text": "Related stories:" }, { "code": null, "e": 6601, "s": 6484, "text": "https://towardsdatascience.com/atom-a-python-package-for-fast-exploration-of-machine-learning-pipelines-653956a16e7b" }, { "code": null, "e": 6724, "s": 6601, "text": "https://towardsdatascience.com/how-to-test-multiple-machine-learning-pipelines-with-just-a-few-lines-of-python-1a16cb4686d" } ]
How can I do "cd" in Python?
You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to. >>> import os >>> os.chdir('my_folder')
[ { "code": null, "e": 1209, "s": 1062, "text": "You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to." }, { "code": null, "e": 1249, "s": 1209, "text": ">>> import os\n>>> os.chdir('my_folder')" } ]
Convex Hull | Set 2 (Graham Scan)
08 Jul, 2022 Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it. 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. We strongly recommend to see the following post first. How to check if two given line segments intersect?We have discussed Jarvis’s Algorithm for Convex Hull. The worst case time complexity of Jarvis’s Algorithm is O(n^2). Using Graham’s scan algorithm, we can find Convex Hull in O(nLogn) time. Following is Graham’s algorithm Let points[0..n-1] be the input array.1) Find the bottom-most point by comparing y coordinate of all points. If there are two points with the same y value, then the point with smaller x coordinate value is considered. Let the bottom-most point be P0. Put P0 at first position in output hull.2) Consider the remaining n-1 points and sort them by polar angle in counterclockwise order around points[0]. If the polar angle of two points is the same, then put the nearest point first. 3 After sorting, check if two or more points have the same angle. If two more points have the same angle, then remove all same angle points except the point farthest from P0. Let the size of the new array be m.4) If m is less than 3, return (Convex Hull not possible)5) Create an empty stack ‘S’ and push points[0], points[1] and points[2] to S.6) Process remaining m-3 points one by one. Do following for every point ‘points[i]’ 4.1) Keep removing points from stack while orientation of following 3 points is not counterclockwise (or they don’t make a left turn). a) Point next to top in stack b) Point at the top of stack c) points[i] 4.2) Push points[i] to S5) Print contents of SThe above algorithm can be divided into two phases.Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process points be sorting them with respect to the bottom-most point. Once the points are sorted, they form a simple closed path (See the following diagram). What should be the sorting criteria? computation of actual angles would be inefficient since trigonometric functions are not simple to evaluate. The idea is to use the orientation to compare angles without actually computing them (See the compare() function below)Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to traverse the path and remove concave points on this path. How to decide which point to remove and which to keep? Again, orientation helps here. The first two points in sorted array are always part of Convex Hull. For remaining points, we keep track of recent three points, and find the angle formed by them. Let the three points be prev(p), curr(c) and next(n). If orientation of these points (considering them in same order) is not counterclockwise, we discard c, otherwise we keep it. Following diagram shows step by step process of this phase. Following is C++ implementation of the above algorithm. CPP Python3 Javascript // A C++ program to find convex hull of a set of points. Refer// https://www.geeksforgeeks.org/orientation-3-ordered-points/// for explanation of orientation()#include <iostream>#include <stack>#include <stdlib.h>using namespace std; struct Point{ int x, y;}; // A global point needed for sorting points with reference// to the first point Used in compare function of qsort()Point p0; // A utility function to find next to top in a stackPoint nextToTop(stack<Point> &S){ Point p = S.top(); S.pop(); Point res = S.top(); S.push(p); return res;} // A utility function to swap two pointsvoid swap(Point &p1, Point &p2){ Point temp = p1; p1 = p2; p2 = temp;} // A utility function to return square of distance// between p1 and p2int distSq(Point p1, Point p2){ return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // A function used by library function qsort() to sort an array of// points with respect to the first pointint compare(const void *vp1, const void *vp2){ Point *p1 = (Point *)vp1; Point *p2 = (Point *)vp2; // Find orientation int o = orientation(p0, *p1, *p2); if (o == 0) return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1; return (o == 2)? -1: 1;} // Prints convex hull of a set of n points.void convexHull(Point points[], int n){ // Find the bottommost point int ymin = points[0].y, min = 0; for (int i = 1; i < n; i++) { int y = points[i].y; // Pick the bottom-most or choose the left // most point in case of tie if ((y < ymin) || (ymin == y && points[i].x < points[min].x)) ymin = points[i].y, min = i; } // Place the bottom-most point at first position swap(points[0], points[min]); // Sort n-1 points with respect to the first point. // A point p1 comes before p2 in sorted output if p2 // has larger polar angle (in counterclockwise // direction) than p1 p0 = points[0]; qsort(&points[1], n-1, sizeof(Point), compare); // If two or more points make same angle with p0, // Remove all but the one that is farthest from p0 // Remember that, in above sorting, our criteria was // to keep the farthest point at the end when more than // one points have same angle. int m = 1; // Initialize size of modified array for (int i=1; i<n; i++) { // Keep removing i while angle of i and i+1 is same // with respect to p0 while (i < n-1 && orientation(p0, points[i], points[i+1]) == 0) i++; points[m] = points[i]; m++; // Update size of modified array } // If modified array of points has less than 3 points, // convex hull is not possible if (m < 3) return; // Create an empty stack and push first three points // to it. stack<Point> S; S.push(points[0]); S.push(points[1]); S.push(points[2]); // Process remaining n-3 points for (int i = 3; i < m; i++) { // Keep removing top while the angle formed by // points next-to-top, top, and points[i] makes // a non-left turn while (S.size()>1 && orientation(nextToTop(S), S.top(), points[i]) != 2) S.pop(); S.push(points[i]); } // Now stack has the output points, print contents of stack while (!S.empty()) { Point p = S.top(); cout << "(" << p.x << ", " << p.y <<")" << endl; S.pop(); }} // Driver program to test above functionsint main(){ Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int n = sizeof(points)/sizeof(points[0]); convexHull(points, n); return 0;} # A Python3 program to find convex hull of a set of points. Refer# https://www.geeksforgeeks.org/orientation-3-ordered-points/# for explanation of orientation() from functools import cmp_to_key # A class used to store the x and y coordinates of pointsclass Point: def __init__(self, x = None, y = None): self.x = x self.y = y # A global point needed for sorting points with reference# to the first pointp0 = Point(0, 0) # A utility function to find next to top in a stackdef nextToTop(S): return S[-2] # A utility function to return square of distance# between p1 and p2def distSq(p1, p2): return ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)) # To find orientation of ordered triplet (p, q, r).# The function returns following values# 0 --> p, q and r are collinear# 1 --> Clockwise# 2 --> Counterclockwisedef orientation(p, q, r): val = ((q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)) if val == 0: return 0 # collinear elif val > 0: return 1 # clock wise else: return 2 # counterclock wise # A function used by cmp_to_key function to sort an array of# points with respect to the first pointdef compare(p1, p2): # Find orientation o = orientation(p0, p1, p2) if o == 0: if distSq(p0, p2) >= distSq(p0, p1): return -1 else: return 1 else: if o == 2: return -1 else: return 1 # Prints convex hull of a set of n points.def convexHull(points, n): # Find the bottommost point ymin = points[0].y min = 0 for i in range(1, n): y = points[i].y # Pick the bottom-most or choose the left # most point in case of tie if ((y < ymin) or (ymin == y and points[i].x < points[min].x)): ymin = points[i].y min = i # Place the bottom-most point at first position points[0], points[min] = points[min], points[0] # Sort n-1 points with respect to the first point. # A point p1 comes before p2 in sorted output if p2 # has larger polar angle (in counterclockwise # direction) than p1 p0 = points[0] points = sorted(points, key=cmp_to_key(compare)) # If two or more points make same angle with p0, # Remove all but the one that is farthest from p0 # Remember that, in above sorting, our criteria was # to keep the farthest point at the end when more than # one points have same angle. m = 1 # Initialize size of modified array for i in range(1, n): # Keep removing i while angle of i and i+1 is same # with respect to p0 while ((i < n - 1) and (orientation(p0, points[i], points[i + 1]) == 0)): i += 1 points[m] = points[i] m += 1 # Update size of modified array # If modified array of points has less than 3 points, # convex hull is not possible if m < 3: return # Create an empty stack and push first three points # to it. S = [] S.append(points[0]) S.append(points[1]) S.append(points[2]) # Process remaining n-3 points for i in range(3, m): # Keep removing top while the angle formed by # points next-to-top, top, and points[i] makes # a non-left turn while ((len(S) > 1) and (orientation(nextToTop(S), S[-1], points[i]) != 2)): S.pop() S.append(points[i]) # Now stack has the output points, # print contents of stack while S: p = S[-1] print("(" + str(p.x) + ", " + str(p.y) + ")") S.pop() # Driver Codeinput_points = [(0, 3), (1, 1), (2, 2), (4, 4), (0, 0), (1, 2), (3, 1), (3, 3)]points = []for point in input_points: points.append(Point(point[0], point[1]))n = len(points)convexHull(points, n) # This code is contributed by Kevin Joshi // JavaScript program to find convex hull of a set of// points. Refer// https://www.geeksforgeeks.org/orientation-3-ordered-points/// for explanation of orientation() // A class used to store the x and y coordinates of pointsclass Point { constructor(x = null, y = null) { this.x = x; this.y = y; }} // A global point needed for sorting points with reference// to the first pointlet p0 = new Point(0, 0); // A utility function to find next to top in a stackfunction nextToTop(S) { return S[S.length - 2]; } // A utility function to return square of distance// between p1 and p2function distSq(p1, p2){ return ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisefunction orientation(p, q, r){ let val = ((q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)); if (val == 0) return 0; // collinear else if (val > 0) return 1; // clock wise else return 2; // counterclock wise} // A function used by cmp_to_key function to sort an array// of points with respect to the first pointfunction compare(p1, p2){ // Find orientation let o = orientation(p0, p1, p2); if (o == 0) { if (distSq(p0, p2) >= distSq(p0, p1)) return -1; else return 1; } else { if (o == 2) return -1; else return 1; }} // Prints convex hull of a set of n points.function convexHull(points, n){ // Find the bottommost point let ymin = points[0].y; let min = 0; for (var i = 1; i < n; i++) { let y = points[i].y; // Pick the bottom-most or choose the left // most point in case of tie if ((y < ymin) || ((ymin == y) && (points[i].x < points[min].x))) { ymin = points[i].y; min = i; } } // Place the bottom-most point at first position points[0], points[min] = points[min], points[0]; // Sort n-1 points with respect to the first point. // A point p1 comes before p2 in sorted output if p2 // has larger polar angle (in counterclockwise // direction) than p1 let p0 = points[0]; points.sort(compare); // If two or more points make same angle with p0, // Remove all but the one that is farthest from p0 // Remember that, in above sorting, our criteria was // to keep the farthest point at the end when more than // one points have same angle. let m = 1; // Initialize size of modified array for (var i = 1; i < n; i++) { // Keep removing i while angle of i and i+1 is same // with respect to p0 while ((i < n - 1) && (orientation(p0, points[i], points[i + 1]) == 0)) i += 1; points[m] = points[i]; m += 1; // Update size of modified array } // If modified array of points has less than 3 points, // convex hull is not possible if (m < 3) return; // Create an empty stack and push first three points // to it. let S = []; S.push(points[0]); S.push(points[1]); S.push(points[2]); // Process remaining n-3 points for (var i = 3; i < m; i++) { // Keep removing top while the angle formed by // points next-to-top, top, and points[i] makes // a non-left turn while (true) { if (S.length < 2) break; if (orientation(nextToTop(S), S[S.length - 1], points[i]) >= 2) break; S.pop(); } S.push(points[i]); } // Now stack has the output points, // print contents of stack while (S.length > 0) { let p = S[S.length - 1]; console.log("(" + p.x + ", " + p.y + ")"); S.pop(); }} // Driver Codelet points = [ new Point(0, 3), new Point(1, 1), new Point(2, 2), new Point(4, 4), new Point(0, 0), new Point(1, 2), new Point(3, 1), new Point(3, 3)]; let n = points.length;convexHull(points, n); // This code is contributed by phasing17 Output: (0, 3) (4, 4) (3, 1) (0, 0) Time Complexity: Let n be the number of input points. The algorithm takes O(nLogn) time if we use a O(nLogn) sorting algorithm. The first step (finding the bottom-most point) takes O(n) time. The second step (sorting points) takes O(nLogn) time. The third step takes O(n) time. In the third step, every element is pushed and popped at most one time. So the sixth step to process points one by one takes O(n) time, assuming that the stack operations take O(1) time. Overall complexity is O(n) + O(nLogn) + O(n) + O(n) which is O(nLogn). Auxiliary Space: O(n), as explicit stack is used References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://www.dcs.gla.ac.uk/~pat/52233/slides/Hull1x1.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rendon Akanksha_Rai shubhamkumarbarnwal sagar0719kumar kevinjoshi46b _shinchancode sweetyty phasing17 Morgan Stanley Samsung Geometric Mathematical Morgan Stanley Samsung Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 183, "s": 52, "text": "Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it. " }, { "code": null, "e": 192, "s": 183, "text": "Chapters" }, { "code": null, "e": 219, "s": 192, "text": "descriptions off, selected" }, { "code": null, "e": 269, "s": 219, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 292, "s": 269, "text": "captions off, selected" }, { "code": null, "e": 300, "s": 292, "text": "English" }, { "code": null, "e": 324, "s": 300, "text": "This is a modal window." }, { "code": null, "e": 393, "s": 324, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 415, "s": 393, "text": "End of dialog window." }, { "code": null, "e": 2250, "s": 415, "text": "We strongly recommend to see the following post first. How to check if two given line segments intersect?We have discussed Jarvis’s Algorithm for Convex Hull. The worst case time complexity of Jarvis’s Algorithm is O(n^2). Using Graham’s scan algorithm, we can find Convex Hull in O(nLogn) time. Following is Graham’s algorithm Let points[0..n-1] be the input array.1) Find the bottom-most point by comparing y coordinate of all points. If there are two points with the same y value, then the point with smaller x coordinate value is considered. Let the bottom-most point be P0. Put P0 at first position in output hull.2) Consider the remaining n-1 points and sort them by polar angle in counterclockwise order around points[0]. If the polar angle of two points is the same, then put the nearest point first. 3 After sorting, check if two or more points have the same angle. If two more points have the same angle, then remove all same angle points except the point farthest from P0. Let the size of the new array be m.4) If m is less than 3, return (Convex Hull not possible)5) Create an empty stack ‘S’ and push points[0], points[1] and points[2] to S.6) Process remaining m-3 points one by one. Do following for every point ‘points[i]’ 4.1) Keep removing points from stack while orientation of following 3 points is not counterclockwise (or they don’t make a left turn). a) Point next to top in stack b) Point at the top of stack c) points[i] 4.2) Push points[i] to S5) Print contents of SThe above algorithm can be divided into two phases.Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process points be sorting them with respect to the bottom-most point. Once the points are sorted, they form a simple closed path (See the following diagram). " }, { "code": null, "e": 3146, "s": 2250, "text": "What should be the sorting criteria? computation of actual angles would be inefficient since trigonometric functions are not simple to evaluate. The idea is to use the orientation to compare angles without actually computing them (See the compare() function below)Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to traverse the path and remove concave points on this path. How to decide which point to remove and which to keep? Again, orientation helps here. The first two points in sorted array are always part of Convex Hull. For remaining points, we keep track of recent three points, and find the angle formed by them. Let the three points be prev(p), curr(c) and next(n). If orientation of these points (considering them in same order) is not counterclockwise, we discard c, otherwise we keep it. Following diagram shows step by step process of this phase." }, { "code": null, "e": 3202, "s": 3146, "text": "Following is C++ implementation of the above algorithm." }, { "code": null, "e": 3206, "s": 3202, "text": "CPP" }, { "code": null, "e": 3214, "s": 3206, "text": "Python3" }, { "code": null, "e": 3225, "s": 3214, "text": "Javascript" }, { "code": "// A C++ program to find convex hull of a set of points. Refer// https://www.geeksforgeeks.org/orientation-3-ordered-points/// for explanation of orientation()#include <iostream>#include <stack>#include <stdlib.h>using namespace std; struct Point{ int x, y;}; // A global point needed for sorting points with reference// to the first point Used in compare function of qsort()Point p0; // A utility function to find next to top in a stackPoint nextToTop(stack<Point> &S){ Point p = S.top(); S.pop(); Point res = S.top(); S.push(p); return res;} // A utility function to swap two pointsvoid swap(Point &p1, Point &p2){ Point temp = p1; p1 = p2; p2 = temp;} // A utility function to return square of distance// between p1 and p2int distSq(Point p1, Point p2){ return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // A function used by library function qsort() to sort an array of// points with respect to the first pointint compare(const void *vp1, const void *vp2){ Point *p1 = (Point *)vp1; Point *p2 = (Point *)vp2; // Find orientation int o = orientation(p0, *p1, *p2); if (o == 0) return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1; return (o == 2)? -1: 1;} // Prints convex hull of a set of n points.void convexHull(Point points[], int n){ // Find the bottommost point int ymin = points[0].y, min = 0; for (int i = 1; i < n; i++) { int y = points[i].y; // Pick the bottom-most or choose the left // most point in case of tie if ((y < ymin) || (ymin == y && points[i].x < points[min].x)) ymin = points[i].y, min = i; } // Place the bottom-most point at first position swap(points[0], points[min]); // Sort n-1 points with respect to the first point. // A point p1 comes before p2 in sorted output if p2 // has larger polar angle (in counterclockwise // direction) than p1 p0 = points[0]; qsort(&points[1], n-1, sizeof(Point), compare); // If two or more points make same angle with p0, // Remove all but the one that is farthest from p0 // Remember that, in above sorting, our criteria was // to keep the farthest point at the end when more than // one points have same angle. int m = 1; // Initialize size of modified array for (int i=1; i<n; i++) { // Keep removing i while angle of i and i+1 is same // with respect to p0 while (i < n-1 && orientation(p0, points[i], points[i+1]) == 0) i++; points[m] = points[i]; m++; // Update size of modified array } // If modified array of points has less than 3 points, // convex hull is not possible if (m < 3) return; // Create an empty stack and push first three points // to it. stack<Point> S; S.push(points[0]); S.push(points[1]); S.push(points[2]); // Process remaining n-3 points for (int i = 3; i < m; i++) { // Keep removing top while the angle formed by // points next-to-top, top, and points[i] makes // a non-left turn while (S.size()>1 && orientation(nextToTop(S), S.top(), points[i]) != 2) S.pop(); S.push(points[i]); } // Now stack has the output points, print contents of stack while (!S.empty()) { Point p = S.top(); cout << \"(\" << p.x << \", \" << p.y <<\")\" << endl; S.pop(); }} // Driver program to test above functionsint main(){ Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int n = sizeof(points)/sizeof(points[0]); convexHull(points, n); return 0;}", "e": 7222, "s": 3225, "text": null }, { "code": "# A Python3 program to find convex hull of a set of points. Refer# https://www.geeksforgeeks.org/orientation-3-ordered-points/# for explanation of orientation() from functools import cmp_to_key # A class used to store the x and y coordinates of pointsclass Point: def __init__(self, x = None, y = None): self.x = x self.y = y # A global point needed for sorting points with reference# to the first pointp0 = Point(0, 0) # A utility function to find next to top in a stackdef nextToTop(S): return S[-2] # A utility function to return square of distance# between p1 and p2def distSq(p1, p2): return ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)) # To find orientation of ordered triplet (p, q, r).# The function returns following values# 0 --> p, q and r are collinear# 1 --> Clockwise# 2 --> Counterclockwisedef orientation(p, q, r): val = ((q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)) if val == 0: return 0 # collinear elif val > 0: return 1 # clock wise else: return 2 # counterclock wise # A function used by cmp_to_key function to sort an array of# points with respect to the first pointdef compare(p1, p2): # Find orientation o = orientation(p0, p1, p2) if o == 0: if distSq(p0, p2) >= distSq(p0, p1): return -1 else: return 1 else: if o == 2: return -1 else: return 1 # Prints convex hull of a set of n points.def convexHull(points, n): # Find the bottommost point ymin = points[0].y min = 0 for i in range(1, n): y = points[i].y # Pick the bottom-most or choose the left # most point in case of tie if ((y < ymin) or (ymin == y and points[i].x < points[min].x)): ymin = points[i].y min = i # Place the bottom-most point at first position points[0], points[min] = points[min], points[0] # Sort n-1 points with respect to the first point. # A point p1 comes before p2 in sorted output if p2 # has larger polar angle (in counterclockwise # direction) than p1 p0 = points[0] points = sorted(points, key=cmp_to_key(compare)) # If two or more points make same angle with p0, # Remove all but the one that is farthest from p0 # Remember that, in above sorting, our criteria was # to keep the farthest point at the end when more than # one points have same angle. m = 1 # Initialize size of modified array for i in range(1, n): # Keep removing i while angle of i and i+1 is same # with respect to p0 while ((i < n - 1) and (orientation(p0, points[i], points[i + 1]) == 0)): i += 1 points[m] = points[i] m += 1 # Update size of modified array # If modified array of points has less than 3 points, # convex hull is not possible if m < 3: return # Create an empty stack and push first three points # to it. S = [] S.append(points[0]) S.append(points[1]) S.append(points[2]) # Process remaining n-3 points for i in range(3, m): # Keep removing top while the angle formed by # points next-to-top, top, and points[i] makes # a non-left turn while ((len(S) > 1) and (orientation(nextToTop(S), S[-1], points[i]) != 2)): S.pop() S.append(points[i]) # Now stack has the output points, # print contents of stack while S: p = S[-1] print(\"(\" + str(p.x) + \", \" + str(p.y) + \")\") S.pop() # Driver Codeinput_points = [(0, 3), (1, 1), (2, 2), (4, 4), (0, 0), (1, 2), (3, 1), (3, 3)]points = []for point in input_points: points.append(Point(point[0], point[1]))n = len(points)convexHull(points, n) # This code is contributed by Kevin Joshi", "e": 11077, "s": 7222, "text": null }, { "code": "// JavaScript program to find convex hull of a set of// points. Refer// https://www.geeksforgeeks.org/orientation-3-ordered-points/// for explanation of orientation() // A class used to store the x and y coordinates of pointsclass Point { constructor(x = null, y = null) { this.x = x; this.y = y; }} // A global point needed for sorting points with reference// to the first pointlet p0 = new Point(0, 0); // A utility function to find next to top in a stackfunction nextToTop(S) { return S[S.length - 2]; } // A utility function to return square of distance// between p1 and p2function distSq(p1, p2){ return ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisefunction orientation(p, q, r){ let val = ((q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)); if (val == 0) return 0; // collinear else if (val > 0) return 1; // clock wise else return 2; // counterclock wise} // A function used by cmp_to_key function to sort an array// of points with respect to the first pointfunction compare(p1, p2){ // Find orientation let o = orientation(p0, p1, p2); if (o == 0) { if (distSq(p0, p2) >= distSq(p0, p1)) return -1; else return 1; } else { if (o == 2) return -1; else return 1; }} // Prints convex hull of a set of n points.function convexHull(points, n){ // Find the bottommost point let ymin = points[0].y; let min = 0; for (var i = 1; i < n; i++) { let y = points[i].y; // Pick the bottom-most or choose the left // most point in case of tie if ((y < ymin) || ((ymin == y) && (points[i].x < points[min].x))) { ymin = points[i].y; min = i; } } // Place the bottom-most point at first position points[0], points[min] = points[min], points[0]; // Sort n-1 points with respect to the first point. // A point p1 comes before p2 in sorted output if p2 // has larger polar angle (in counterclockwise // direction) than p1 let p0 = points[0]; points.sort(compare); // If two or more points make same angle with p0, // Remove all but the one that is farthest from p0 // Remember that, in above sorting, our criteria was // to keep the farthest point at the end when more than // one points have same angle. let m = 1; // Initialize size of modified array for (var i = 1; i < n; i++) { // Keep removing i while angle of i and i+1 is same // with respect to p0 while ((i < n - 1) && (orientation(p0, points[i], points[i + 1]) == 0)) i += 1; points[m] = points[i]; m += 1; // Update size of modified array } // If modified array of points has less than 3 points, // convex hull is not possible if (m < 3) return; // Create an empty stack and push first three points // to it. let S = []; S.push(points[0]); S.push(points[1]); S.push(points[2]); // Process remaining n-3 points for (var i = 3; i < m; i++) { // Keep removing top while the angle formed by // points next-to-top, top, and points[i] makes // a non-left turn while (true) { if (S.length < 2) break; if (orientation(nextToTop(S), S[S.length - 1], points[i]) >= 2) break; S.pop(); } S.push(points[i]); } // Now stack has the output points, // print contents of stack while (S.length > 0) { let p = S[S.length - 1]; console.log(\"(\" + p.x + \", \" + p.y + \")\"); S.pop(); }} // Driver Codelet points = [ new Point(0, 3), new Point(1, 1), new Point(2, 2), new Point(4, 4), new Point(0, 0), new Point(1, 2), new Point(3, 1), new Point(3, 3)]; let n = points.length;convexHull(points, n); // This code is contributed by phasing17", "e": 15284, "s": 11077, "text": null }, { "code": null, "e": 15293, "s": 15284, "text": "Output: " }, { "code": null, "e": 15322, "s": 15293, "text": "(0, 3)\n(4, 4)\n(3, 1)\n(0, 0) " }, { "code": null, "e": 15858, "s": 15322, "text": "Time Complexity: Let n be the number of input points. The algorithm takes O(nLogn) time if we use a O(nLogn) sorting algorithm. The first step (finding the bottom-most point) takes O(n) time. The second step (sorting points) takes O(nLogn) time. The third step takes O(n) time. In the third step, every element is pushed and popped at most one time. So the sixth step to process points one by one takes O(n) time, assuming that the stack operations take O(1) time. Overall complexity is O(n) + O(nLogn) + O(n) + O(n) which is O(nLogn)." }, { "code": null, "e": 15907, "s": 15858, "text": "Auxiliary Space: O(n), as explicit stack is used" }, { "code": null, "e": 16215, "s": 15907, "text": "References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://www.dcs.gla.ac.uk/~pat/52233/slides/Hull1x1.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 16383, "s": 16215, "text": "This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 16390, "s": 16383, "text": "rendon" }, { "code": null, "e": 16403, "s": 16390, "text": "Akanksha_Rai" }, { "code": null, "e": 16423, "s": 16403, "text": "shubhamkumarbarnwal" }, { "code": null, "e": 16438, "s": 16423, "text": "sagar0719kumar" }, { "code": null, "e": 16452, "s": 16438, "text": "kevinjoshi46b" }, { "code": null, "e": 16466, "s": 16452, "text": "_shinchancode" }, { "code": null, "e": 16475, "s": 16466, "text": "sweetyty" }, { "code": null, "e": 16485, "s": 16475, "text": "phasing17" }, { "code": null, "e": 16500, "s": 16485, "text": "Morgan Stanley" }, { "code": null, "e": 16508, "s": 16500, "text": "Samsung" }, { "code": null, "e": 16518, "s": 16508, "text": "Geometric" }, { "code": null, "e": 16531, "s": 16518, "text": "Mathematical" }, { "code": null, "e": 16546, "s": 16531, "text": "Morgan Stanley" }, { "code": null, "e": 16554, "s": 16546, "text": "Samsung" }, { "code": null, "e": 16567, "s": 16554, "text": "Mathematical" }, { "code": null, "e": 16577, "s": 16567, "text": "Geometric" } ]
Java.lang.ThreadLocal Class in Java
26 May, 2022 This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing immutable classes. Since the Object is no more shared there is no requirement for Synchronization which can improve the scalability and performance of the application. ThreadLocal provides thread restriction which is an extension of a local variable. ThreadLocal is visible only in a single thread. No two threads can see each other’s thread-local variable. These variables are generally private static fields in classes and maintain their state inside the thread. Note: ThreadLocal class extends Object class Constructor: ThreadLocal(): This creates a thread-local variable. Example 1: Java // Java Program to Illustrate ThreadLocal Class// Via get() and set() Method // Class// ThreadLocalDemoclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of ThreadLocal class ThreadLocal<Number> gfg_local = new ThreadLocal<Number>(); ThreadLocal<String> gfg = new ThreadLocal<String>(); // Now setting custom value gfg_local.set(100); // Returns the current thread's value System.out.println("value = " + gfg_local.get()); // Setting the value gfg_local.set(90); // Returns the current thread's value of System.out.println("value = " + gfg_local.get()); // Setting the value gfg_local.set(88.45); // Returns the current thread's value of System.out.println("value = " + gfg_local.get()); // Setting the value gfg.set("GeeksforGeeks"); // Returning the current thread's value of System.out.println("value = " + gfg.get()); }} value = 100 value = 90 value = 88.45 value = GeeksforGeeks Example 2: Java // Java Program to Illustrate ThreadLocal Class// Via Illustrating remove() Method // Class// ThreadLocalDemopublic class GFG { // Main driver method public static void main(String[] args) { // Creating objects of ThreadLocal class ThreadLocal<Number> gfg_local = new ThreadLocal<Number>(); ThreadLocal<String> gfg = new ThreadLocal<String>(); // Setting the value gfg_local.set(100); // Returning the current thread's value System.out.println("value = " + gfg_local.get()); // Setting the value gfg_local.set(90); // Returns the current thread's value of System.out.println("value = " + gfg_local.get()); // Setting the value gfg_local.set(88.45); // Returning the current thread's value of System.out.println("value = " + gfg_local.get()); // Setting the value gfg.set("GeeksforGeeks"); // Returning the current thread's value of System.out.println("value = " + gfg.get()); // Removing value using remove() method gfg.remove(); // Returning the current thread's value of System.out.println("value = " + gfg.get()); // Removing vale gfg_local.remove(); // Returns the current thread's value of System.out.println("value = " + gfg_local.get()); }} value = 100 value = 90 value = 88.45 value = GeeksforGeeks value = null value = null Example 3: Java // Java Program to Illustrate ThreadLocal Class// Via initialValue() Method // Importing required classesimport java.lang.*; // Class 1// Helper class extending Thread classclass NewThread extends Thread { private static ThreadLocal gfg = new ThreadLocal() { protected Object initialValue() { return new Integer(question--); } }; private static int question = 15; NewThread(String name) { // super keyword refers to parent class instance super(name); start(); } // Method // run() method for Thread public void run() { for (int i = 0; i < 2; i++) System.out.println(getName() + " " + gfg.get()); }} // Class 2// Main class// ThreadLocalDemopublic class GFG { // Main driver method public static void main(String[] args) { // Creating threads inside main() method NewThread t1 = new NewThread("quiz1"); NewThread t2 = new NewThread("quiz2"); }} Output: This article is contributed by Abhishek Verma. 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. solankimayank rkbhola5 varshagumber28 Java-Classes Java-lang package Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Singleton Class in Java Initializing a List in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 791, "s": 28, "text": "This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing immutable classes. Since the Object is no more shared there is no requirement for Synchronization which can improve the scalability and performance of the application. ThreadLocal provides thread restriction which is an extension of a local variable. ThreadLocal is visible only in a single thread. No two threads can see each other’s thread-local variable. These variables are generally private static fields in classes and maintain their state inside the thread." }, { "code": null, "e": 836, "s": 791, "text": "Note: ThreadLocal class extends Object class" }, { "code": null, "e": 902, "s": 836, "text": "Constructor: ThreadLocal(): This creates a thread-local variable." }, { "code": null, "e": 913, "s": 902, "text": "Example 1:" }, { "code": null, "e": 918, "s": 913, "text": "Java" }, { "code": "// Java Program to Illustrate ThreadLocal Class// Via get() and set() Method // Class// ThreadLocalDemoclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of ThreadLocal class ThreadLocal<Number> gfg_local = new ThreadLocal<Number>(); ThreadLocal<String> gfg = new ThreadLocal<String>(); // Now setting custom value gfg_local.set(100); // Returns the current thread's value System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg_local.set(90); // Returns the current thread's value of System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg_local.set(88.45); // Returns the current thread's value of System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg.set(\"GeeksforGeeks\"); // Returning the current thread's value of System.out.println(\"value = \" + gfg.get()); }}", "e": 1954, "s": 918, "text": null }, { "code": null, "e": 2013, "s": 1954, "text": "value = 100\nvalue = 90\nvalue = 88.45\nvalue = GeeksforGeeks" }, { "code": null, "e": 2024, "s": 2013, "text": "Example 2:" }, { "code": null, "e": 2029, "s": 2024, "text": "Java" }, { "code": "// Java Program to Illustrate ThreadLocal Class// Via Illustrating remove() Method // Class// ThreadLocalDemopublic class GFG { // Main driver method public static void main(String[] args) { // Creating objects of ThreadLocal class ThreadLocal<Number> gfg_local = new ThreadLocal<Number>(); ThreadLocal<String> gfg = new ThreadLocal<String>(); // Setting the value gfg_local.set(100); // Returning the current thread's value System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg_local.set(90); // Returns the current thread's value of System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg_local.set(88.45); // Returning the current thread's value of System.out.println(\"value = \" + gfg_local.get()); // Setting the value gfg.set(\"GeeksforGeeks\"); // Returning the current thread's value of System.out.println(\"value = \" + gfg.get()); // Removing value using remove() method gfg.remove(); // Returning the current thread's value of System.out.println(\"value = \" + gfg.get()); // Removing vale gfg_local.remove(); // Returns the current thread's value of System.out.println(\"value = \" + gfg_local.get()); }}", "e": 3402, "s": 2029, "text": null }, { "code": null, "e": 3487, "s": 3402, "text": "value = 100\nvalue = 90\nvalue = 88.45\nvalue = GeeksforGeeks\nvalue = null\nvalue = null" }, { "code": null, "e": 3498, "s": 3487, "text": "Example 3:" }, { "code": null, "e": 3503, "s": 3498, "text": "Java" }, { "code": "// Java Program to Illustrate ThreadLocal Class// Via initialValue() Method // Importing required classesimport java.lang.*; // Class 1// Helper class extending Thread classclass NewThread extends Thread { private static ThreadLocal gfg = new ThreadLocal() { protected Object initialValue() { return new Integer(question--); } }; private static int question = 15; NewThread(String name) { // super keyword refers to parent class instance super(name); start(); } // Method // run() method for Thread public void run() { for (int i = 0; i < 2; i++) System.out.println(getName() + \" \" + gfg.get()); }} // Class 2// Main class// ThreadLocalDemopublic class GFG { // Main driver method public static void main(String[] args) { // Creating threads inside main() method NewThread t1 = new NewThread(\"quiz1\"); NewThread t2 = new NewThread(\"quiz2\"); }}", "e": 4490, "s": 3503, "text": null }, { "code": null, "e": 4498, "s": 4490, "text": "Output:" }, { "code": null, "e": 4923, "s": 4500, "text": "This article is contributed by Abhishek Verma. 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": 4937, "s": 4923, "text": "solankimayank" }, { "code": null, "e": 4946, "s": 4937, "text": "rkbhola5" }, { "code": null, "e": 4961, "s": 4946, "text": "varshagumber28" }, { "code": null, "e": 4974, "s": 4961, "text": "Java-Classes" }, { "code": null, "e": 4992, "s": 4974, "text": "Java-lang package" }, { "code": null, "e": 5012, "s": 4992, "text": "Java-Multithreading" }, { "code": null, "e": 5017, "s": 5012, "text": "Java" }, { "code": null, "e": 5022, "s": 5017, "text": "Java" }, { "code": null, "e": 5120, "s": 5022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5171, "s": 5120, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5202, "s": 5171, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5221, "s": 5202, "text": "Interfaces in Java" }, { "code": null, "e": 5239, "s": 5221, "text": "ArrayList in Java" }, { "code": null, "e": 5259, "s": 5239, "text": "Collections in Java" }, { "code": null, "e": 5291, "s": 5259, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5306, "s": 5291, "text": "Stream In Java" }, { "code": null, "e": 5330, "s": 5306, "text": "Singleton Class in Java" }, { "code": null, "e": 5358, "s": 5330, "text": "Initializing a List in Java" } ]
Variables and Keywords in C
16 Jun, 2022 A variable in simple terms is a storage place that has some memory allocated to it. Basically, a variable is used to store some form of data. Different types of variables require different amounts of memory, different type of memory locations, and some specific set of operations that can be applied to them. Variable Declaration: A typical variable declaration is of the form: type variable_name; or for multiple variables: type variable1_name, variable2_name, variable3_name; A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’ character. However, the name must not start with a number.Below is an example of variables in C language, C #include <stdio.h> int main(){ int b = 17, c = 18; char a1 = 'J'; printf("Character value : %c\n", a1); printf("Integer value : %d\t%d\n", b, c); return 0;} Character value : J Integer value : 17 18 Difference b/w variable declaration and definition: Variable declaration refers to the part where a variable is first declared or introduced before its first use. Declaration of variable type is also done in the part. A variable definition is a part where the variable is assigned a memory location and a value. Most of the time, variable declaration and definition are done together. Below is the C program for better clarification: C #include <stdio.h>int main(){ // declaration and definition of variable 'a123' char a123 = 'a'; // This is also both declaration and definition as 'b' is allocated // memory and assigned some garbage value. float b; // multiple declarations and definitions int _c, _d45, e; // Let us print a variable printf("%c \n", a123); return 0;} a Is it possible to have a separate declaration and definition? It is possible in the case of extern variables and functions? See question 1 of this for more details. A variable can have alphabets, digits, and underscore.A variable name can start with the alphabet, and underscore only. It can’t start with a digit.No whitespace is allowed within the variable name.A variable name must not be any reserved word or keyword, e.g. int, goto, etc. A variable can have alphabets, digits, and underscore. A variable name can start with the alphabet, and underscore only. It can’t start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc. Example: _srujan , srujan_poojari , srujan812 , srujan_812 We can’t declare a variable in the form: srujan poojari (it contains wide space in between srujan and poojari )13srujan (it is starting with a number so we cant declare it as a variable )void, char, int (we cant declare them as variables because they have already assigned some functions in the C programming library ) srujan poojari (it contains wide space in between srujan and poojari ) 13srujan (it is starting with a number so we cant declare it as a variable ) void, char, int (we cant declare them as variables because they have already assigned some functions in the C programming library ) 1. Local Variable: A variable that is declared and used inside the function or block is called a local variable. It is scope is limited to function or block. It cannot be used outside the block. Local variables need to be initialized before use. Example: C #include <stdio.h>void function() { int x = 10; // local variable} int main(){ function();} In the above code, x can be used only in the scope of function() . Using it in the main function will give an error. 2. Global Variable: A variable that is declared outside the function or block is called a global variable. It is declared at the start of the program. It is available for all functions. Example: C #include <stdio.h>int x = 20;//global variablevoid function1(){ printf("%d\n" , x);}void function2(){ printf("%d\n" , x);}int main() { function1(); function2(); return 0;} 20 20 In the above code, both functions can use the global variable x as we already have global variables accessible by all the functions. 3. Static Variable: A variable that retains its value between multiple function calls is known as a static variable. It is declared with the static keyword. Example: C #include <stdio.h>void function(){ int x = 20;//local variable static int y = 30;//static variable x = x + 10; y = y + 10; printf("\n%d,%d",x,y); } int main() { function(); function(); function(); return 0;} 30,40 30,50 30,60 In the above example, the local variable will always print the same value whenever the function will be called whereas the static variable will print the incremented value in each function call. 4. Automatic Variable: All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using the auto keyword. Automatic variables are similar to local variables. Example: C #include <stdio.h>void function(){ int x=10;//local variable (also automatic) auto int y=20;//automatic variable}int main() { function(); return 0;} In the above example, both x and y are automatic variables. The only difference is that variable y is explicitly declared with auto keyword. 5. External Variable: External variables can be shared between multiple C files. We can declare an external variable using extern keyword. Example: myfile.h extern int x=10;//external variable (also global) program1.c #include "myfile.h" #include <stdio.h> void printValue(){ printf("Global variable: %d", global_variable); } In the above example, x is an external variable that is used in multiple files. Keywords : These are reserved words whose meaning is already known to the compiler. There are 32 keywords available in c: auto double int struct break long else switch case return enum typedef char register extern union const short float unsigned continue signed for void default sizeof goto volatile do static if while Most of these keywords have already been discussed in the various sub-sections of the C language, like Data Types, Storage Classes, Control Statements, Functions, etc. Let us discuss some of the other keywords which allow us to use the basic functionality of C: const: const can be used to declare constant variables. Constant variables are variables that, when initialized, can’t change their value. Or in other words, the value assigned to them cannot be modified further down in the program. Syntax: const data_type var_name = var_value; Note: Constant variables must be initialized during their declaration. const keyword is also used with pointers. Please refer the const qualifier in C for understanding the same. extern: extern simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. Syntax: extern data_type var_name = var_value; static: static keyword is used to declare static variables, which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere within that file as their scope is local to the file. By default, they are assigned the value 0 by the compiler. Syntax: static data_type var_name = var_value; void: void is a special data type. But what makes it so special? void, as it literally means, is an empty data type. It means it has nothing or it holds no value. For example, when it is used as the return data type for a function it simply represents that the function returns no value. Similarly, when it’s added to a function heading, it represents that the function takes no arguments. Note: void also has a significant use with pointers. Please refer to the void pointer in C for understanding the same. typedef: typedef is used to give a new name to an already existing or even a custom data type (like a structure). It comes in very handy at times, for example in a case when the name of the structure defined by you is very long or you just need a short-hand notation of a pre-existing data type. Let’s implement the keywords which we have discussed above. Take a look at the following code which is a working example to demonstrate these keywords: Example C #include <stdio.h> // declaring and initializing an extern variableextern int x = 9; // declaring and initializing a global variable// simply int z; would have initialized z with// the default value of a global variable which is 0int z = 10; // using typedef to give a short name to long long int// very convenient to use now due to the short nametypedef long long int LL; // function which prints square of a no. and which has void// as its return data typevoid calSquare(int arg){ printf("The square of %d is %d\n", arg, arg * arg);} // Here void means function main takes no parametersint main(void){ // declaring a constant variable, its value cannot be // modified const int a = 32; // declaring a char variable char b = 'G'; // telling the compiler that the variable z is an extern // variable and has been defined elsewhere (above the // main function) extern int z; LL c = 1000000; printf("Hello World!\n"); // printing the above variables printf("This is the value of the constant variable " "'a': %d\n", a); printf("'b' is a char variable. Its value is %c\n", b); printf("'c' is a long long int variable. Its value is " "%lld\n", c); printf("These are the values of the extern variables " "'x' and 'z'" " respectively: %d and %d\n", x, z); // value of extern variable x modified x = 2; // value of extern variable z modified z = 5; // printing the modified values of extern variables 'x' // and 'z' printf("These are the modified values of the extern " "variables" " 'x' and 'z' respectively: %d and %d\n", x, z); // using a static variable printf("The value of static variable 'y' is NOT " "initialized to 5 after the " "first iteration! See for yourself :)\n"); while (x > 0) { static int y = 5; y++; // printing value at each iteration printf("The value of y is %d\n", y); x--; } // print square of 5 calSquare(5); printf("Bye! See you soon. :)\n"); return 0;} Output: Hello World This is the value of the constant variable 'a': 32 'b' is a char variable. Its value is G 'c' is a long long int variable. Its value is 1000000 These are the values of the extern variables 'x' and 'z' respectively: 9 and 10 These are the modified values of the extern variables 'x' and 'z' respectively: 2 and 5 The value of static variable 'y' is NOT initialized to 5 after the first iteration! See for yourself :) The value of y is 6 The value of y is 7 The square of 5 is 25 Bye! See you soon. :) This article is contributed by Ayush Jaggi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. InathiSirayi Srinivas Nekkanti alankritiyadav divyanshtiwari shubhankarsharma22 srujanpoojari08 suruchikumarimfp4 C Basics C-Variable Declaration and Scope C Language School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 362, "s": 52, "text": "A variable in simple terms is a storage place that has some memory allocated to it. Basically, a variable is used to store some form of data. Different types of variables require different amounts of memory, different type of memory locations, and some specific set of operations that can be applied to them. " }, { "code": null, "e": 432, "s": 362, "text": "Variable Declaration: A typical variable declaration is of the form: " }, { "code": null, "e": 540, "s": 432, "text": " type variable_name;\n or for multiple variables:\n type variable1_name, variable2_name, variable3_name;" }, { "code": null, "e": 748, "s": 540, "text": "A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’ character. However, the name must not start with a number.Below is an example of variables in C language," }, { "code": null, "e": 750, "s": 748, "text": "C" }, { "code": "#include <stdio.h> int main(){ int b = 17, c = 18; char a1 = 'J'; printf(\"Character value : %c\\n\", a1); printf(\"Integer value : %d\\t%d\\n\", b, c); return 0;}", "e": 922, "s": 750, "text": null }, { "code": null, "e": 968, "s": 922, "text": "Character value : J\nInteger value : 17 18\n" }, { "code": null, "e": 1353, "s": 968, "text": "Difference b/w variable declaration and definition: Variable declaration refers to the part where a variable is first declared or introduced before its first use. Declaration of variable type is also done in the part. A variable definition is a part where the variable is assigned a memory location and a value. Most of the time, variable declaration and definition are done together." }, { "code": null, "e": 1404, "s": 1353, "text": "Below is the C program for better clarification: " }, { "code": null, "e": 1406, "s": 1404, "text": "C" }, { "code": "#include <stdio.h>int main(){ // declaration and definition of variable 'a123' char a123 = 'a'; // This is also both declaration and definition as 'b' is allocated // memory and assigned some garbage value. float b; // multiple declarations and definitions int _c, _d45, e; // Let us print a variable printf(\"%c \\n\", a123); return 0;}", "e": 1778, "s": 1406, "text": null }, { "code": null, "e": 1782, "s": 1778, "text": "a \n" }, { "code": null, "e": 1948, "s": 1782, "text": "Is it possible to have a separate declaration and definition? It is possible in the case of extern variables and functions? See question 1 of this for more details. " }, { "code": null, "e": 2225, "s": 1948, "text": "A variable can have alphabets, digits, and underscore.A variable name can start with the alphabet, and underscore only. It can’t start with a digit.No whitespace is allowed within the variable name.A variable name must not be any reserved word or keyword, e.g. int, goto, etc." }, { "code": null, "e": 2280, "s": 2225, "text": "A variable can have alphabets, digits, and underscore." }, { "code": null, "e": 2375, "s": 2280, "text": "A variable name can start with the alphabet, and underscore only. It can’t start with a digit." }, { "code": null, "e": 2426, "s": 2375, "text": "No whitespace is allowed within the variable name." }, { "code": null, "e": 2505, "s": 2426, "text": "A variable name must not be any reserved word or keyword, e.g. int, goto, etc." }, { "code": null, "e": 2564, "s": 2505, "text": "Example: _srujan , srujan_poojari , srujan812 , srujan_812" }, { "code": null, "e": 2611, "s": 2564, "text": " We can’t declare a variable in the form:" }, { "code": null, "e": 2893, "s": 2611, "text": "srujan poojari (it contains wide space in between srujan and poojari )13srujan (it is starting with a number so we cant declare it as a variable )void, char, int (we cant declare them as variables because they have already assigned some functions in the C programming library )" }, { "code": null, "e": 2966, "s": 2893, "text": "srujan poojari (it contains wide space in between srujan and poojari )" }, { "code": null, "e": 3044, "s": 2966, "text": "13srujan (it is starting with a number so we cant declare it as a variable )" }, { "code": null, "e": 3177, "s": 3044, "text": "void, char, int (we cant declare them as variables because they have already assigned some functions in the C programming library )" }, { "code": null, "e": 3423, "s": 3177, "text": "1. Local Variable: A variable that is declared and used inside the function or block is called a local variable. It is scope is limited to function or block. It cannot be used outside the block. Local variables need to be initialized before use." }, { "code": null, "e": 3432, "s": 3423, "text": "Example:" }, { "code": null, "e": 3434, "s": 3432, "text": "C" }, { "code": "#include <stdio.h>void function() { int x = 10; // local variable} int main(){ function();}", "e": 3528, "s": 3434, "text": null }, { "code": null, "e": 3647, "s": 3530, "text": "In the above code, x can be used only in the scope of function() . Using it in the main function will give an error." }, { "code": null, "e": 3834, "s": 3647, "text": "2. Global Variable: A variable that is declared outside the function or block is called a global variable. It is declared at the start of the program. It is available for all functions. " }, { "code": null, "e": 3843, "s": 3834, "text": "Example:" }, { "code": null, "e": 3845, "s": 3843, "text": "C" }, { "code": "#include <stdio.h>int x = 20;//global variablevoid function1(){ printf(\"%d\\n\" , x);}void function2(){ printf(\"%d\\n\" , x);}int main() { function1(); function2(); return 0;}", "e": 4025, "s": 3845, "text": null }, { "code": null, "e": 4032, "s": 4025, "text": "20\n20\n" }, { "code": null, "e": 4165, "s": 4032, "text": "In the above code, both functions can use the global variable x as we already have global variables accessible by all the functions." }, { "code": null, "e": 4322, "s": 4165, "text": "3. Static Variable: A variable that retains its value between multiple function calls is known as a static variable. It is declared with the static keyword." }, { "code": null, "e": 4332, "s": 4322, "text": "Example: " }, { "code": null, "e": 4334, "s": 4332, "text": "C" }, { "code": "#include <stdio.h>void function(){ int x = 20;//local variable static int y = 30;//static variable x = x + 10; y = y + 10; printf(\"\\n%d,%d\",x,y); } int main() { function(); function(); function(); return 0;}", "e": 4547, "s": 4334, "text": null }, { "code": null, "e": 4565, "s": 4547, "text": "30,40\n30,50\n30,60" }, { "code": null, "e": 4760, "s": 4565, "text": "In the above example, the local variable will always print the same value whenever the function will be called whereas the static variable will print the incremented value in each function call." }, { "code": null, "e": 4999, "s": 4760, "text": "4. Automatic Variable: All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using the auto keyword. Automatic variables are similar to local variables. " }, { "code": null, "e": 5008, "s": 4999, "text": "Example:" }, { "code": null, "e": 5010, "s": 5008, "text": "C" }, { "code": "#include <stdio.h>void function(){ int x=10;//local variable (also automatic) auto int y=20;//automatic variable}int main() { function(); return 0;}", "e": 5169, "s": 5010, "text": null }, { "code": null, "e": 5312, "s": 5171, "text": "In the above example, both x and y are automatic variables. The only difference is that variable y is explicitly declared with auto keyword." }, { "code": null, "e": 5451, "s": 5312, "text": "5. External Variable: External variables can be shared between multiple C files. We can declare an external variable using extern keyword." }, { "code": null, "e": 5461, "s": 5451, "text": "Example: " }, { "code": null, "e": 5671, "s": 5461, "text": " myfile.h\n\n extern int x=10;//external variable (also global) \n\n \n program1.c\n #include \"myfile.h\" \n #include <stdio.h> \n void printValue(){ \n printf(\"Global variable: %d\", global_variable); \n }" }, { "code": null, "e": 5751, "s": 5671, "text": "In the above example, x is an external variable that is used in multiple files." }, { "code": null, "e": 5873, "s": 5751, "text": "Keywords : These are reserved words whose meaning is already known to the compiler. There are 32 keywords available in c:" }, { "code": null, "e": 6829, "s": 5873, "text": " auto double int struct\n break long else switch\n case return enum typedef\n char register extern union\n const short float unsigned\n continue signed for void\n default sizeof goto volatile\n do static if while" }, { "code": null, "e": 6997, "s": 6829, "text": "Most of these keywords have already been discussed in the various sub-sections of the C language, like Data Types, Storage Classes, Control Statements, Functions, etc." }, { "code": null, "e": 7091, "s": 6997, "text": "Let us discuss some of the other keywords which allow us to use the basic functionality of C:" }, { "code": null, "e": 7325, "s": 7091, "text": "const: const can be used to declare constant variables. Constant variables are variables that, when initialized, can’t change their value. Or in other words, the value assigned to them cannot be modified further down in the program. " }, { "code": null, "e": 7334, "s": 7325, "text": "Syntax: " }, { "code": null, "e": 7372, "s": 7334, "text": "const data_type var_name = var_value;" }, { "code": null, "e": 7551, "s": 7372, "text": "Note: Constant variables must be initialized during their declaration. const keyword is also used with pointers. Please refer the const qualifier in C for understanding the same." }, { "code": null, "e": 8392, "s": 7551, "text": "extern: extern simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. " }, { "code": null, "e": 8401, "s": 8392, "text": "Syntax: " }, { "code": null, "e": 8440, "s": 8401, "text": "extern data_type var_name = var_value;" }, { "code": null, "e": 9141, "s": 8440, "text": "static: static keyword is used to declare static variables, which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere within that file as their scope is local to the file. By default, they are assigned the value 0 by the compiler. Syntax: " }, { "code": null, "e": 9180, "s": 9141, "text": "static data_type var_name = var_value;" }, { "code": null, "e": 9689, "s": 9180, "text": "void: void is a special data type. But what makes it so special? void, as it literally means, is an empty data type. It means it has nothing or it holds no value. For example, when it is used as the return data type for a function it simply represents that the function returns no value. Similarly, when it’s added to a function heading, it represents that the function takes no arguments. Note: void also has a significant use with pointers. Please refer to the void pointer in C for understanding the same." }, { "code": null, "e": 9985, "s": 9689, "text": "typedef: typedef is used to give a new name to an already existing or even a custom data type (like a structure). It comes in very handy at times, for example in a case when the name of the structure defined by you is very long or you just need a short-hand notation of a pre-existing data type." }, { "code": null, "e": 10139, "s": 9985, "text": "Let’s implement the keywords which we have discussed above. Take a look at the following code which is a working example to demonstrate these keywords: " }, { "code": null, "e": 10147, "s": 10139, "text": "Example" }, { "code": null, "e": 10149, "s": 10147, "text": "C" }, { "code": "#include <stdio.h> // declaring and initializing an extern variableextern int x = 9; // declaring and initializing a global variable// simply int z; would have initialized z with// the default value of a global variable which is 0int z = 10; // using typedef to give a short name to long long int// very convenient to use now due to the short nametypedef long long int LL; // function which prints square of a no. and which has void// as its return data typevoid calSquare(int arg){ printf(\"The square of %d is %d\\n\", arg, arg * arg);} // Here void means function main takes no parametersint main(void){ // declaring a constant variable, its value cannot be // modified const int a = 32; // declaring a char variable char b = 'G'; // telling the compiler that the variable z is an extern // variable and has been defined elsewhere (above the // main function) extern int z; LL c = 1000000; printf(\"Hello World!\\n\"); // printing the above variables printf(\"This is the value of the constant variable \" \"'a': %d\\n\", a); printf(\"'b' is a char variable. Its value is %c\\n\", b); printf(\"'c' is a long long int variable. Its value is \" \"%lld\\n\", c); printf(\"These are the values of the extern variables \" \"'x' and 'z'\" \" respectively: %d and %d\\n\", x, z); // value of extern variable x modified x = 2; // value of extern variable z modified z = 5; // printing the modified values of extern variables 'x' // and 'z' printf(\"These are the modified values of the extern \" \"variables\" \" 'x' and 'z' respectively: %d and %d\\n\", x, z); // using a static variable printf(\"The value of static variable 'y' is NOT \" \"initialized to 5 after the \" \"first iteration! See for yourself :)\\n\"); while (x > 0) { static int y = 5; y++; // printing value at each iteration printf(\"The value of y is %d\\n\", y); x--; } // print square of 5 calSquare(5); printf(\"Bye! See you soon. :)\\n\"); return 0;}", "e": 12287, "s": 10149, "text": null }, { "code": null, "e": 12296, "s": 12287, "text": "Output: " }, { "code": null, "e": 12808, "s": 12296, "text": "Hello World\nThis is the value of the constant variable 'a': 32\n'b' is a char variable. Its value is G\n'c' is a long long int variable. Its value is 1000000\nThese are the values of the extern variables 'x' and 'z' respectively: 9 and 10\nThese are the modified values of the extern variables 'x' and 'z' respectively: 2 and 5\nThe value of static variable 'y' is NOT initialized to 5 after the first iteration! See for yourself :)\nThe value of y is 6\nThe value of y is 7\nThe square of 5 is 25\nBye! See you soon. :)" }, { "code": null, "e": 12980, "s": 12808, "text": "This article is contributed by Ayush Jaggi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 12993, "s": 12980, "text": "InathiSirayi" }, { "code": null, "e": 13011, "s": 12993, "text": "Srinivas Nekkanti" }, { "code": null, "e": 13026, "s": 13011, "text": "alankritiyadav" }, { "code": null, "e": 13041, "s": 13026, "text": "divyanshtiwari" }, { "code": null, "e": 13060, "s": 13041, "text": "shubhankarsharma22" }, { "code": null, "e": 13076, "s": 13060, "text": "srujanpoojari08" }, { "code": null, "e": 13094, "s": 13076, "text": "suruchikumarimfp4" }, { "code": null, "e": 13103, "s": 13094, "text": "C Basics" }, { "code": null, "e": 13136, "s": 13103, "text": "C-Variable Declaration and Scope" }, { "code": null, "e": 13147, "s": 13136, "text": "C Language" }, { "code": null, "e": 13166, "s": 13147, "text": "School Programming" } ]
Understanding “volatile” qualifier in C | Set 2 (Examples)
17 Jun, 2022 The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in a temporary register at the point it is requested, even if a previous instruction asked for the value from the same object. So the simple question is, how can the value of a variable change in such a way that the compiler cannot predict? Consider the following cases for an answer to this question: 1) Global variables modified by an interrupt service routine outside the scope: For example, a global variable can represent a data port (usually a global pointer, referred to as memory mapped IO) which will be updated dynamically. The code reading the data port must be declared as volatile in order to fetch the latest data available at the port. Failing to declare the variable as volatile will result in the compiler optimizing the code in such a way that it will read the port only once and keep using the same value in a temporary register to speed up the program (speed optimization). In general, an ISR is used to update these data ports when there is an interrupt due to the availability of new data. 2) Global variables within a multi-threaded application: There are multiple ways for threads’ communication, viz., message passing, shared memory, mail boxes, etc. A global variable is weak form of shared memory. When two threads are sharing information via global variables, those variables need to be qualified with volatile. Since threads run asynchronously, any update of global variables due to one thread should be fetched freshly by the other consumer thread. The compiler can read the global variables and place them in temporary variables of the current thread context. To nullify the effect of compiler optimizations, such global variables need to be qualified as volatile. If we do not use volatile qualifier, the following problems may arise: 1) Code may not work as expected when optimization is turned on. 2) Code may not work as expected when interrupts are enabled and used. Let us see an example to understand how compilers interpret volatile keyword. Consider the below code. We are changing the value of a const object using a pointer and we are compiling code without optimization option. Hence the compiler won’t do any optimization and will change the value of the const object. C /* Compile code without optimization option */#include <stdio.h>int main(void){ const int local = 10; int *ptr = (int*) &local; printf("Initial value of local : %d \n", local); *ptr = 100; printf("Modified value of local: %d \n", local); return 0;} When we compile code with “–save-temps” option of gcc, it generates 3 output files:1) preprocessed code (having .i extension) 2) assembly code (having .s extension) and 3) object code (having .o extension). We compiled code without optimization, that’s why the size of assembly code will be larger (which is highlighted in red below). Output: [narendra@ubuntu]$ gcc volatile.c -o volatile –save-temps [narendra@ubuntu]$ ./volatile Initial value of local : 10 Modified value of local: 100 [narendra@ubuntu]$ ls -l volatile.s -rw-r–r– 1 narendra narendra 731 2016-11-19 16:19 volatile.s [narendra@ubuntu]$ Let us compile the same code with optimization option (i.e. -O option). In the below code, “local” is declared as const (and non-volatile). The GCC compiler does optimization and ignores the instructions which try to change the value of the const object. Hence the value of the const object remains same. C /* Compile code with optimization option */#include <stdio.h> int main(void){ const int local = 10; int *ptr = (int*) &local; printf("Initial value of local : %d \n", local); *ptr = 100; printf("Modified value of local: %d \n", local); return 0;} For the above code, the compiler does optimization, that’s why the size of assembly code will reduce. Output: [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temps [narendra@ubuntu]$ ./volatile Initial value of local : 10 Modified value of local: 10 [narendra@ubuntu]$ ls -l volatile.s -rw-r–r– 1 narendra narendra 626 2016-11-19 16:21 volatile.s Let us declare the const object as volatile and compile code with optimization option. Although we compile code with optimization option, the value of the const object will change because the variable is declared as volatile which means, don’t do any optimization. C /* Compile code with optimization option */#include <stdio.h> int main(void){ const volatile int local = 10; int *ptr = (int*) &local; printf("Initial value of local : %d \n", local); *ptr = 100; printf("Modified value of local: %d \n", local); return 0;} Output: [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temp [narendra@ubuntu]$ ./volatile Initial value of local : 10 Modified value of local: 100 [narendra@ubuntu]$ ls -l volatile.s -rw-r–r– 1 narendra narendra 711 2016-11-19 16:22 volatile.s [narendra@ubuntu]$ The above example may not be a good practical example, but the purpose was to explain how compilers interpret volatile keyword. As a practical example, think of the touch sensor on mobile phones. The driver abstracting the touch sensor will read the location of touch and send it to higher level applications. The driver itself should not modify (const-ness) the read location, and make sure it reads the touch input every time fresh (volatile-ness). Such driver must read the touch sensor input in const volatile manner. Note: The above codes are compiler specific and may not work on all compilers. The purpose of the examples is to make readers understand the concept. Related Article : Understanding “volatile” qualifier in C | Set 1 (Introduction)Refer to the following links for more details on volatile keyword: Volatile: A programmer’s best friend Do not use volatile as a synchronization primitiveThis article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shohamziner arorakashish0911 anikakapoor sriparnxnw7 C-Storage Classes and Type Qualifiers C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 222, "s": 54, "text": "The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. " }, { "code": null, "e": 793, "s": 222, "text": "Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in a temporary register at the point it is requested, even if a previous instruction asked for the value from the same object. So the simple question is, how can the value of a variable change in such a way that the compiler cannot predict? Consider the following cases for an answer to this question: " }, { "code": null, "e": 1504, "s": 793, "text": "1) Global variables modified by an interrupt service routine outside the scope: For example, a global variable can represent a data port (usually a global pointer, referred to as memory mapped IO) which will be updated dynamically. The code reading the data port must be declared as volatile in order to fetch the latest data available at the port. Failing to declare the variable as volatile will result in the compiler optimizing the code in such a way that it will read the port only once and keep using the same value in a temporary register to speed up the program (speed optimization). In general, an ISR is used to update these data ports when there is an interrupt due to the availability of new data. " }, { "code": null, "e": 2188, "s": 1504, "text": "2) Global variables within a multi-threaded application: There are multiple ways for threads’ communication, viz., message passing, shared memory, mail boxes, etc. A global variable is weak form of shared memory. When two threads are sharing information via global variables, those variables need to be qualified with volatile. Since threads run asynchronously, any update of global variables due to one thread should be fetched freshly by the other consumer thread. The compiler can read the global variables and place them in temporary variables of the current thread context. To nullify the effect of compiler optimizations, such global variables need to be qualified as volatile." }, { "code": null, "e": 2395, "s": 2188, "text": "If we do not use volatile qualifier, the following problems may arise: 1) Code may not work as expected when optimization is turned on. 2) Code may not work as expected when interrupts are enabled and used." }, { "code": null, "e": 2705, "s": 2395, "text": "Let us see an example to understand how compilers interpret volatile keyword. Consider the below code. We are changing the value of a const object using a pointer and we are compiling code without optimization option. Hence the compiler won’t do any optimization and will change the value of the const object." }, { "code": null, "e": 2707, "s": 2705, "text": "C" }, { "code": "/* Compile code without optimization option */#include <stdio.h>int main(void){ const int local = 10; int *ptr = (int*) &local; printf(\"Initial value of local : %d \\n\", local); *ptr = 100; printf(\"Modified value of local: %d \\n\", local); return 0;}", "e": 2978, "s": 2707, "text": null }, { "code": null, "e": 3186, "s": 2978, "text": "When we compile code with “–save-temps” option of gcc, it generates 3 output files:1) preprocessed code (having .i extension) 2) assembly code (having .s extension) and 3) object code (having .o extension). " }, { "code": null, "e": 3314, "s": 3186, "text": "We compiled code without optimization, that’s why the size of assembly code will be larger (which is highlighted in red below)." }, { "code": null, "e": 3323, "s": 3314, "text": "Output: " }, { "code": null, "e": 3598, "s": 3323, "text": " [narendra@ubuntu]$ gcc volatile.c -o volatile –save-temps\n [narendra@ubuntu]$ ./volatile\n Initial value of local : 10\n Modified value of local: 100\n [narendra@ubuntu]$ ls -l volatile.s\n -rw-r–r– 1 narendra narendra 731 2016-11-19 16:19 volatile.s\n [narendra@ubuntu]$" }, { "code": null, "e": 3904, "s": 3598, "text": "Let us compile the same code with optimization option (i.e. -O option). In the below code, “local” is declared as const (and non-volatile). The GCC compiler does optimization and ignores the instructions which try to change the value of the const object. Hence the value of the const object remains same. " }, { "code": null, "e": 3906, "s": 3904, "text": "C" }, { "code": "/* Compile code with optimization option */#include <stdio.h> int main(void){ const int local = 10; int *ptr = (int*) &local; printf(\"Initial value of local : %d \\n\", local); *ptr = 100; printf(\"Modified value of local: %d \\n\", local); return 0;}", "e": 4175, "s": 3906, "text": null }, { "code": null, "e": 4277, "s": 4175, "text": "For the above code, the compiler does optimization, that’s why the size of assembly code will reduce." }, { "code": null, "e": 4286, "s": 4277, "text": "Output: " }, { "code": null, "e": 4543, "s": 4286, "text": " [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temps\n [narendra@ubuntu]$ ./volatile\n Initial value of local : 10\n Modified value of local: 10\n [narendra@ubuntu]$ ls -l volatile.s\n -rw-r–r– 1 narendra narendra 626 2016-11-19 16:21 volatile.s" }, { "code": null, "e": 4809, "s": 4543, "text": "Let us declare the const object as volatile and compile code with optimization option. Although we compile code with optimization option, the value of the const object will change because the variable is declared as volatile which means, don’t do any optimization. " }, { "code": null, "e": 4811, "s": 4809, "text": "C" }, { "code": "/* Compile code with optimization option */#include <stdio.h> int main(void){ const volatile int local = 10; int *ptr = (int*) &local; printf(\"Initial value of local : %d \\n\", local); *ptr = 100; printf(\"Modified value of local: %d \\n\", local); return 0;}", "e": 5089, "s": 4811, "text": null }, { "code": null, "e": 5098, "s": 5089, "text": "Output: " }, { "code": null, "e": 5376, "s": 5098, "text": " [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temp\n [narendra@ubuntu]$ ./volatile\n Initial value of local : 10\n Modified value of local: 100\n [narendra@ubuntu]$ ls -l volatile.s\n -rw-r–r– 1 narendra narendra 711 2016-11-19 16:22 volatile.s\n [narendra@ubuntu]$" }, { "code": null, "e": 5898, "s": 5376, "text": "The above example may not be a good practical example, but the purpose was to explain how compilers interpret volatile keyword. As a practical example, think of the touch sensor on mobile phones. The driver abstracting the touch sensor will read the location of touch and send it to higher level applications. The driver itself should not modify (const-ness) the read location, and make sure it reads the touch input every time fresh (volatile-ness). Such driver must read the touch sensor input in const volatile manner." }, { "code": null, "e": 6048, "s": 5898, "text": "Note: The above codes are compiler specific and may not work on all compilers. The purpose of the examples is to make readers understand the concept." }, { "code": null, "e": 6494, "s": 6048, "text": "Related Article : Understanding “volatile” qualifier in C | Set 1 (Introduction)Refer to the following links for more details on volatile keyword: Volatile: A programmer’s best friend Do not use volatile as a synchronization primitiveThis article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6506, "s": 6494, "text": "shohamziner" }, { "code": null, "e": 6523, "s": 6506, "text": "arorakashish0911" }, { "code": null, "e": 6535, "s": 6523, "text": "anikakapoor" }, { "code": null, "e": 6547, "s": 6535, "text": "sriparnxnw7" }, { "code": null, "e": 6585, "s": 6547, "text": "C-Storage Classes and Type Qualifiers" }, { "code": null, "e": 6596, "s": 6585, "text": "C Language" } ]
How to Validate a Password using Regular Expressions in Android?
11 Dec, 2020 Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following: MatchResult InterfaceMatcher classPattern classPatternSyntaxException class MatchResult Interface Matcher class Pattern class PatternSyntaxException class Pattern p = Pattern.compile(“.e”); // represents single character Matcher m = p.matcher(“geeks”); boolean b = m.matches(); // the boolean value of ‘b’ is true as second character in geeks is ‘e’ In this example, we will validate email and password on the client-side which means that we don’t check that email-password are stored at some server and matches to it, instead, we compare the email-password to a predefined pattern. Note we are going to implement this project in Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding Dependencies In order to use the design support library, we need to add its dependencies. Go to Gradle Scripts > build.gradle(Module:app) and add the following dependencies. After adding the dependency click on Sync Now. implementation ‘com.google.android.material:material:1.0.0’ Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources> Step 3: Designing the layout file In this step, we will design the layout for our application. Go to app > res > layout > activity_main.xml. In this layout, we have used TextInputLayout in order to add extra features to our EditText, such as spacing for error message below Views. Below is the code snippet is given for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:inputType="textEmailAddress" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="true" app:passwordToggleEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="confirmInput" android:text="Submit" /> </LinearLayout> Step 4: Working with the MainActivity.java file In the MainActivity.java file we use the predefined pattern for Email validation and define our own pattern for password validation. For this, we have defined two methods ValidateEmail() and ValidatePassword(). ValidateEmail() method uses predefined email pattern .i.e., it must have ‘@’ and ‘.'(dot) in the input email. If the email fails to satisfy the condition it will display an error message “Please enter a valid email address”. In ValidatePassword(), we define our own pattern as: private static final Pattern PASSWORD_PATTERN = Pattern.compile(“^” + “(?=.*[@#$%^&+=])” + // at least 1 special character “(?=\\S+$)” + // no white spaces “.{4,}” + // at least 4 characters “$”); If the password fails to satisfy any of these conditions, an error message will be shown as “Password is too weak”. If any of the field email or password is empty, it will display “Fields can not be empty”. If both email and password match the conditions, a toast message will be displayed which shows that input email and password. Below is the code snippet for the MainActivity.java file. Java import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.textfield.TextInputLayout;import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { // defining our own password pattern private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[@#$%^&+=])" + // at least 1 special character "(?=\\S+$)" + // no white spaces ".{4,}" + // at least 4 characters "$"); private TextInputLayout email; private TextInputLayout password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing email and password email = findViewById(R.id.email); password = findViewById(R.id.password); } private boolean validateEmail() { // Extract input from EditText String emailInput = email.getEditText().getText().toString().trim(); // if the email input field is empty if (emailInput.isEmpty()) { email.setError("Field can not be empty"); return false; } // Matching the input email to a predefined email pattern else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { email.setError("Please enter a valid email address"); return false; } else { email.setError(null); return true; } } private boolean validatePassword() { String passwordInput = password.getEditText().getText().toString().trim(); // if password field is empty // it will display error message "Field can not be empty" if (passwordInput.isEmpty()) { password.setError("Field can not be empty"); return false; } // if password does not matches to the pattern // it will display an error message "Password is too weak" else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) { password.setError("Password is too weak"); return false; } else { password.setError(null); return true; } } public void confirmInput(View v) { if (!validateEmail() | !validatePassword()) { return; } // if the email and password matches, a toast message // with email and password is displayed String input = "Email: " + email.getEditText().getText().toString(); input += "\n"; input += "Password: " + password.getEditText().getText().toString(); Toast.makeText(this, input, Toast.LENGTH_SHORT).show(); }} android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Android Project folder Structure Broadcast Receiver in Android With Example Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 238, "s": 28, "text": "Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following:" }, { "code": null, "e": 314, "s": 238, "text": "MatchResult InterfaceMatcher classPattern classPatternSyntaxException class" }, { "code": null, "e": 336, "s": 314, "text": "MatchResult Interface" }, { "code": null, "e": 350, "s": 336, "text": "Matcher class" }, { "code": null, "e": 364, "s": 350, "text": "Pattern class" }, { "code": null, "e": 393, "s": 364, "text": "PatternSyntaxException class" }, { "code": null, "e": 459, "s": 393, "text": "Pattern p = Pattern.compile(“.e”); // represents single character" }, { "code": null, "e": 491, "s": 459, "text": "Matcher m = p.matcher(“geeks”);" }, { "code": null, "e": 588, "s": 491, "text": "boolean b = m.matches(); // the boolean value of ‘b’ is true as second character in geeks is ‘e’" }, { "code": null, "e": 883, "s": 588, "text": "In this example, we will validate email and password on the client-side which means that we don’t check that email-password are stored at some server and matches to it, instead, we compare the email-password to a predefined pattern. Note we are going to implement this project in Java language." }, { "code": null, "e": 912, "s": 883, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1074, "s": 912, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1102, "s": 1074, "text": "Step 2: Adding Dependencies" }, { "code": null, "e": 1310, "s": 1102, "text": "In order to use the design support library, we need to add its dependencies. Go to Gradle Scripts > build.gradle(Module:app) and add the following dependencies. After adding the dependency click on Sync Now." }, { "code": null, "e": 1370, "s": 1310, "text": "implementation ‘com.google.android.material:material:1.0.0’" }, { "code": null, "e": 1536, "s": 1370, "text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. " }, { "code": null, "e": 1540, "s": 1536, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ", "e": 1710, "s": 1540, "text": null }, { "code": null, "e": 1744, "s": 1710, "text": "Step 3: Designing the layout file" }, { "code": null, "e": 2058, "s": 1744, "text": "In this step, we will design the layout for our application. Go to app > res > layout > activity_main.xml. In this layout, we have used TextInputLayout in order to add extra features to our EditText, such as spacing for error message below Views. Below is the code snippet is given for the activity_main.xml file." }, { "code": null, "e": 2062, "s": 2058, "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\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:errorEnabled=\"true\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Email\" android:inputType=\"textEmailAddress\" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:errorEnabled=\"true\" app:passwordToggleEnabled=\"true\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Password\" android:inputType=\"textPassword\" /> </com.google.android.material.textfield.TextInputLayout> <Button android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:onClick=\"confirmInput\" android:text=\"Submit\" /> </LinearLayout>", "e": 3716, "s": 2062, "text": null }, { "code": null, "e": 3764, "s": 3716, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 4253, "s": 3764, "text": "In the MainActivity.java file we use the predefined pattern for Email validation and define our own pattern for password validation. For this, we have defined two methods ValidateEmail() and ValidatePassword(). ValidateEmail() method uses predefined email pattern .i.e., it must have ‘@’ and ‘.'(dot) in the input email. If the email fails to satisfy the condition it will display an error message “Please enter a valid email address”. In ValidatePassword(), we define our own pattern as:" }, { "code": null, "e": 4301, "s": 4253, "text": "private static final Pattern PASSWORD_PATTERN =" }, { "code": null, "e": 4334, "s": 4301, "text": " Pattern.compile(“^” +" }, { "code": null, "e": 4410, "s": 4334, "text": " “(?=.*[@#$%^&+=])” + // at least 1 special character" }, { "code": null, "e": 4482, "s": 4410, "text": " “(?=\\\\S+$)” + // no white spaces" }, { "code": null, "e": 4565, "s": 4482, "text": " “.{4,}” + // at least 4 characters" }, { "code": null, "e": 4590, "s": 4565, "text": " “$”);" }, { "code": null, "e": 4982, "s": 4590, "text": "If the password fails to satisfy any of these conditions, an error message will be shown as “Password is too weak”. If any of the field email or password is empty, it will display “Fields can not be empty”. If both email and password match the conditions, a toast message will be displayed which shows that input email and password. Below is the code snippet for the MainActivity.java file." }, { "code": null, "e": 4987, "s": 4982, "text": "Java" }, { "code": "import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.textfield.TextInputLayout;import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { // defining our own password pattern private static final Pattern PASSWORD_PATTERN = Pattern.compile(\"^\" + \"(?=.*[@#$%^&+=])\" + // at least 1 special character \"(?=\\\\S+$)\" + // no white spaces \".{4,}\" + // at least 4 characters \"$\"); private TextInputLayout email; private TextInputLayout password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing email and password email = findViewById(R.id.email); password = findViewById(R.id.password); } private boolean validateEmail() { // Extract input from EditText String emailInput = email.getEditText().getText().toString().trim(); // if the email input field is empty if (emailInput.isEmpty()) { email.setError(\"Field can not be empty\"); return false; } // Matching the input email to a predefined email pattern else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { email.setError(\"Please enter a valid email address\"); return false; } else { email.setError(null); return true; } } private boolean validatePassword() { String passwordInput = password.getEditText().getText().toString().trim(); // if password field is empty // it will display error message \"Field can not be empty\" if (passwordInput.isEmpty()) { password.setError(\"Field can not be empty\"); return false; } // if password does not matches to the pattern // it will display an error message \"Password is too weak\" else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) { password.setError(\"Password is too weak\"); return false; } else { password.setError(null); return true; } } public void confirmInput(View v) { if (!validateEmail() | !validatePassword()) { return; } // if the email and password matches, a toast message // with email and password is displayed String input = \"Email: \" + email.getEditText().getText().toString(); input += \"\\n\"; input += \"Password: \" + password.getEditText().getText().toString(); Toast.makeText(this, input, Toast.LENGTH_SHORT).show(); }}", "e": 7895, "s": 4987, "text": null }, { "code": null, "e": 7903, "s": 7895, "text": "android" }, { "code": null, "e": 7927, "s": 7903, "text": "Technical Scripter 2020" }, { "code": null, "e": 7935, "s": 7927, "text": "Android" }, { "code": null, "e": 7940, "s": 7935, "text": "Java" }, { "code": null, "e": 7959, "s": 7940, "text": "Technical Scripter" }, { "code": null, "e": 7964, "s": 7959, "text": "Java" }, { "code": null, "e": 7972, "s": 7964, "text": "Android" }, { "code": null, "e": 8070, "s": 7972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8102, "s": 8070, "text": "Android SDK and it's Components" }, { "code": null, "e": 8133, "s": 8102, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 8166, "s": 8133, "text": "Android Project folder Structure" }, { "code": null, "e": 8209, "s": 8166, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 8248, "s": 8209, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8263, "s": 8248, "text": "Arrays in Java" }, { "code": null, "e": 8307, "s": 8263, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8343, "s": 8307, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8394, "s": 8343, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to create matrix and vector from CSV file in R ?
21 Apr, 2021 In this article, we will discuss how to convert CSV data into a matrix and a vector in R Programming Language. We will use read.csv() function to load the csv file: Syntax: object=read.csv(path) where, path is the location of a file present in our local system. Matrix: Matrix is a two-dimensional data structure that contains rows and columns. It can hold multiple data types. We can convert csv file data into matrix by using the method called as.matrix() Syntax:as.matrix(csv_file_object) Vector: Vector is a one-dimensional data structure that can hold multiple datatypes. We can convert CSV data into a vector, By using as.vector() Syntax: as.vector(csv_file_object) CSV File Used: Step 1: Create an object to CSV by reading the path R data=read.csv("C:/sravan/data.csv")print(data) Output: Name ID 1 sravan 7058 2 Jyothika 7059 Step 2: Convert the data into a matrix. R matrixdata = as.matrix(data)print(matrixdata) Output: Name ID [1, ] "sravan" "7058" [2, ] " Jyothika" "7059" Step 3: Convert the data into a vector R vectordata=as.vector(data)print(vectordata) Output: Name ID 1 sravan 7058 2 Jyothika 7059 Below is the full implementation: R # Read data from CSVdata=read.csv("C:/sravan/data.csv") # Create a matrixmatrixdata=as.matrix(data) # Create a vectorvectordata=as.vector(data)print(matrixdata)print(vectordata) Output: Name ID [1, ] "sravan" "7058" [2, ] " Jyothika" "7059" Name ID 1 sravan 7058 2 Jyothika 7059 Picked R-CSV R-Matrix R-Vectors R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 193, "s": 28, "text": "In this article, we will discuss how to convert CSV data into a matrix and a vector in R Programming Language. We will use read.csv() function to load the csv file:" }, { "code": null, "e": 223, "s": 193, "text": "Syntax: object=read.csv(path)" }, { "code": null, "e": 290, "s": 223, "text": "where, path is the location of a file present in our local system." }, { "code": null, "e": 486, "s": 290, "text": "Matrix: Matrix is a two-dimensional data structure that contains rows and columns. It can hold multiple data types. We can convert csv file data into matrix by using the method called as.matrix()" }, { "code": null, "e": 520, "s": 486, "text": "Syntax:as.matrix(csv_file_object)" }, { "code": null, "e": 665, "s": 520, "text": "Vector: Vector is a one-dimensional data structure that can hold multiple datatypes. We can convert CSV data into a vector, By using as.vector()" }, { "code": null, "e": 700, "s": 665, "text": "Syntax: as.vector(csv_file_object)" }, { "code": null, "e": 715, "s": 700, "text": "CSV File Used:" }, { "code": null, "e": 767, "s": 715, "text": "Step 1: Create an object to CSV by reading the path" }, { "code": null, "e": 769, "s": 767, "text": "R" }, { "code": "data=read.csv(\"C:/sravan/data.csv\")print(data)", "e": 816, "s": 769, "text": null }, { "code": null, "e": 824, "s": 816, "text": "Output:" }, { "code": null, "e": 878, "s": 824, "text": " Name ID\n1 sravan 7058\n2 Jyothika 7059" }, { "code": null, "e": 918, "s": 878, "text": "Step 2: Convert the data into a matrix." }, { "code": null, "e": 920, "s": 918, "text": "R" }, { "code": "matrixdata = as.matrix(data)print(matrixdata)", "e": 966, "s": 920, "text": null }, { "code": null, "e": 974, "s": 966, "text": "Output:" }, { "code": null, "e": 1045, "s": 974, "text": " Name ID\n[1, ] \"sravan\" \"7058\"\n[2, ] \" Jyothika\" \"7059\"" }, { "code": null, "e": 1084, "s": 1045, "text": "Step 3: Convert the data into a vector" }, { "code": null, "e": 1086, "s": 1084, "text": "R" }, { "code": "vectordata=as.vector(data)print(vectordata)", "e": 1130, "s": 1086, "text": null }, { "code": null, "e": 1138, "s": 1130, "text": "Output:" }, { "code": null, "e": 1192, "s": 1138, "text": " Name ID\n1 sravan 7058\n2 Jyothika 7059" }, { "code": null, "e": 1226, "s": 1192, "text": "Below is the full implementation:" }, { "code": null, "e": 1228, "s": 1226, "text": "R" }, { "code": "# Read data from CSVdata=read.csv(\"C:/sravan/data.csv\") # Create a matrixmatrixdata=as.matrix(data) # Create a vectorvectordata=as.vector(data)print(matrixdata)print(vectordata)", "e": 1408, "s": 1228, "text": null }, { "code": null, "e": 1416, "s": 1408, "text": "Output:" }, { "code": null, "e": 1541, "s": 1416, "text": " Name ID\n[1, ] \"sravan\" \"7058\"\n[2, ] \" Jyothika\" \"7059\"\n Name ID\n1 sravan 7058\n2 Jyothika 7059" }, { "code": null, "e": 1548, "s": 1541, "text": "Picked" }, { "code": null, "e": 1554, "s": 1548, "text": "R-CSV" }, { "code": null, "e": 1563, "s": 1554, "text": "R-Matrix" }, { "code": null, "e": 1573, "s": 1563, "text": "R-Vectors" }, { "code": null, "e": 1584, "s": 1573, "text": "R Language" } ]
Node.js Web Server
13 Oct, 2021 What is Node.js ?Node.js is an open source server environment. Node.js uses JavaScript on the server. The task of a web server is to open a file on the server and return the content to the client. Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. Example: // Import the Node.js http modulevar http = require('http'); // req is the request object which is// coming from the client side// res is the response object which is going// to client as response from the server // Create a server objecthttp.createServer(function (req, res) { // 200 is the status code which means// All OK and the second argument is// the object of response header.res.writeHead(200, {'Content-Type': 'text/html'}); // Write a response to the client res.write('Congrats you have a created a web server'); // End the response res.end(); }).listen(8081); // Server object listens on port 8081 console.log('Node.js web server at port 8081 is running..') The function passed in the http.createServer() will be executed when the client goes to the url http://localhost:8081. Steps to run the code: Save the above code in a file with .js extension Open the command prompt and goes to the folder where the file is there using cd command. Run the command node file_name.js Open the browser and go the url http://localhost:8081 When http://localhost:8081 is opened in browser. The http.createServer() method includes request object that can be used to get information about the current HTTP request e.g. url, request header, and data. The following example demonstrates handling HTTP request and response in Node.js. // Import Node.js core module i.e httpvar http = require('http'); // Create web servervar server = http.createServer(function (req, res) { // Check the URL of the current request if (req.url == '/') { // Set response header res.writeHead(200, { 'Content-Type': 'text/html' }); // Set response content res.write( `<html><body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks Home Page</h1> <p>A computer science portal</p> </body></html>`); res.end();//end the response } else if (req.url == "/webtech") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(` <html><body style="text-align:center;"> <h1 style="color:green;">Welcome to GeeksforGeeks</h1> <a href="https://www.geeksforgeeks.org/web-technology/"> Read Web Technology content </a> </body></html>`); res.end();//end the response } else if (req.url == "/DS") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(`<html><body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <a href="https://www.geeksforgeeks.org/data-structures/"> Read Data Structures Content </a> </body></html>`); res.end(); //end the response } else if (req.url == "/algo") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(`<html><body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <a href="https://www.geeksforgeeks.org/fundamentals-of-algorithms/"> Read Algorithm analysis and Design Content </a> </body></html>`); res.end(); //end the response } else res.end('Invalid Request!'); //end the response // Server object listens on port 8081}).listen(3000, ()=>console.log('Server running on port 3000')); In the above example, req.url is used to check the url of the current request and based on that it sends the response.Command to Run code: node index.js Output: URL: localhost:3000 URL: localhost:3000/webtech URL: localhost:3000/DS URL: localhost:3000/algo Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method How to connect Node.js with React.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": "\n13 Oct, 2021" }, { "code": null, "e": 225, "s": 28, "text": "What is Node.js ?Node.js is an open source server environment. Node.js uses JavaScript on the server. The task of a web server is to open a file on the server and return the content to the client." }, { "code": null, "e": 464, "s": 225, "text": "Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client." }, { "code": null, "e": 473, "s": 464, "text": "Example:" }, { "code": "// Import the Node.js http modulevar http = require('http'); // req is the request object which is// coming from the client side// res is the response object which is going// to client as response from the server // Create a server objecthttp.createServer(function (req, res) { // 200 is the status code which means// All OK and the second argument is// the object of response header.res.writeHead(200, {'Content-Type': 'text/html'}); // Write a response to the client res.write('Congrats you have a created a web server'); // End the response res.end(); }).listen(8081); // Server object listens on port 8081 console.log('Node.js web server at port 8081 is running..')", "e": 1166, "s": 473, "text": null }, { "code": null, "e": 1285, "s": 1166, "text": "The function passed in the http.createServer() will be executed when the client goes to the url http://localhost:8081." }, { "code": null, "e": 1308, "s": 1285, "text": "Steps to run the code:" }, { "code": null, "e": 1357, "s": 1308, "text": "Save the above code in a file with .js extension" }, { "code": null, "e": 1446, "s": 1357, "text": "Open the command prompt and goes to the folder where the file is there using cd command." }, { "code": null, "e": 1480, "s": 1446, "text": "Run the command node file_name.js" }, { "code": null, "e": 1534, "s": 1480, "text": "Open the browser and go the url http://localhost:8081" }, { "code": null, "e": 1583, "s": 1534, "text": "When http://localhost:8081 is opened in browser." }, { "code": null, "e": 1741, "s": 1583, "text": "The http.createServer() method includes request object that can be used to get information about the current HTTP request e.g. url, request header, and data." }, { "code": null, "e": 1823, "s": 1741, "text": "The following example demonstrates handling HTTP request and response in Node.js." }, { "code": "// Import Node.js core module i.e httpvar http = require('http'); // Create web servervar server = http.createServer(function (req, res) { // Check the URL of the current request if (req.url == '/') { // Set response header res.writeHead(200, { 'Content-Type': 'text/html' }); // Set response content res.write( `<html><body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks Home Page</h1> <p>A computer science portal</p> </body></html>`); res.end();//end the response } else if (req.url == \"/webtech\") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(` <html><body style=\"text-align:center;\"> <h1 style=\"color:green;\">Welcome to GeeksforGeeks</h1> <a href=\"https://www.geeksforgeeks.org/web-technology/\"> Read Web Technology content </a> </body></html>`); res.end();//end the response } else if (req.url == \"/DS\") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(`<html><body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <a href=\"https://www.geeksforgeeks.org/data-structures/\"> Read Data Structures Content </a> </body></html>`); res.end(); //end the response } else if (req.url == \"/algo\") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(`<html><body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <a href=\"https://www.geeksforgeeks.org/fundamentals-of-algorithms/\"> Read Algorithm analysis and Design Content </a> </body></html>`); res.end(); //end the response } else res.end('Invalid Request!'); //end the response // Server object listens on port 8081}).listen(3000, ()=>console.log('Server running on port 3000'));", "e": 3876, "s": 1823, "text": null }, { "code": null, "e": 4015, "s": 3876, "text": "In the above example, req.url is used to check the url of the current request and based on that it sends the response.Command to Run code:" }, { "code": null, "e": 4029, "s": 4015, "text": "node index.js" }, { "code": null, "e": 4037, "s": 4029, "text": "Output:" }, { "code": null, "e": 4057, "s": 4037, "text": "URL: localhost:3000" }, { "code": null, "e": 4085, "s": 4057, "text": "URL: localhost:3000/webtech" }, { "code": null, "e": 4108, "s": 4085, "text": "URL: localhost:3000/DS" }, { "code": null, "e": 4133, "s": 4108, "text": "URL: localhost:3000/algo" }, { "code": null, "e": 4148, "s": 4133, "text": "Node.js-Basics" }, { "code": null, "e": 4155, "s": 4148, "text": "Picked" }, { "code": null, "e": 4163, "s": 4155, "text": "Node.js" }, { "code": null, "e": 4180, "s": 4163, "text": "Web Technologies" }, { "code": null, "e": 4278, "s": 4180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4310, "s": 4278, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 4345, "s": 4310, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 4415, "s": 4345, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 4442, "s": 4415, "text": "Mongoose Populate() Method" }, { "code": null, "e": 4481, "s": 4442, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 4543, "s": 4481, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4604, "s": 4543, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4654, "s": 4604, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4697, "s": 4654, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | ToDo GUI Application using Tkinter
10 Jun, 2021 Prerequisites : Introduction to tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. To create a tkinter : Importing the module – tkinter Create the main window (container) Add any number of widgets to the main window. Apply the event Trigger on the widgets. The GUI would look like below: Let’s create a GUI based simple ToDo application in which you can add and delete the Task. Below is the implementation : Python3 # import all functions from the tkinter from tkinter import * # import messagebox class from tkinterfrom tkinter import messagebox # global list is declare for storing all the tasktasks_list = [] # global variable is declare for counting the taskcounter = 1 # Function for checking input error when# empty input is given in task fielddef inputError() : # check for enter task field is empty or not if enterTaskField.get() == "" : # show the error message messagebox.showerror("Input Error") return 0 return 1 # Function for clearing the contents# of task number text fielddef clear_taskNumberField() : # clear the content of task number text field taskNumberField.delete(0.0, END) # Function for clearing the contents# of task entry field def clear_taskField() : # clear the content of task field entry box enterTaskField.delete(0, END) # Function for inserting the contents# from the task entry field to the text areadef insertTask(): global counter # check for error value = inputError() # if error occur then return if value == 0 : return # get the task string concatenating # with new line character content = enterTaskField.get() + "\n" # store task in the list tasks_list.append(content) # insert content of task entry field to the text area # add task one by one in below one by one TextArea.insert('end -1 chars', "[ " + str(counter) + " ] " + content) # incremented counter += 1 # function calling for deleting the content of task field clear_taskField() # function for deleting the specified taskdef delete() : global counter # handling the empty task error if len(tasks_list) == 0 : messagebox.showerror("No task") return # get the task number, which is required to delete number = taskNumberField.get(1.0, END) # checking for input error when # empty input in task number field if number == "\n" : messagebox.showerror("input error") return else : task_no = int(number) # function calling for deleting the # content of task number field clear_taskNumberField() # deleted specified task from the list tasks_list.pop(task_no - 1) # decremented counter -= 1 # whole content of text area widget is deleted TextArea.delete(1.0, END) # rewriting the task after deleting one task at a time for i in range(len(tasks_list)) : TextArea.insert('end -1 chars', "[ " + str(i + 1) + " ] " + tasks_list[i]) # Driver codeif __name__ == "__main__" : # create a GUI window gui = Tk() # set the background colour of GUI window gui.configure(background = "light green") # set the title of GUI window gui.title("ToDo App") # set the configuration of GUI window gui.geometry("250x300") # create a label : Enter Your Task enterTask = Label(gui, text = "Enter Your Task", bg = "light green") # create a text entry box # for typing the task enterTaskField = Entry(gui) # create a Submit Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed Submit = Button(gui, text = "Submit", fg = "Black", bg = "Red", command = insertTask) # create a text area for the root # with lunida 13 font # text area is for writing the content TextArea = Text(gui, height = 5, width = 25, font = "lucida 13") # create a label : Delete Task Number taskNumber = Label(gui, text = "Delete Task Number", bg = "blue") taskNumberField = Text(gui, height = 1, width = 2, font = "lucida 13") # create a Delete Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed . delete = Button(gui, text = "Delete", fg = "Black", bg = "Red", command = delete) # create a Exit Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed . Exit = Button(gui, text = "Exit", fg = "Black", bg = "Red", command = exit) # grid method is used for placing # the widgets at respective positions # in table like structure. enterTask.grid(row = 0, column = 2) # ipadx attributed set the entry box horizontal size enterTaskField.grid(row = 1, column = 2, ipadx = 50) Submit.grid(row = 2, column = 2) # padx attributed provide x-axis margin # from the root window to the widget. TextArea.grid(row = 3, column = 2, padx = 10, sticky = W) taskNumber.grid(row = 4, column = 2, pady = 5) taskNumberField.grid(row = 5, column = 2) # pady attributed provide y-axis # margin from the widget. delete.grid(row = 6, column = 2, pady = 5) Exit.grid(row = 7, column = 2) # start the GUI gui.mainloop() Output: abhigoya surinderdawra388 Python Tkinter-exercises Python-gui Python-tkinter Technical Scripter 2019 Project Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2021" }, { "code": null, "e": 69, "s": 28, "text": "Prerequisites : Introduction to tkinter " }, { "code": null, "e": 328, "s": 69, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. " }, { "code": null, "e": 351, "s": 328, "text": "To create a tkinter : " }, { "code": null, "e": 382, "s": 351, "text": "Importing the module – tkinter" }, { "code": null, "e": 417, "s": 382, "text": "Create the main window (container)" }, { "code": null, "e": 463, "s": 417, "text": "Add any number of widgets to the main window." }, { "code": null, "e": 503, "s": 463, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 534, "s": 503, "text": "The GUI would look like below:" }, { "code": null, "e": 626, "s": 534, "text": "Let’s create a GUI based simple ToDo application in which you can add and delete the Task. " }, { "code": null, "e": 657, "s": 626, "text": "Below is the implementation : " }, { "code": null, "e": 665, "s": 657, "text": "Python3" }, { "code": "# import all functions from the tkinter from tkinter import * # import messagebox class from tkinterfrom tkinter import messagebox # global list is declare for storing all the tasktasks_list = [] # global variable is declare for counting the taskcounter = 1 # Function for checking input error when# empty input is given in task fielddef inputError() : # check for enter task field is empty or not if enterTaskField.get() == \"\" : # show the error message messagebox.showerror(\"Input Error\") return 0 return 1 # Function for clearing the contents# of task number text fielddef clear_taskNumberField() : # clear the content of task number text field taskNumberField.delete(0.0, END) # Function for clearing the contents# of task entry field def clear_taskField() : # clear the content of task field entry box enterTaskField.delete(0, END) # Function for inserting the contents# from the task entry field to the text areadef insertTask(): global counter # check for error value = inputError() # if error occur then return if value == 0 : return # get the task string concatenating # with new line character content = enterTaskField.get() + \"\\n\" # store task in the list tasks_list.append(content) # insert content of task entry field to the text area # add task one by one in below one by one TextArea.insert('end -1 chars', \"[ \" + str(counter) + \" ] \" + content) # incremented counter += 1 # function calling for deleting the content of task field clear_taskField() # function for deleting the specified taskdef delete() : global counter # handling the empty task error if len(tasks_list) == 0 : messagebox.showerror(\"No task\") return # get the task number, which is required to delete number = taskNumberField.get(1.0, END) # checking for input error when # empty input in task number field if number == \"\\n\" : messagebox.showerror(\"input error\") return else : task_no = int(number) # function calling for deleting the # content of task number field clear_taskNumberField() # deleted specified task from the list tasks_list.pop(task_no - 1) # decremented counter -= 1 # whole content of text area widget is deleted TextArea.delete(1.0, END) # rewriting the task after deleting one task at a time for i in range(len(tasks_list)) : TextArea.insert('end -1 chars', \"[ \" + str(i + 1) + \" ] \" + tasks_list[i]) # Driver codeif __name__ == \"__main__\" : # create a GUI window gui = Tk() # set the background colour of GUI window gui.configure(background = \"light green\") # set the title of GUI window gui.title(\"ToDo App\") # set the configuration of GUI window gui.geometry(\"250x300\") # create a label : Enter Your Task enterTask = Label(gui, text = \"Enter Your Task\", bg = \"light green\") # create a text entry box # for typing the task enterTaskField = Entry(gui) # create a Submit Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed Submit = Button(gui, text = \"Submit\", fg = \"Black\", bg = \"Red\", command = insertTask) # create a text area for the root # with lunida 13 font # text area is for writing the content TextArea = Text(gui, height = 5, width = 25, font = \"lucida 13\") # create a label : Delete Task Number taskNumber = Label(gui, text = \"Delete Task Number\", bg = \"blue\") taskNumberField = Text(gui, height = 1, width = 2, font = \"lucida 13\") # create a Delete Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed . delete = Button(gui, text = \"Delete\", fg = \"Black\", bg = \"Red\", command = delete) # create a Exit Button and place into the root window # when user press the button, the command or # function affiliated to that button is executed . Exit = Button(gui, text = \"Exit\", fg = \"Black\", bg = \"Red\", command = exit) # grid method is used for placing # the widgets at respective positions # in table like structure. enterTask.grid(row = 0, column = 2) # ipadx attributed set the entry box horizontal size enterTaskField.grid(row = 1, column = 2, ipadx = 50) Submit.grid(row = 2, column = 2) # padx attributed provide x-axis margin # from the root window to the widget. TextArea.grid(row = 3, column = 2, padx = 10, sticky = W) taskNumber.grid(row = 4, column = 2, pady = 5) taskNumberField.grid(row = 5, column = 2) # pady attributed provide y-axis # margin from the widget. delete.grid(row = 6, column = 2, pady = 5) Exit.grid(row = 7, column = 2) # start the GUI gui.mainloop()", "e": 5729, "s": 665, "text": null }, { "code": null, "e": 5738, "s": 5729, "text": "Output: " }, { "code": null, "e": 5747, "s": 5738, "text": "abhigoya" }, { "code": null, "e": 5764, "s": 5747, "text": "surinderdawra388" }, { "code": null, "e": 5789, "s": 5764, "text": "Python Tkinter-exercises" }, { "code": null, "e": 5800, "s": 5789, "text": "Python-gui" }, { "code": null, "e": 5815, "s": 5800, "text": "Python-tkinter" }, { "code": null, "e": 5839, "s": 5815, "text": "Technical Scripter 2019" }, { "code": null, "e": 5847, "s": 5839, "text": "Project" }, { "code": null, "e": 5854, "s": 5847, "text": "Python" }, { "code": null, "e": 5873, "s": 5854, "text": "Technical Scripter" } ]
LISP - Loops
There may be a situation, when you need to execute a block of code numbers of times. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages. LISP provides the following types of constructs to handle looping requirements. Click the following links to check their detail. The loop construct is the simplest form of iteration provided by LISP. In its simplest form, it allows you to execute some statement(s) repeatedly until it finds a return statement. The loop for construct allows you to implement a for-loop like iteration as most common in other languages. The do construct is also used for performing iteration using LISP. It provides a structured form of iteration. The dotimes construct allows looping for some fixed number of iterations. The dolist construct allows iteration through each element of a list. The block and return-from allows you to exit gracefully from any nested blocks in case of any error. The block function allows you to create a named block with a body composed of zero or more statements. Syntax is − (block block-name( ... ... )) The return-from function takes a block name and an optional (the default is nil) return value. The following example demonstrates this − Create a new source code file named main.lisp and type the following code in it − (defun demo-function (flag) (print 'entering-outer-block) (block outer-block (print 'entering-inner-block) (print (block inner-block (if flag (return-from outer-block 3) (return-from inner-block 5) ) (print 'This-wil--not-be-printed)) ) (print 'left-inner-block) (print 'leaving-outer-block) t) ) (demo-function t) (terpri) (demo-function nil) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − ENTERING-OUTER-BLOCK ENTERING-INNER-BLOCK ENTERING-OUTER-BLOCK ENTERING-INNER-BLOCK 5 LEFT-INNER-BLOCK LEAVING-OUTER-BLOCK 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2060, "text": "There may be a situation, when you need to execute a block of code numbers of times. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages." }, { "code": null, "e": 2454, "s": 2325, "text": "LISP provides the following types of constructs to handle looping requirements. Click the following links to check their detail." }, { "code": null, "e": 2636, "s": 2454, "text": "The loop construct is the simplest form of iteration provided by LISP. In its simplest form, it allows you to execute some statement(s) repeatedly until it finds a return statement." }, { "code": null, "e": 2744, "s": 2636, "text": "The loop for construct allows you to implement a for-loop like iteration as most common in other languages." }, { "code": null, "e": 2855, "s": 2744, "text": "The do construct is also used for performing iteration using LISP. It provides a structured form of iteration." }, { "code": null, "e": 2929, "s": 2855, "text": "The dotimes construct allows looping for some fixed number of iterations." }, { "code": null, "e": 2999, "s": 2929, "text": "The dolist construct allows iteration through each element of a list." }, { "code": null, "e": 3100, "s": 2999, "text": "The block and return-from allows you to exit gracefully from any nested blocks in case of any error." }, { "code": null, "e": 3215, "s": 3100, "text": "The block function allows you to create a named block with a body composed of zero or more statements. Syntax is −" }, { "code": null, "e": 3246, "s": 3215, "text": "(block block-name(\n...\n...\n))\n" }, { "code": null, "e": 3341, "s": 3246, "text": "The return-from function takes a block name and an optional (the default is nil) return value." }, { "code": null, "e": 3383, "s": 3341, "text": "The following example demonstrates this −" }, { "code": null, "e": 3465, "s": 3383, "text": "Create a new source code file named main.lisp and type the following code in it −" }, { "code": null, "e": 3906, "s": 3465, "text": "(defun demo-function (flag)\n (print 'entering-outer-block)\n \n (block outer-block\n (print 'entering-inner-block)\n (print (block inner-block\n\n (if flag\n (return-from outer-block 3)\n (return-from inner-block 5)\n )\n\n (print 'This-wil--not-be-printed))\n )\n\n (print 'left-inner-block)\n (print 'leaving-outer-block)\n t)\n)\n(demo-function t)\n(terpri)\n(demo-function nil)" }, { "code": null, "e": 4015, "s": 3906, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 4146, "s": 4015, "text": "ENTERING-OUTER-BLOCK \nENTERING-INNER-BLOCK \n\nENTERING-OUTER-BLOCK \nENTERING-INNER-BLOCK \n5 \nLEFT-INNER-BLOCK \nLEAVING-OUTER-BLOCK\n" }, { "code": null, "e": 4179, "s": 4146, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 4194, "s": 4179, "text": " Arnold Higuit" }, { "code": null, "e": 4201, "s": 4194, "text": " Print" }, { "code": null, "e": 4212, "s": 4201, "text": " Add Notes" } ]
Need help in deleting duplicate columns from a table in MySQL?
To delete duplicate columns, use DELETE with INNER JOIN. Following is the syntax − delete tbl1 from yourTableName anyAliasName1 inner join yourTableName anyAliasName2 where yourCondition1 and yourCondition2 Let us create a table − mysql> create table demo14 −> ( −> id int not null auto_increment primary key, −> name varchar(30) −> ); Query OK, 0 rows affected (1.89 sec) Insert some records into the table with the help of insert command − mysql> insert into demo14(name) values('John'); Query OK, 1 row affected (0.14 sec) mysql> insert into demo14(name) values('David'); Query OK, 1 row affected (0.18 sec) mysql> insert into demo14(name) values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into demo14(name) values('Bob'); Query OK, 1 row affected (0.15 sec) mysql> insert into demo14(name) values('John'); Query OK, 1 row affected (0.45 sec) mysql> insert into demo14(name) values('Carol'); Query OK, 1 row affected (0.16 sec) Display records from the table using select statement − mysql> select *from demo14; This will produce the following output − +----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | David | | 3 | David | | 4 | Bob | | 5 | John | | 6 | Carol | +----+-------+ 6 rows in set (0.00 sec) Following is the query to delete duplicate columns from the table − mysql> delete tbl1 from demo14 tbl1 −> inner join demo14 tbl2 −> where −> tbl1.id < tbl2.id and −> tbl1.name = tbl2.name −> ; Query OK, 2 rows affected (0.20 sec) Display records from the table using select statement − mysql> select *from demo14; This will produce the following output − +----+-------+ | id | name | +----+-------+ | 3 | David | | 4 | Bob | | 5 | John | | 6 | Carol | +----+-------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1145, "s": 1062, "text": "To delete duplicate columns, use DELETE with INNER JOIN. Following is the syntax −" }, { "code": null, "e": 1269, "s": 1145, "text": "delete tbl1 from yourTableName anyAliasName1\ninner join yourTableName anyAliasName2\nwhere\nyourCondition1\nand\nyourCondition2" }, { "code": null, "e": 1293, "s": 1269, "text": "Let us create a table −" }, { "code": null, "e": 1435, "s": 1293, "text": "mysql> create table demo14\n−> (\n−> id int not null auto_increment primary key,\n−> name varchar(30)\n−> );\nQuery OK, 0 rows affected (1.89 sec)" }, { "code": null, "e": 1504, "s": 1435, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 2015, "s": 1504, "text": "mysql> insert into demo14(name) values('John');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into demo14(name) values('David');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into demo14(name) values('David');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into demo14(name) values('Bob');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into demo14(name) values('John');\nQuery OK, 1 row affected (0.45 sec)\n\nmysql> insert into demo14(name) values('Carol');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2071, "s": 2015, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2099, "s": 2071, "text": "mysql> select *from demo14;" }, { "code": null, "e": 2140, "s": 2099, "text": "This will produce the following output −" }, { "code": null, "e": 2315, "s": 2140, "text": "+----+-------+\n| id | name |\n+----+-------+\n| 1 | John |\n| 2 | David |\n| 3 | David |\n| 4 | Bob |\n| 5 | John |\n| 6 | Carol |\n+----+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2383, "s": 2315, "text": "Following is the query to delete duplicate columns from the table −" }, { "code": null, "e": 2546, "s": 2383, "text": "mysql> delete tbl1 from demo14 tbl1\n−> inner join demo14 tbl2\n−> where\n−> tbl1.id < tbl2.id and\n−> tbl1.name = tbl2.name\n−> ;\nQuery OK, 2 rows affected (0.20 sec)" }, { "code": null, "e": 2602, "s": 2546, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2630, "s": 2602, "text": "mysql> select *from demo14;" }, { "code": null, "e": 2671, "s": 2630, "text": "This will produce the following output −" }, { "code": null, "e": 2816, "s": 2671, "text": "+----+-------+\n| id | name |\n+----+-------+\n| 3 | David |\n| 4 | Bob |\n| 5 | John |\n| 6 | Carol |\n+----+-------+\n4 rows in set (0.00 sec)" } ]
Simple Customer Segmentation Using RFM Analysis | by Chi Nguyen | Towards Data Science
RFM analysis is a customer behavior segmentation technique. Based on customers’ historical transactions, RFM analysis focuses on 3 main aspects of customers’ transactions: recency, frequency and purchase amount. Understanding these behaviors will allow businesses to cluster different customers into groups. Here is the dataset of a store whose customers are coming from all over the world. It includes information such as invoice number, invoice date, customer id, stock code, description of the product, purchased quantity and country where the customer lives. In this article, I will only show you my method of doing the RFM analysis, and not my steps in cleaning the dataset. Figure 1 & 2 below are the results of my dataset after being edited and transformed. Firstly, I will clarify the definition of RFM in my analysis. Recency (R): How recently customers have made their purchases. Frequency (F): How often customers have made their purchases. Monetary (M): How much money customers have paid for their purchases. Next, I will calculate these 3 components for each of the customers. Recency (R) import datetime###Calculate total_amount of money for each orderdf5.InvoiceDate = pd.to_datetime(df5.InvoiceDate)df5['amount'] = df5.Quantity*df5.UnitPricedf6=df5.copy()###Taking a reference date to calculate the gap between this reference date and the last purchase date of each customer.The gap can be referred as the recency of each customerreference_date = df6.InvoiceDate.max() + datetime.timedelta(days = 1)df6['days_from_last_purchase'] = (reference_date - df6.InvoiceDate).astype('timedelta64[D]')lastpurchase_day = df6[['CustomerID','days_from_last_purchase']].groupby('CustomerID').min().reset_index()lastpurchase_day.rename(columns={'days_from_last_purchase':'recency'}, inplace=True) After calculating number of days since the last purchase of each customer, I have an output as below: Frequency (F) ###Calculate number of orders purchased by each customerfreq = df6[['CustomerID','InvoiceNo']].groupby(['CustomerID','InvoiceNo']).count().reset_index().\groupby(["CustomerID"]).count().reset_index()freq.rename(columns = {'InvoiceNo':'frequency'}, inplace = True) The result of customers’ frequency is as the following: Monetary (M) ###Total amount of money spent per customermoney = df6[['CustomerID','amount']].groupby('CustomerID').sum().reset_index()money.rename(columns = {'amount':'monetary'}, inplace = True) Output: Eventually, when I combine these 3 indicators, here is the RFM information for each customer. RFM Score After having RFM information for each customer, I will give each buyer a RFM score based on her/his RFM data. The benchmark for my scoring will depend on the percentile of each indicator. In details, you can see the code below for more reference: ###Calculating quantile valuesquintiles = rfm[['recency', 'frequency', 'monetary']].quantile([.2, .25, .3, .35, .4, .5, .6, .7, .8, .9]).to_dict()###Benchmark to give score for recency indicatordef r_score(r): if r < quintiles['recency'][.2]: return 3 elif r < quintiles['recency'][.8]: return 2 else: return 1###Benchmark to give score for frequency & monetary indicator. def fm_score(f): if f > quintiles['frequency'][.8]: return 3 elif f > quintiles['frequency'][.2]: return 2 else: return 1 Applying this rule to the data frame: rfm2 = rfm.copy()rfm2['r_score'] = rfm2.recency.apply(lambda x: r_score(x))rfm2['f_score'] = rfm2.frequency.apply(lambda x: fm_score(x))rfm2['m_score'] = rfm2.monetary.apply(lambda x: fm_score(x))rfm2['rfm'] = rfm2['r_score'].map(str)+rfm2['f_score'].map(str) + rfm2['m_score'].map(str) Each customer now has a RFM score: Now, this is my favorite step as I can divide the group in whichever way I want. However, it is important to consider your business situations when categorizing customers. Different business purposes will generate different types of grouping and in turn different strategies. In this section, I will divide my customers into 7 groups, each of which is labeled as below: ###Loyal Customers, who are the champions of all the customers with highest score of RFM. rfm2_group1 = rfm2[rfm2['rfm']=='333']rfm2_group1['label'] = 'champion'###Customers who have the most potential to become the Champions. They recently buy the products and they make their purchases quite frequently. Moreover, the amount they spent is quite great. rfm2_group2 = rfm2[rfm2['rfm'].str.contains('332|331|323|313')] rfm2_group2['label'] = 'potential1'###Customers whose frequency score and monetary score are slightly lower than potential 1 grouprfm2_group3 = rfm2[rfm2['rfm'].str.contains('321|322|311|312')] rfm2_group3['label'] = 'potential2'###Customers who used to pay a lot of money and come to the store frequently. They did not purchase recently. rfm2_group4 = rfm2[rfm2['rfm'].str.contains('233')]rfm2_group4['label'] = 'needing_attention1'###Customers who do not come to store often and not frequently make purchases.rfm2_group5 = rfm2[rfm2['rfm'].str.contains('223|213|212|231|232|211|221|222')]rfm2_group5['label'] = 'needing_attention2'###Customers who haven't paid a visit to the store for a long time. However, once in a while, they do spend lot of moneyrfm2_group6 = rfm2[rfm2['rfm'].str.contains('132|123|113|133')]rfm2_group6['label'] = 'lost1'###Customers who churnrfm2_group7 = rfm2[rfm2['rfm'].str.contains('111|112|121|122|131')]rfm2_group7['label'] = 'lost2' Above is a simple analysis of RFM. However, RFM may be a lot more meaningful when combined with other deep dive analysis. I hope that this article may be a helpful source of reference for your future work.
[ { "code": null, "e": 479, "s": 171, "text": "RFM analysis is a customer behavior segmentation technique. Based on customers’ historical transactions, RFM analysis focuses on 3 main aspects of customers’ transactions: recency, frequency and purchase amount. Understanding these behaviors will allow businesses to cluster different customers into groups." }, { "code": null, "e": 936, "s": 479, "text": "Here is the dataset of a store whose customers are coming from all over the world. It includes information such as invoice number, invoice date, customer id, stock code, description of the product, purchased quantity and country where the customer lives. In this article, I will only show you my method of doing the RFM analysis, and not my steps in cleaning the dataset. Figure 1 & 2 below are the results of my dataset after being edited and transformed." }, { "code": null, "e": 998, "s": 936, "text": "Firstly, I will clarify the definition of RFM in my analysis." }, { "code": null, "e": 1061, "s": 998, "text": "Recency (R): How recently customers have made their purchases." }, { "code": null, "e": 1123, "s": 1061, "text": "Frequency (F): How often customers have made their purchases." }, { "code": null, "e": 1193, "s": 1123, "text": "Monetary (M): How much money customers have paid for their purchases." }, { "code": null, "e": 1262, "s": 1193, "text": "Next, I will calculate these 3 components for each of the customers." }, { "code": null, "e": 1274, "s": 1262, "text": "Recency (R)" }, { "code": null, "e": 1970, "s": 1274, "text": "import datetime###Calculate total_amount of money for each orderdf5.InvoiceDate = pd.to_datetime(df5.InvoiceDate)df5['amount'] = df5.Quantity*df5.UnitPricedf6=df5.copy()###Taking a reference date to calculate the gap between this reference date and the last purchase date of each customer.The gap can be referred as the recency of each customerreference_date = df6.InvoiceDate.max() + datetime.timedelta(days = 1)df6['days_from_last_purchase'] = (reference_date - df6.InvoiceDate).astype('timedelta64[D]')lastpurchase_day = df6[['CustomerID','days_from_last_purchase']].groupby('CustomerID').min().reset_index()lastpurchase_day.rename(columns={'days_from_last_purchase':'recency'}, inplace=True)" }, { "code": null, "e": 2072, "s": 1970, "text": "After calculating number of days since the last purchase of each customer, I have an output as below:" }, { "code": null, "e": 2086, "s": 2072, "text": "Frequency (F)" }, { "code": null, "e": 2351, "s": 2086, "text": "###Calculate number of orders purchased by each customerfreq = df6[['CustomerID','InvoiceNo']].groupby(['CustomerID','InvoiceNo']).count().reset_index().\\groupby([\"CustomerID\"]).count().reset_index()freq.rename(columns = {'InvoiceNo':'frequency'}, inplace = True) " }, { "code": null, "e": 2407, "s": 2351, "text": "The result of customers’ frequency is as the following:" }, { "code": null, "e": 2420, "s": 2407, "text": "Monetary (M)" }, { "code": null, "e": 2604, "s": 2420, "text": "###Total amount of money spent per customermoney = df6[['CustomerID','amount']].groupby('CustomerID').sum().reset_index()money.rename(columns = {'amount':'monetary'}, inplace = True) " }, { "code": null, "e": 2612, "s": 2604, "text": "Output:" }, { "code": null, "e": 2706, "s": 2612, "text": "Eventually, when I combine these 3 indicators, here is the RFM information for each customer." }, { "code": null, "e": 2716, "s": 2706, "text": "RFM Score" }, { "code": null, "e": 2963, "s": 2716, "text": "After having RFM information for each customer, I will give each buyer a RFM score based on her/his RFM data. The benchmark for my scoring will depend on the percentile of each indicator. In details, you can see the code below for more reference:" }, { "code": null, "e": 3525, "s": 2963, "text": "###Calculating quantile valuesquintiles = rfm[['recency', 'frequency', 'monetary']].quantile([.2, .25, .3, .35, .4, .5, .6, .7, .8, .9]).to_dict()###Benchmark to give score for recency indicatordef r_score(r): if r < quintiles['recency'][.2]: return 3 elif r < quintiles['recency'][.8]: return 2 else: return 1###Benchmark to give score for frequency & monetary indicator. def fm_score(f): if f > quintiles['frequency'][.8]: return 3 elif f > quintiles['frequency'][.2]: return 2 else: return 1" }, { "code": null, "e": 3563, "s": 3525, "text": "Applying this rule to the data frame:" }, { "code": null, "e": 3850, "s": 3563, "text": "rfm2 = rfm.copy()rfm2['r_score'] = rfm2.recency.apply(lambda x: r_score(x))rfm2['f_score'] = rfm2.frequency.apply(lambda x: fm_score(x))rfm2['m_score'] = rfm2.monetary.apply(lambda x: fm_score(x))rfm2['rfm'] = rfm2['r_score'].map(str)+rfm2['f_score'].map(str) + rfm2['m_score'].map(str)" }, { "code": null, "e": 3885, "s": 3850, "text": "Each customer now has a RFM score:" }, { "code": null, "e": 4161, "s": 3885, "text": "Now, this is my favorite step as I can divide the group in whichever way I want. However, it is important to consider your business situations when categorizing customers. Different business purposes will generate different types of grouping and in turn different strategies." }, { "code": null, "e": 4255, "s": 4161, "text": "In this section, I will divide my customers into 7 groups, each of which is labeled as below:" }, { "code": null, "e": 5639, "s": 4255, "text": "###Loyal Customers, who are the champions of all the customers with highest score of RFM. rfm2_group1 = rfm2[rfm2['rfm']=='333']rfm2_group1['label'] = 'champion'###Customers who have the most potential to become the Champions. They recently buy the products and they make their purchases quite frequently. Moreover, the amount they spent is quite great. rfm2_group2 = rfm2[rfm2['rfm'].str.contains('332|331|323|313')] rfm2_group2['label'] = 'potential1'###Customers whose frequency score and monetary score are slightly lower than potential 1 grouprfm2_group3 = rfm2[rfm2['rfm'].str.contains('321|322|311|312')] rfm2_group3['label'] = 'potential2'###Customers who used to pay a lot of money and come to the store frequently. They did not purchase recently. rfm2_group4 = rfm2[rfm2['rfm'].str.contains('233')]rfm2_group4['label'] = 'needing_attention1'###Customers who do not come to store often and not frequently make purchases.rfm2_group5 = rfm2[rfm2['rfm'].str.contains('223|213|212|231|232|211|221|222')]rfm2_group5['label'] = 'needing_attention2'###Customers who haven't paid a visit to the store for a long time. However, once in a while, they do spend lot of moneyrfm2_group6 = rfm2[rfm2['rfm'].str.contains('132|123|113|133')]rfm2_group6['label'] = 'lost1'###Customers who churnrfm2_group7 = rfm2[rfm2['rfm'].str.contains('111|112|121|122|131')]rfm2_group7['label'] = 'lost2'" } ]
How to display hidden element when a user starts typing using JavaScript ? - GeeksforGeeks
17 Sep, 2019 Method 1: Using the oninput attribute to input element: The oninput attribute is fired whenever user starts typing to the input element. This can be used to detect changes in a <input> or <textarea> element. A function is called with the value of this attribute. This function selects the hidden element and changes its display property to ‘block’. This unhides the element, provided that the element is hidden by using ‘none’ display property. Other methods of showing the element can be used in this function. Therefore whenever the user starts typing in the input box, the function is triggered and the hidden element is shown. Syntax: <input oninput="showElem()"></input>function showElem() { document.querySelector('.box').style.display = "block";} Example: <!DOCTYPE html><html> <head> <title> How to display hidden element when a user starts typing using JavaScript ? </title> <style> .box { height: 50px; width: 300px; background-color: lightgreen; /* hide the element by default */ display: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript code to show hidden element when a user starts typing </b> <p> Start typing in the input box below to unhide the message </p> <input oninput="showElem()"></input> <div class="box"> You have started typing in the input box </div> <script type="text/javascript"> function showElem() { document.querySelector('.box').style.display = "block"; } </script></body> </html> Output: Before Typing: After Typing: Method 2: Adding an event listener to the input box: The addEventListener() method is used for adding an event handler to any element. Whenever the specified event occurs to the target element, the function specified is executed. The input event is used with this method. This event fires whenever a change is detected in a <input> or <textarea> element. The input where the user would type is first selected and stored. The addEventListener() method is then called on this input box. A new function is then created inside the method. This function selects the hidden element and changes its display property to ‘block’. This unhides the element, provided that the element is hidden by ‘none’ display property. Other methods of showing the element can be used in this function. Therefore whenever the user starts typing in the input box, the function is triggered and the hidden element is shown. Syntax: let inputBox = document.querySelector('.inputBox') inputBox.addEventListener('input', function() { document.querySelector('.box').style.display = "block";}); Example: <!DOCTYPE html><html> <head> <title> How to display hidden element when a user starts typing using JavaScript ? </title> <style> .box { height: 50px; width: 300px; background-color: lightgreen; /* hide the element by default */ display: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript code to show hidden element when a user starts typing </b> <p> Start typing in the input box below to unhide the message </p> <input class="inputBox"></input> <div class="box"> You have started typing in the input box </div> <script type="text/javascript"> let inputBox = document.querySelector('.inputBox') inputBox.addEventListener('input', function() { document.querySelector('.box').style.display = "block"; }); </script></body> </html> Output: Before Typing: After Typing: Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Set the value of an input field in JavaScript Differences between Functional Components and Class Components in React Form validation using HTML and JavaScript Difference between var, let and const keywords in JavaScript Express.js express.Router() Function Installation of Node.js on Linux Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24763, "s": 24735, "text": "\n17 Sep, 2019" }, { "code": null, "e": 25026, "s": 24763, "text": "Method 1: Using the oninput attribute to input element: The oninput attribute is fired whenever user starts typing to the input element. This can be used to detect changes in a <input> or <textarea> element. A function is called with the value of this attribute." }, { "code": null, "e": 25275, "s": 25026, "text": "This function selects the hidden element and changes its display property to ‘block’. This unhides the element, provided that the element is hidden by using ‘none’ display property. Other methods of showing the element can be used in this function." }, { "code": null, "e": 25394, "s": 25275, "text": "Therefore whenever the user starts typing in the input box, the function is triggered and the hidden element is shown." }, { "code": null, "e": 25402, "s": 25394, "text": "Syntax:" }, { "code": "<input oninput=\"showElem()\"></input>function showElem() { document.querySelector('.box').style.display = \"block\";}", "e": 25520, "s": 25402, "text": null }, { "code": null, "e": 25529, "s": 25520, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to display hidden element when a user starts typing using JavaScript ? </title> <style> .box { height: 50px; width: 300px; background-color: lightgreen; /* hide the element by default */ display: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript code to show hidden element when a user starts typing </b> <p> Start typing in the input box below to unhide the message </p> <input oninput=\"showElem()\"></input> <div class=\"box\"> You have started typing in the input box </div> <script type=\"text/javascript\"> function showElem() { document.querySelector('.box').style.display = \"block\"; } </script></body> </html>", "e": 26490, "s": 25529, "text": null }, { "code": null, "e": 26498, "s": 26490, "text": "Output:" }, { "code": null, "e": 26513, "s": 26498, "text": "Before Typing:" }, { "code": null, "e": 26527, "s": 26513, "text": "After Typing:" }, { "code": null, "e": 26757, "s": 26527, "text": "Method 2: Adding an event listener to the input box: The addEventListener() method is used for adding an event handler to any element. Whenever the specified event occurs to the target element, the function specified is executed." }, { "code": null, "e": 26882, "s": 26757, "text": "The input event is used with this method. This event fires whenever a change is detected in a <input> or <textarea> element." }, { "code": null, "e": 27062, "s": 26882, "text": "The input where the user would type is first selected and stored. The addEventListener() method is then called on this input box. A new function is then created inside the method." }, { "code": null, "e": 27305, "s": 27062, "text": "This function selects the hidden element and changes its display property to ‘block’. This unhides the element, provided that the element is hidden by ‘none’ display property. Other methods of showing the element can be used in this function." }, { "code": null, "e": 27424, "s": 27305, "text": "Therefore whenever the user starts typing in the input box, the function is triggered and the hidden element is shown." }, { "code": null, "e": 27432, "s": 27424, "text": "Syntax:" }, { "code": "let inputBox = document.querySelector('.inputBox') inputBox.addEventListener('input', function() { document.querySelector('.box').style.display = \"block\";});", "e": 27594, "s": 27432, "text": null }, { "code": null, "e": 27603, "s": 27594, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to display hidden element when a user starts typing using JavaScript ? </title> <style> .box { height: 50px; width: 300px; background-color: lightgreen; /* hide the element by default */ display: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript code to show hidden element when a user starts typing </b> <p> Start typing in the input box below to unhide the message </p> <input class=\"inputBox\"></input> <div class=\"box\"> You have started typing in the input box </div> <script type=\"text/javascript\"> let inputBox = document.querySelector('.inputBox') inputBox.addEventListener('input', function() { document.querySelector('.box').style.display = \"block\"; }); </script></body> </html>", "e": 28652, "s": 27603, "text": null }, { "code": null, "e": 28660, "s": 28652, "text": "Output:" }, { "code": null, "e": 28675, "s": 28660, "text": "Before Typing:" }, { "code": null, "e": 28689, "s": 28675, "text": "After Typing:" }, { "code": null, "e": 28696, "s": 28689, "text": "Picked" }, { "code": null, "e": 28707, "s": 28696, "text": "JavaScript" }, { "code": null, "e": 28724, "s": 28707, "text": "Web Technologies" }, { "code": null, "e": 28751, "s": 28724, "text": "Web technologies Questions" }, { "code": null, "e": 28849, "s": 28751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28858, "s": 28849, "text": "Comments" }, { "code": null, "e": 28871, "s": 28858, "text": "Old Comments" }, { "code": null, "e": 28916, "s": 28871, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28962, "s": 28916, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 29034, "s": 28962, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29076, "s": 29034, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 29137, "s": 29076, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29174, "s": 29137, "text": "Express.js express.Router() Function" }, { "code": null, "e": 29207, "s": 29174, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29279, "s": 29207, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29337, "s": 29279, "text": "How to create footer to stay at the bottom of a Web page?" } ]
CSS | Web Fonts - GeeksforGeeks
21 Feb, 2019 Web fonts are used to allow the use of fonts in CSS, which are not installed on the local system. After choosing the not installed font, just include the font file on the web server and it will be automatically downloaded when needed. Syntax: @font-face { font details } Types of Font Formats: There are many types of font formats which are listed below: TrueType Fonts (TTF): Whether one uses Microsoft Operating Systems or Mac Operating System, the most commonly used font format is TrueType. This is a font standard developed by Microsoft and Apple in the late 1980’s. TrueType fonts describe each glyph as a set of paths. A path means a closed curve specified using points and particular mathematics. For Example, a lower case ‘i’ has two paths, one for the dot and one for the rest of it. Pixels are used to fill the path to create the final letter form. The advantage of TrueType font format is that the glyphs are scalable, meaning that it can be set to any scale and at any point size. OpenType Fonts (OTF): OpenType is a font format that was built on TrueType. The OpenType font format was developed by Microsoft and Adobe, but is a registered trademark of Microsoft. Layout features within OpenType fonts are organized by scripts and languages, which allows a single font to support multiple writing systems, within the same script. The OpenType font format addresses the goals of better protection for font data, broader multi-platform support to name a few. The Web Open Font Format (WOFF): WOFF is a font format is used in web pages developed in 2009 by Mozilla in concert with Type Supply, LettError, and other organizations. WOFF is basically an OpenType or TrueType with compression and additional metadata. The goal of WOFF to support font distribution from a server to a client over a network with bandwidth constraints. There are two versions of WOFF, which are WOFF and WOFF2, they mostly differ in regard to the compression algorithm used. They are described by the ‘woff’ and ‘woff2’ format descriptor respectively. SVG Fonts/Shapes: SVG stands for Scalable Vector Graphics. When SVG was first specified most of the web browsers did not fully support web fonts. But in order to render text correctly, a font description technology had later been added to SVG to provide this ability. It provide the means of embedding glyph information into SVG when rendered. Embedded OpenType Fonts (EOT): The Embedded OpenType File Format was developed by Microsoft. EOT fonts are a compact form of OpenType fonts to use as embedded fonts on web pages. It was designed with the purpose of enabling TrueType and OpenType fonts to be linked to web pages for download to render the web page with the font as required by the user. Font Descriptors: Descriptors can be defined inside the @font-face rule. We shall now explain the different types of font descriptors. font-family: It is used to define the name of font. It is required for web fonts to function. src: It is used to define the URL from which we get the font. Like font-family the src is also required. Except these two fields the rest of the descriptors are optional. font-stretch: It is used to find, how font should be stretched. Normal is the value taken by default. The different font stretch values are normal, condensed, semi-condensed, ultra-condensed, extra-condensed, expanded, semi-expanded, extra-expanded and lastly ultra-expanded. font-style: It is used to define the font different styles. The different styles that can be set are oblique and the default style is normal. font-weight: The weight of the font can be defined using this descriptor. Default value of font-weight is “normal”. The different values for the boldness are normal, bold, and we can also give numerical values ranging from 100-900 in increments of 100. Example 1: This example illustrates the use of web-fonts. <!DOCTYPE html><html> <head> <style> @font-face{ font-family: monospace; src:url(sansation_light.woff); } /* Sets font family to monospace */ * { font-family: monospace; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p>A computer science portal for geeks.</p> </div> <h1>Great Geek's font face example.</h1></body> </html> Output: Example 2: This example illustrates the use of web-fonts. <!DOCTYPE html><html> <head> <style> @font-face{ /* Set font family to monospace */ font-family:monospace; src:url(sansation_light.woff); } * { font-family:monospace; /** font style to italic */ font-style:italic; font-weight:bold; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p>A computer science portal for geeks.</p> </div> <h1>Great Geek's font face example.</h1></body> </html> Output: CSS-Basics Picked 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 create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form 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 Convert a string to an integer in JavaScript
[ { "code": null, "e": 28072, "s": 28044, "text": "\n21 Feb, 2019" }, { "code": null, "e": 28307, "s": 28072, "text": "Web fonts are used to allow the use of fonts in CSS, which are not installed on the local system. After choosing the not installed font, just include the font file on the web server and it will be automatically downloaded when needed." }, { "code": null, "e": 28315, "s": 28307, "text": "Syntax:" }, { "code": null, "e": 28348, "s": 28315, "text": "@font-face {\n font details\n}\n" }, { "code": null, "e": 28432, "s": 28348, "text": "Types of Font Formats: There are many types of font formats which are listed below:" }, { "code": null, "e": 29071, "s": 28432, "text": "TrueType Fonts (TTF): Whether one uses Microsoft Operating Systems or Mac Operating System, the most commonly used font format is TrueType. This is a font standard developed by Microsoft and Apple in the late 1980’s. TrueType fonts describe each glyph as a set of paths. A path means a closed curve specified using points and particular mathematics. For Example, a lower case ‘i’ has two paths, one for the dot and one for the rest of it. Pixels are used to fill the path to create the final letter form. The advantage of TrueType font format is that the glyphs are scalable, meaning that it can be set to any scale and at any point size." }, { "code": null, "e": 29547, "s": 29071, "text": "OpenType Fonts (OTF): OpenType is a font format that was built on TrueType. The OpenType font format was developed by Microsoft and Adobe, but is a registered trademark of Microsoft. Layout features within OpenType fonts are organized by scripts and languages, which allows a single font to support multiple writing systems, within the same script. The OpenType font format addresses the goals of better protection for font data, broader multi-platform support to name a few." }, { "code": null, "e": 30115, "s": 29547, "text": "The Web Open Font Format (WOFF): WOFF is a font format is used in web pages developed in 2009 by Mozilla in concert with Type Supply, LettError, and other organizations. WOFF is basically an OpenType or TrueType with compression and additional metadata. The goal of WOFF to support font distribution from a server to a client over a network with bandwidth constraints. There are two versions of WOFF, which are WOFF and WOFF2, they mostly differ in regard to the compression algorithm used. They are described by the ‘woff’ and ‘woff2’ format descriptor respectively." }, { "code": null, "e": 30459, "s": 30115, "text": "SVG Fonts/Shapes: SVG stands for Scalable Vector Graphics. When SVG was first specified most of the web browsers did not fully support web fonts. But in order to render text correctly, a font description technology had later been added to SVG to provide this ability. It provide the means of embedding glyph information into SVG when rendered." }, { "code": null, "e": 30812, "s": 30459, "text": "Embedded OpenType Fonts (EOT): The Embedded OpenType File Format was developed by Microsoft. EOT fonts are a compact form of OpenType fonts to use as embedded fonts on web pages. It was designed with the purpose of enabling TrueType and OpenType fonts to be linked to web pages for download to render the web page with the font as required by the user." }, { "code": null, "e": 30947, "s": 30812, "text": "Font Descriptors: Descriptors can be defined inside the @font-face rule. We shall now explain the different types of font descriptors." }, { "code": null, "e": 31041, "s": 30947, "text": "font-family: It is used to define the name of font. It is required for web fonts to function." }, { "code": null, "e": 31212, "s": 31041, "text": "src: It is used to define the URL from which we get the font. Like font-family the src is also required. Except these two fields the rest of the descriptors are optional." }, { "code": null, "e": 31488, "s": 31212, "text": "font-stretch: It is used to find, how font should be stretched. Normal is the value taken by default. The different font stretch values are normal, condensed, semi-condensed, ultra-condensed, extra-condensed, expanded, semi-expanded, extra-expanded and lastly ultra-expanded." }, { "code": null, "e": 31630, "s": 31488, "text": "font-style: It is used to define the font different styles. The different styles that can be set are oblique and the default style is normal." }, { "code": null, "e": 31883, "s": 31630, "text": "font-weight: The weight of the font can be defined using this descriptor. Default value of font-weight is “normal”. The different values for the boldness are normal, bold, and we can also give numerical values ranging from 100-900 in increments of 100." }, { "code": null, "e": 31941, "s": 31883, "text": "Example 1: This example illustrates the use of web-fonts." }, { "code": "<!DOCTYPE html><html> <head> <style> @font-face{ font-family: monospace; src:url(sansation_light.woff); } /* Sets font family to monospace */ * { font-family: monospace; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p>A computer science portal for geeks.</p> </div> <h1>Great Geek's font face example.</h1></body> </html> ", "e": 32421, "s": 31941, "text": null }, { "code": null, "e": 32429, "s": 32421, "text": "Output:" }, { "code": null, "e": 32487, "s": 32429, "text": "Example 2: This example illustrates the use of web-fonts." }, { "code": "<!DOCTYPE html><html> <head> <style> @font-face{ /* Set font family to monospace */ font-family:monospace; src:url(sansation_light.woff); } * { font-family:monospace; /** font style to italic */ font-style:italic; font-weight:bold; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p>A computer science portal for geeks.</p> </div> <h1>Great Geek's font face example.</h1></body> </html> ", "e": 33092, "s": 32487, "text": null }, { "code": null, "e": 33100, "s": 33092, "text": "Output:" }, { "code": null, "e": 33111, "s": 33100, "text": "CSS-Basics" }, { "code": null, "e": 33118, "s": 33111, "text": "Picked" }, { "code": null, "e": 33122, "s": 33118, "text": "CSS" }, { "code": null, "e": 33139, "s": 33122, "text": "Web Technologies" }, { "code": null, "e": 33237, "s": 33139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33299, "s": 33237, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33349, "s": 33299, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33407, "s": 33349, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 33455, "s": 33407, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33505, "s": 33455, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 33547, "s": 33505, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 33580, "s": 33547, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33623, "s": 33580, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33685, "s": 33623, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Private Variables in Python
In actual terms (practically), python doesn’t have anything called private member variable in Python. However, adding two underlines(__) at the beginning makes a variable or a method private is the convention used by most python code. Let’s understand this concept through an example − Live Demo class myClass: __privateVar = 27; def __privMeth(self): print("I'm inside class myClass") def hello(self): print("Private Variable value: ",myClass.__privateVar) foo = myClass() foo.hello() foo.__privateMeth In the above program, __privMeth is a private method and __privateVar is a private variable. Let’s see its output now − Private Variable value: 27 Traceback (most recent call last): File "C:/Python/Python361/privateVar1.py", line 12, in <module> foo.__privateMeth AttributeError: 'myClass' object has no attribute '__privateMeth' From the above output, we can see that outside the class “myClass”, you cannot access the private method as well as the private variable. However, inside the class (myClass) we can access the private variables. In the hello() method, the __privateVar variable can be accessed (as shown above: “Private Variable value: 27”). So from the above example, we can understand that all the variables and the methods inside the class are public by the method. When we declare data member as private it means they are accessible only side the class and are inaccessible outside the class. The technique of making a variable or method private is called data mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class. Double underscore names are meant to avoid accidental overriding by a subclass instead.
[ { "code": null, "e": 1297, "s": 1062, "text": "In actual terms (practically), python doesn’t have anything called private member variable in Python. However, adding two underlines(__) at the beginning makes a variable or a method private is the convention used by most python code." }, { "code": null, "e": 1348, "s": 1297, "text": "Let’s understand this concept through an example −" }, { "code": null, "e": 1359, "s": 1348, "text": " Live Demo" }, { "code": null, "e": 1588, "s": 1359, "text": "class myClass:\n __privateVar = 27;\n def __privMeth(self):\n print(\"I'm inside class myClass\")\n def hello(self):\n print(\"Private Variable value: \",myClass.__privateVar)\nfoo = myClass()\nfoo.hello()\nfoo.__privateMeth" }, { "code": null, "e": 1708, "s": 1588, "text": "In the above program, __privMeth is a private method and __privateVar is a private variable. Let’s see its output now −" }, { "code": null, "e": 1924, "s": 1708, "text": "Private Variable value: 27\nTraceback (most recent call last):\n File \"C:/Python/Python361/privateVar1.py\", line 12, in <module>\n foo.__privateMeth\nAttributeError: 'myClass' object has no attribute '__privateMeth'" }, { "code": null, "e": 2248, "s": 1924, "text": "From the above output, we can see that outside the class “myClass”, you cannot access the private method as well as the private variable. However, inside the class (myClass) we can access the private variables. In the hello() method, the __privateVar variable can be accessed (as shown above: “Private Variable value: 27”)." }, { "code": null, "e": 2946, "s": 2248, "text": "So from the above example, we can understand that all the variables and the methods inside the class are public by the method. When we declare data member as private it means they are accessible only side the class and are inaccessible outside the class. The technique of making a variable or method private is called data mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class." }, { "code": null, "e": 3034, "s": 2946, "text": "Double underscore names are meant to avoid accidental overriding by a subclass instead." } ]
AWT WindowEvent Class
The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window. Following is the declaration for java.awt.event.WindowEvent class: public class WindowEvent extends ComponentEvent Following are the fields for java.awt.event.WindowEvent class: static int WINDOW_ACTIVATED --The window-activated event type. static int WINDOW_ACTIVATED --The window-activated event type. static int WINDOW_CLOSED -- The window closed event. static int WINDOW_CLOSED -- The window closed event. static int WINDOW_CLOSING -- The "window is closing" event. static int WINDOW_CLOSING -- The "window is closing" event. static int WINDOW_DEACTIVATED -- The window-deactivated event type. static int WINDOW_DEACTIVATED -- The window-deactivated event type. static int WINDOW_DEICONIFIED -- The window deiconified event type. static int WINDOW_DEICONIFIED -- The window deiconified event type. static int WINDOW_FIRST -- The first number in the range of ids used for window events. static int WINDOW_FIRST -- The first number in the range of ids used for window events. static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type. static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type. static int WINDOW_ICONIFIED -- The window iconified event. static int WINDOW_ICONIFIED -- The window iconified event. static int WINDOW_LAST -- The last number in the range of ids used for window events. static int WINDOW_LAST -- The last number in the range of ids used for window events. static int WINDOW_LOST_FOCUS -- The window-lost-focus event type. static int WINDOW_LOST_FOCUS -- The window-lost-focus event type. static int WINDOW_OPENED -- The window opened event. static int WINDOW_OPENED -- The window opened event. static int WINDOW_STATE_CHANGED -- The window-state-changed event type. static int WINDOW_STATE_CHANGED -- The window-state-changed event type. WindowEvent(Window source, int id) Constructs a WindowEvent object. WindowEvent(Window source, int id, int oldState, int newState) Constructs a WindowEvent object with the specified previous and new window states. WindowEvent(Window source, int id, Window opposite) Constructs a WindowEvent object with the specified opposite Window. WindowEvent(Window source, int id, Window opposite, int oldState, int newState) Constructs a WindowEvent object. int getNewState() For WINDOW_STATE_CHANGED events returns the new state of the window. int getOldState() For WINDOW_STATE_CHANGED events returns the previous state of the window. Window getOppositeWindow() Returns the other Window involved in this focus or activation change. Window getWindow() Returns the originator of the event. String paramString() Returns a parameter string identifying this event. This class inherits methods from the following classes: java.awt.event.ComponentEvent java.awt.event.ComponentEvent java.awt.AWTEvent java.awt.AWTEvent java.util.EventObject java.util.EventObject java.lang.Object java.lang.Object 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2001, "s": 1747, "text": "The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window." }, { "code": null, "e": 2068, "s": 2001, "text": "Following is the declaration for java.awt.event.WindowEvent class:" }, { "code": null, "e": 2119, "s": 2068, "text": "public class WindowEvent\n extends ComponentEvent" }, { "code": null, "e": 2182, "s": 2119, "text": "Following are the fields for java.awt.event.WindowEvent class:" }, { "code": null, "e": 2246, "s": 2182, "text": "static int WINDOW_ACTIVATED --The window-activated event type." }, { "code": null, "e": 2310, "s": 2246, "text": "static int WINDOW_ACTIVATED --The window-activated event type." }, { "code": null, "e": 2364, "s": 2310, "text": "static int WINDOW_CLOSED -- The window closed event." }, { "code": null, "e": 2418, "s": 2364, "text": "static int WINDOW_CLOSED -- The window closed event." }, { "code": null, "e": 2479, "s": 2418, "text": "static int WINDOW_CLOSING -- The \"window is closing\" event." }, { "code": null, "e": 2540, "s": 2479, "text": "static int WINDOW_CLOSING -- The \"window is closing\" event." }, { "code": null, "e": 2609, "s": 2540, "text": "static int WINDOW_DEACTIVATED --\tThe window-deactivated event type." }, { "code": null, "e": 2678, "s": 2609, "text": "static int WINDOW_DEACTIVATED --\tThe window-deactivated event type." }, { "code": null, "e": 2747, "s": 2678, "text": "static int WINDOW_DEICONIFIED -- The window deiconified event type." }, { "code": null, "e": 2816, "s": 2747, "text": "static int WINDOW_DEICONIFIED -- The window deiconified event type." }, { "code": null, "e": 2905, "s": 2816, "text": "static int WINDOW_FIRST -- The first number in the range of ids used for window events." }, { "code": null, "e": 2994, "s": 2905, "text": "static int WINDOW_FIRST -- The first number in the range of ids used for window events." }, { "code": null, "e": 3065, "s": 2994, "text": "static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type." }, { "code": null, "e": 3136, "s": 3065, "text": "static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type." }, { "code": null, "e": 3196, "s": 3136, "text": "static int WINDOW_ICONIFIED -- The window iconified event." }, { "code": null, "e": 3256, "s": 3196, "text": "static int WINDOW_ICONIFIED -- The window iconified event." }, { "code": null, "e": 3343, "s": 3256, "text": "static int WINDOW_LAST -- The last number in the range of ids used for window events." }, { "code": null, "e": 3430, "s": 3343, "text": "static int WINDOW_LAST -- The last number in the range of ids used for window events." }, { "code": null, "e": 3497, "s": 3430, "text": "static int WINDOW_LOST_FOCUS -- The window-lost-focus event type." }, { "code": null, "e": 3564, "s": 3497, "text": "static int WINDOW_LOST_FOCUS -- The window-lost-focus event type." }, { "code": null, "e": 3618, "s": 3564, "text": "static int WINDOW_OPENED -- The window opened event." }, { "code": null, "e": 3672, "s": 3618, "text": "static int WINDOW_OPENED -- The window opened event." }, { "code": null, "e": 3745, "s": 3672, "text": "static int WINDOW_STATE_CHANGED -- The window-state-changed event type." }, { "code": null, "e": 3818, "s": 3745, "text": "static int WINDOW_STATE_CHANGED -- The window-state-changed event type." }, { "code": null, "e": 3854, "s": 3818, "text": "WindowEvent(Window source, int id) " }, { "code": null, "e": 3887, "s": 3854, "text": "Constructs a WindowEvent object." }, { "code": null, "e": 3951, "s": 3887, "text": "WindowEvent(Window source, int id, int oldState, int newState) " }, { "code": null, "e": 4034, "s": 3951, "text": "Constructs a WindowEvent object with the specified previous and new window states." }, { "code": null, "e": 4087, "s": 4034, "text": "WindowEvent(Window source, int id, Window opposite) " }, { "code": null, "e": 4155, "s": 4087, "text": "Constructs a WindowEvent object with the specified opposite Window." }, { "code": null, "e": 4236, "s": 4155, "text": "WindowEvent(Window source, int id, Window opposite, int oldState, int newState) " }, { "code": null, "e": 4269, "s": 4236, "text": "Constructs a WindowEvent object." }, { "code": null, "e": 4288, "s": 4269, "text": "int getNewState() " }, { "code": null, "e": 4357, "s": 4288, "text": "For WINDOW_STATE_CHANGED events returns the new state of the window." }, { "code": null, "e": 4376, "s": 4357, "text": "int getOldState() " }, { "code": null, "e": 4451, "s": 4376, "text": " For WINDOW_STATE_CHANGED events returns the previous state of the window." }, { "code": null, "e": 4479, "s": 4451, "text": "Window\tgetOppositeWindow() " }, { "code": null, "e": 4550, "s": 4479, "text": " Returns the other Window involved in this focus or activation change." }, { "code": null, "e": 4570, "s": 4550, "text": "Window\tgetWindow() " }, { "code": null, "e": 4607, "s": 4570, "text": "Returns the originator of the event." }, { "code": null, "e": 4629, "s": 4607, "text": "String\tparamString() " }, { "code": null, "e": 4681, "s": 4629, "text": " Returns a parameter string identifying this event." }, { "code": null, "e": 4737, "s": 4681, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 4767, "s": 4737, "text": "java.awt.event.ComponentEvent" }, { "code": null, "e": 4797, "s": 4767, "text": "java.awt.event.ComponentEvent" }, { "code": null, "e": 4815, "s": 4797, "text": "java.awt.AWTEvent" }, { "code": null, "e": 4833, "s": 4815, "text": "java.awt.AWTEvent" }, { "code": null, "e": 4855, "s": 4833, "text": "java.util.EventObject" }, { "code": null, "e": 4877, "s": 4855, "text": "java.util.EventObject" }, { "code": null, "e": 4894, "s": 4877, "text": "java.lang.Object" }, { "code": null, "e": 4911, "s": 4894, "text": "java.lang.Object" }, { "code": null, "e": 4944, "s": 4911, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 4952, "s": 4944, "text": " EduOLC" }, { "code": null, "e": 4959, "s": 4952, "text": " Print" }, { "code": null, "e": 4970, "s": 4959, "text": " Add Notes" } ]
How do I terminate a thread in C++11?
Here we will see, how to terminate the threads in C++11. The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object. To create one promise object, we have to follow this syntax − std::promise<void> exitSignal; Now fetch the associated future object from this created promise object in main function − std::future<void> futureObj = exitSignal.get_future(); Now pass the main function while creating the thread, pass the future object − std::thread th(&threadFunction, std::move(futureObj)); #include <thread> #include <iostream> #include <assert.h> #include <chrono> #include <future> using namespace std; void threadFunction(std::future<void> future){ std::cout << "Starting the thread" << std::endl; while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){ std::cout << "Executing the thread....." << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds } std::cout << "Thread Terminated" << std::endl; } main(){ std::promise<void> signal_exit; //create promise object std::future<void> future = signal_exit.get_future();//create future objects std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds std::cout << "Threads will be stopped soon...." << std::endl; signal_exit.set_value(); //set value into promise my_thread.join(); //join the thread with the main thread std::cout << "Doing task in main function" << std::endl; } Starting the thread Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Executing the thread..... Threads will be stopped soon.... Thread Terminated Doing task in main function
[ { "code": null, "e": 1183, "s": 1062, "text": "Here we will see, how to terminate the threads in C++11. The C++11 does not have direct method to terminate the threads." }, { "code": null, "e": 1395, "s": 1183, "text": "The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object." }, { "code": null, "e": 1457, "s": 1395, "text": "To create one promise object, we have to follow this syntax −" }, { "code": null, "e": 1488, "s": 1457, "text": "std::promise<void> exitSignal;" }, { "code": null, "e": 1579, "s": 1488, "text": "Now fetch the associated future object from this created promise object in main function −" }, { "code": null, "e": 1634, "s": 1579, "text": "std::future<void> futureObj = exitSignal.get_future();" }, { "code": null, "e": 1713, "s": 1634, "text": "Now pass the main function while creating the thread, pass the future object −" }, { "code": null, "e": 1768, "s": 1713, "text": "std::thread th(&threadFunction, std::move(futureObj));" }, { "code": null, "e": 2842, "s": 1768, "text": "#include <thread>\n#include <iostream>\n#include <assert.h>\n#include <chrono>\n#include <future>\nusing namespace std;\nvoid threadFunction(std::future<void> future){\n std::cout << \"Starting the thread\" << std::endl;\n while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){\n std::cout << \"Executing the thread.....\" << std::endl;\n std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds\n }\n std::cout << \"Thread Terminated\" << std::endl;\n}\nmain(){\n std::promise<void> signal_exit; //create promise object\n std::future<void> future = signal_exit.get_future();//create future objects\n std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future\n std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds\n std::cout << \"Threads will be stopped soon....\" << std::endl;\n signal_exit.set_value(); //set value into promise\n my_thread.join(); //join the thread with the main thread\n std::cout << \"Doing task in main function\" << std::endl;\n}" }, { "code": null, "e": 3305, "s": 2842, "text": "Starting the thread\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nExecuting the thread.....\nThreads will be stopped soon....\nThread Terminated\nDoing task in main function" } ]
Sum of all N digit palindrome numbers - GeeksforGeeks
24 Feb, 2022 Given a number N. The task is to find the sum of all N-digit palindromes. Examples: Input: N = 2 Output: 495 Explanation: 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 = 495 Input: N = 7 Output: 49500000000 Naive Approach:Run a loop from 10^(n-1) to 10^(n) – 1 and check when the current number is palindrome or not. If it adds its value to the answer. Below is the implementation of the above approach: CPP Java Python C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to check// palindromebool isPalindrome(string& s){ int left = 0, right = s.size() - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromelong long getSum(int n){ int start = pow(10, n - 1); int end = pow(10, n) - 1; long long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { string s = to_string(i); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codeint main(){ int n = 1; long long ans = getSum(n); cout << ans << '\n'; return 0;} // Java program for the// above approachimport java.util.*; class GFG{ // Function to check// palindromestatic boolean isPalindrome(String s){ int left = 0, right = s.length() - 1; while (left <= right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromestatic long getSum(int n){ int start = (int) Math.pow(10, n - 1); int end = (int) (Math.pow(10, n) - 1); long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { String s = String.valueOf(i); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codepublic static void main(String[] args){ int n = 1; long ans = getSum(n); System.out.print(ans);}} // This code is contributed by 29AjayKumar # Python program for the above approachimport math # Function to check# palindromedef isPalindrome(s): left = 0 right = len(s) - 1 while (left <= right): if (s[left] != s[right]): return False left = left + 1 right = right - 1 return True # Function to calculate# the sum of n-digit# palindromedef getSum(n): start = int(math.pow(10, n - 1)) end = int(math.pow(10, n)) - 1 sum = 0 # Run a loop to check # all possible palindrome for i in range(start, end + 1): s = str(i) # If palindrome # append sum if (isPalindrome(s)): sum = sum + i return sum # Driver code n = 1ans = getSum(n)print(ans) # This code is contributed by Sanjit_Prasad // C# program for the above approachusing System; class GFG{ // Function to check // palindrome static bool isPalindrome(string s) { int left = 0, right = s.Length - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true; } // Function to calculate // the sum of n-digit // palindrome static long getSum(int n) { int start = (int) Math.Pow(10, n - 1); int end = (int) (Math.Pow(10, n) - 1); long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { string s = i.ToString();; // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum; } // Driver code public static void Main() { int n = 1; long ans = getSum(n); Console.Write(ans); }} // This code is contributed by AnkitRai01 <script> // JavaScript program for the// above approach // Function to check// palindromefunction isPalindrome(s){ var left = 0, right = s.length - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromefunction getSum(n){ var start = Math.pow(10, n - 1); var end = Math.pow(10, n) - 1; var sum = 0; // Run a loop to check // all possible palindrome for (var i = start; i <= end; i++) { var s = (i.toString()); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codevar n = 1;var ans = getSum(n);document.write( ans + "<br>"); </script> 45 Time Complexity: O(n*log(n)) Auxiliary Space: O(1) Efficient approach:On carefully observing the sum of n digit palindrome a series is formed i.e 45, 495, 49500, 495000, 49500000, 495000000. Therefore, by deducing this to a mathematical formula, we get for n = 1 sum = 45 and for n > 1 put sum = (99/2)*10^n-1*10^(n-1)/2 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// sum of n digit numberlong double getSum(int n){ long double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * pow(10, n - 1) * pow(10, (n - 1) / 2); } return sum;} // Driver codeint main(){ int n = 3; long double ans = getSum(n); cout << setprecision(12) << ans << '\n'; return 0;} // Java program for// the above approach class GFG{ // Function to calculate // sum of n digit number static double getSum(int n) { double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.pow(10, n - 1) * Math.pow(10, (n - 1) / 2); } return sum; } // Driver code public static void main(String[] args) { int n = 3; double ans = getSum(n); System.out.print(ans); }} // This code is contributed by PrinciRaj1992 # Python program for# the above approach # Function to calculate# sum of n digit numberdef getSum(n): sum = 0; # Corner case if (n == 1): sum = 45.0; # Using above approach else: sum = (99.0 / 2.0) * pow(10, n - 1)\ * pow(10, (n - 1) / 2); return sum; # Driver codeif __name__ == '__main__': n = 3; ans = int(getSum(n)); print(ans); # This code is contributed by 29AjayKumar // C# program for// the above approachusing System; class GFG{ // Function to calculate // sum of n digit number static double getSum(int n) { double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.Pow(10, n - 1) * Math.Pow(10, (n - 1) / 2); } return sum; } // Driver code public static void Main(String[] args) { int n = 3; double ans = getSum(n); Console.Write(ans); }} // This code is contributed by 29AjayKumar <script> // Javascript program for// the above approach // Function to calculate// sum of n digit numberfunction getSum(n){ var sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.pow(10, n - 1) * Math.pow(10, parseInt((n - 1) / 2)); } return sum;} // Driver codevar n = 3;var ans = getSum(n);document.write(ans + "<br>"); </script> 49500 Time Complexity: O(1) Auxiliary Space: O(1) Sanjit_Prasad 29AjayKumar ankthon princiraj1992 itsok famously as5853535 subhammahato348 Numbers palindrome Mathematical Mathematical Numbers palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007) Find all factors of a natural number | Set 1 Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24477, "s": 24449, "text": "\n24 Feb, 2022" }, { "code": null, "e": 24551, "s": 24477, "text": "Given a number N. The task is to find the sum of all N-digit palindromes." }, { "code": null, "e": 24562, "s": 24551, "text": "Examples: " }, { "code": null, "e": 24685, "s": 24562, "text": "Input: N = 2\nOutput: 495\nExplanation: \n11 + 22 + 33 + 44 + 55 +\n66 + 77 + 88 + 99\n= 495\n\nInput: N = 7\nOutput: 49500000000 " }, { "code": null, "e": 24831, "s": 24685, "text": "Naive Approach:Run a loop from 10^(n-1) to 10^(n) – 1 and check when the current number is palindrome or not. If it adds its value to the answer." }, { "code": null, "e": 24884, "s": 24831, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 24888, "s": 24884, "text": "CPP" }, { "code": null, "e": 24893, "s": 24888, "text": "Java" }, { "code": null, "e": 24900, "s": 24893, "text": "Python" }, { "code": null, "e": 24903, "s": 24900, "text": "C#" }, { "code": null, "e": 24914, "s": 24903, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to check// palindromebool isPalindrome(string& s){ int left = 0, right = s.size() - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromelong long getSum(int n){ int start = pow(10, n - 1); int end = pow(10, n) - 1; long long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { string s = to_string(i); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codeint main(){ int n = 1; long long ans = getSum(n); cout << ans << '\\n'; return 0;}", "e": 25781, "s": 24914, "text": null }, { "code": "// Java program for the// above approachimport java.util.*; class GFG{ // Function to check// palindromestatic boolean isPalindrome(String s){ int left = 0, right = s.length() - 1; while (left <= right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromestatic long getSum(int n){ int start = (int) Math.pow(10, n - 1); int end = (int) (Math.pow(10, n) - 1); long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { String s = String.valueOf(i); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codepublic static void main(String[] args){ int n = 1; long ans = getSum(n); System.out.print(ans);}} // This code is contributed by 29AjayKumar", "e": 26769, "s": 25781, "text": null }, { "code": "# Python program for the above approachimport math # Function to check# palindromedef isPalindrome(s): left = 0 right = len(s) - 1 while (left <= right): if (s[left] != s[right]): return False left = left + 1 right = right - 1 return True # Function to calculate# the sum of n-digit# palindromedef getSum(n): start = int(math.pow(10, n - 1)) end = int(math.pow(10, n)) - 1 sum = 0 # Run a loop to check # all possible palindrome for i in range(start, end + 1): s = str(i) # If palindrome # append sum if (isPalindrome(s)): sum = sum + i return sum # Driver code n = 1ans = getSum(n)print(ans) # This code is contributed by Sanjit_Prasad", "e": 27532, "s": 26769, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to check // palindrome static bool isPalindrome(string s) { int left = 0, right = s.Length - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true; } // Function to calculate // the sum of n-digit // palindrome static long getSum(int n) { int start = (int) Math.Pow(10, n - 1); int end = (int) (Math.Pow(10, n) - 1); long sum = 0; // Run a loop to check // all possible palindrome for (int i = start; i <= end; i++) { string s = i.ToString();; // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum; } // Driver code public static void Main() { int n = 1; long ans = getSum(n); Console.Write(ans); }} // This code is contributed by AnkitRai01", "e": 28682, "s": 27532, "text": null }, { "code": "<script> // JavaScript program for the// above approach // Function to check// palindromefunction isPalindrome(s){ var left = 0, right = s.length - 1; while (left <= right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function to calculate// the sum of n-digit// palindromefunction getSum(n){ var start = Math.pow(10, n - 1); var end = Math.pow(10, n) - 1; var sum = 0; // Run a loop to check // all possible palindrome for (var i = start; i <= end; i++) { var s = (i.toString()); // If palindrome // append sum if (isPalindrome(s)) { sum += i; } } return sum;} // Driver codevar n = 1;var ans = getSum(n);document.write( ans + \"<br>\"); </script>", "e": 29491, "s": 28682, "text": null }, { "code": null, "e": 29494, "s": 29491, "text": "45" }, { "code": null, "e": 29525, "s": 29496, "text": "Time Complexity: O(n*log(n))" }, { "code": null, "e": 29548, "s": 29525, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 29819, "s": 29548, "text": "Efficient approach:On carefully observing the sum of n digit palindrome a series is formed i.e 45, 495, 49500, 495000, 49500000, 495000000. Therefore, by deducing this to a mathematical formula, we get for n = 1 sum = 45 and for n > 1 put sum = (99/2)*10^n-1*10^(n-1)/2 " }, { "code": null, "e": 29872, "s": 29819, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29876, "s": 29872, "text": "C++" }, { "code": null, "e": 29881, "s": 29876, "text": "Java" }, { "code": null, "e": 29889, "s": 29881, "text": "Python3" }, { "code": null, "e": 29892, "s": 29889, "text": "C#" }, { "code": null, "e": 29903, "s": 29892, "text": "Javascript" }, { "code": "// C++ program for// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate// sum of n digit numberlong double getSum(int n){ long double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * pow(10, n - 1) * pow(10, (n - 1) / 2); } return sum;} // Driver codeint main(){ int n = 3; long double ans = getSum(n); cout << setprecision(12) << ans << '\\n'; return 0;}", "e": 30416, "s": 29903, "text": null }, { "code": "// Java program for// the above approach class GFG{ // Function to calculate // sum of n digit number static double getSum(int n) { double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.pow(10, n - 1) * Math.pow(10, (n - 1) / 2); } return sum; } // Driver code public static void main(String[] args) { int n = 3; double ans = getSum(n); System.out.print(ans); }} // This code is contributed by PrinciRaj1992", "e": 31085, "s": 30416, "text": null }, { "code": "# Python program for# the above approach # Function to calculate# sum of n digit numberdef getSum(n): sum = 0; # Corner case if (n == 1): sum = 45.0; # Using above approach else: sum = (99.0 / 2.0) * pow(10, n - 1)\\ * pow(10, (n - 1) / 2); return sum; # Driver codeif __name__ == '__main__': n = 3; ans = int(getSum(n)); print(ans); # This code is contributed by 29AjayKumar", "e": 31520, "s": 31085, "text": null }, { "code": "// C# program for// the above approachusing System; class GFG{ // Function to calculate // sum of n digit number static double getSum(int n) { double sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.Pow(10, n - 1) * Math.Pow(10, (n - 1) / 2); } return sum; } // Driver code public static void Main(String[] args) { int n = 3; double ans = getSum(n); Console.Write(ans); }} // This code is contributed by 29AjayKumar", "e": 32194, "s": 31520, "text": null }, { "code": "<script> // Javascript program for// the above approach // Function to calculate// sum of n digit numberfunction getSum(n){ var sum = 0; // Corner case if (n == 1) { sum = 45.0; } // Using above approach else { sum = (99.0 / 2.0) * Math.pow(10, n - 1) * Math.pow(10, parseInt((n - 1) / 2)); } return sum;} // Driver codevar n = 3;var ans = getSum(n);document.write(ans + \"<br>\"); </script>", "e": 32638, "s": 32194, "text": null }, { "code": null, "e": 32644, "s": 32638, "text": "49500" }, { "code": null, "e": 32668, "s": 32646, "text": "Time Complexity: O(1)" }, { "code": null, "e": 32691, "s": 32668, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 32705, "s": 32691, "text": "Sanjit_Prasad" }, { "code": null, "e": 32717, "s": 32705, "text": "29AjayKumar" }, { "code": null, "e": 32725, "s": 32717, "text": "ankthon" }, { "code": null, "e": 32739, "s": 32725, "text": "princiraj1992" }, { "code": null, "e": 32745, "s": 32739, "text": "itsok" }, { "code": null, "e": 32754, "s": 32745, "text": "famously" }, { "code": null, "e": 32764, "s": 32754, "text": "as5853535" }, { "code": null, "e": 32780, "s": 32764, "text": "subhammahato348" }, { "code": null, "e": 32788, "s": 32780, "text": "Numbers" }, { "code": null, "e": 32799, "s": 32788, "text": "palindrome" }, { "code": null, "e": 32812, "s": 32799, "text": "Mathematical" }, { "code": null, "e": 32825, "s": 32812, "text": "Mathematical" }, { "code": null, "e": 32833, "s": 32825, "text": "Numbers" }, { "code": null, "e": 32844, "s": 32833, "text": "palindrome" }, { "code": null, "e": 32942, "s": 32844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32951, "s": 32942, "text": "Comments" }, { "code": null, "e": 32964, "s": 32951, "text": "Old Comments" }, { "code": null, "e": 32988, "s": 32964, "text": "Merge two sorted arrays" }, { "code": null, "e": 33030, "s": 32988, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33073, "s": 33030, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33087, "s": 33073, "text": "Prime Numbers" }, { "code": null, "e": 33109, "s": 33087, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33150, "s": 33109, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33177, "s": 33150, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 33222, "s": 33177, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 33271, "s": 33222, "text": "Program to find sum of elements in a given array" } ]
How to close active/current tab without closing the browser in Selenium-Python?
We can close the active/current tab without closing the browser in Selenium webdriver in Python. By default, Selenium has control over the parent window. Once another browser window is opened, we have to explicitly shift the control with the help of switch_to.window method. The handle id of the browser window where we want to shift is passed as a parameter to that method. The method window_handles returns the list of all window handle ids of the opened browsers. The method current_window_handle is used to hold the window handle id of the browser window in focus. To close only the active or current tab we have to use the close method. parent = driver.window_handles[0] chld = driver.window_handles[1] driver.switch_to.window(chld) driver.close() Let us try to close active browser as shown in the below image − from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://accounts.google.com/") #identify element m = driver.find_element_by_link_text("Help") m.click() #obtain parent window handle p= driver.window_handles[0] #obtain browser tab window c = driver.window_handles[1] #switch to tab browser driver.switch_to.window(c) print("Page title :") print(driver.title) #close browser tab window driver.close() #switch to parent window driver.switch_to.window(p) print("Current page title:") print(driver.title) #close browser parent window driver.quit()
[ { "code": null, "e": 1337, "s": 1062, "text": "We can close the active/current tab without closing the browser in Selenium webdriver in Python. By default, Selenium has control over the parent window. Once another browser window is opened, we have to explicitly shift the control with the help of switch_to.window method." }, { "code": null, "e": 1529, "s": 1337, "text": "The handle id of the browser window where we want to shift is passed as a parameter to that method. The method window_handles returns the list of all window handle ids of the opened browsers." }, { "code": null, "e": 1704, "s": 1529, "text": "The method current_window_handle is used to hold the window handle id of the browser window in focus. To close only the active or current tab we have to use the close method." }, { "code": null, "e": 1815, "s": 1704, "text": "parent = driver.window_handles[0]\nchld = driver.window_handles[1]\ndriver.switch_to.window(chld)\ndriver.close()" }, { "code": null, "e": 1880, "s": 1815, "text": "Let us try to close active browser as shown in the below image −" }, { "code": null, "e": 2550, "s": 1880, "text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://accounts.google.com/\")\n#identify element\nm = driver.find_element_by_link_text(\"Help\")\nm.click()\n#obtain parent window handle\np= driver.window_handles[0]\n#obtain browser tab window\nc = driver.window_handles[1]\n#switch to tab browser\ndriver.switch_to.window(c)\nprint(\"Page title :\")\nprint(driver.title)\n#close browser tab window\ndriver.close()\n#switch to parent window\ndriver.switch_to.window(p)\nprint(\"Current page title:\")\nprint(driver.title)\n#close browser parent window\ndriver.quit()" } ]
Region Prioritisation Algorithm: Helping Business identify Top Regions to serve | by Abhishek Mungoli | Towards Data Science
In the present time, due to the Pandemic, many suppliers and online services are serving selected regions which could be the major sales contributors. Also, when someone starts a new business they want to focus on a few regions which can draw maximum profit and think of expansion later. Many times suppliers at times close low-profit regions where ROI(Return on Investment) is poor. All the above instances need identification of regions as per their importance/priority/contribution to the business. Through this blog, I intend to propose an algorithm that is simple, intuitive, scalable, and does a decent job of dividing the regions as per their importance. I will also propose a metric that can quantify the algorithm’s effectiveness in prioritizing the regions. The proposed algorithm consists of three steps : The first step consists of counting the frequency of orders coming from every region. A region can be defined based on postal code or city or state depending on the type of business and the way it operates. Similarly, the frequency can be daily, weekly, or monthly depending on the type of business and the way it operates. The blue line denotes the route in the figure. The Circle represents different regions and dots the orders. In the above figure, we have a supplier ‘S’ and 10 Regions (A-J). The frequency of orders on a weekly basis is summarised in the table: Sort the regions by order frequency (from step 1) and divide them into high, medium, and low-frequency regions. Normally, my selection criteria goes like90-100th percentile of Frequency ~ High-frequency region75-90th percentile of Frequency ~ Medium-frequency region<75th percentile of Frequency ~ Low-frequency regionThis percentile used for region selection is a hyperparameters which can be tuned as per the Business, its type and needs. This final step is the heart of the Algorithm. Here we cluster regions based on priority and then move a few regions from one cluster to another to come up with the final ranking. Initialize high-priority regions with all high-frequent regions from Step 2. Initialize medium-priority regions with all medium-frequent regions from Step 2. Initialize low-priority regions with all low-frequent regions from Step 2. For all high-priority regions store the intermediate points in the route(at some interval), there are Map Apis which provides that. Find the distance of regions belonging to medium and low priority regions with all these intermediate points. If the shortest distance is anywhere less than a threshold (< 5 miles ~ example), move the region into the high priority cluster. The distance can be Map distance (Road distance) or other distance like Haversine. The main reason is that, if there is a medium or low-priority region in the route or near-by of the high-priority region, it can be served with minimal efforts while serving the high-priority ones. Similarly, move regions from low to medium-priority clusters that fall on the route or nearby of the medium-priority regions. As a result of this step Regions ‘E’, ‘H’, and ‘F’ move to High-priority regions as they are in the route or near-by of the high priority region ‘G’. Intuition is ‘E’, ‘H’, and ‘F’ can be served together with high-priority region ‘G’ with minimal efforts. The final Supplier location map looks like: To quantify the effectiveness of the proposed algorithm, we devise a metric ‘Prioritization Gain’. Prioritization Gain is defined as the ratio of Sales Coverage to that of Distance coverage. Let’s say after prioritization of regions and just serving the high-priority ones, we have reduced the distance to 40% to that of actual and sales reduced to 80% to that of actual. ‘Prioritization Gain’ in this case will be: Prioritization Gain = 0.80/0.40 = 2.28 Higher the ‘Prioritization Gain’ value, better is the algorithm’s performance. With this blog post, We devised a simple and scalable Region Prioritisation algorithm to help a business identify the top-priority(most profitable) regions to serve smartly. Also, we analyzed visually how it works and defined a metric to measure its effectiveness. If you have any doubts or queries, do reach out to me. I will be interested to know if you are working on some Route prioritisation or Graph based algorithms and this blog post was helpful. My Youtube channel for more content: www.youtube.com About the author-: Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc. My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me up at Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs - 5 Mistakes every Data Scientist should avoid Decomposing Time Series in a simple & intuitive way How GPU Computing literally saved me at work? Information Theory & KL Divergence Part I and Part II Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets A Semi-Supervised Embedding based Fuzzy Clustering Compare which Machine Learning Model performs Better Analyzing Fitbit Data to Demystify Bodily Pattern Changes Amid Pandemic Lockdown Myths and Reality around Correlation
[ { "code": null, "e": 556, "s": 172, "text": "In the present time, due to the Pandemic, many suppliers and online services are serving selected regions which could be the major sales contributors. Also, when someone starts a new business they want to focus on a few regions which can draw maximum profit and think of expansion later. Many times suppliers at times close low-profit regions where ROI(Return on Investment) is poor." }, { "code": null, "e": 940, "s": 556, "text": "All the above instances need identification of regions as per their importance/priority/contribution to the business. Through this blog, I intend to propose an algorithm that is simple, intuitive, scalable, and does a decent job of dividing the regions as per their importance. I will also propose a metric that can quantify the algorithm’s effectiveness in prioritizing the regions." }, { "code": null, "e": 989, "s": 940, "text": "The proposed algorithm consists of three steps :" }, { "code": null, "e": 1196, "s": 989, "text": "The first step consists of counting the frequency of orders coming from every region. A region can be defined based on postal code or city or state depending on the type of business and the way it operates." }, { "code": null, "e": 1313, "s": 1196, "text": "Similarly, the frequency can be daily, weekly, or monthly depending on the type of business and the way it operates." }, { "code": null, "e": 1421, "s": 1313, "text": "The blue line denotes the route in the figure. The Circle represents different regions and dots the orders." }, { "code": null, "e": 1557, "s": 1421, "text": "In the above figure, we have a supplier ‘S’ and 10 Regions (A-J). The frequency of orders on a weekly basis is summarised in the table:" }, { "code": null, "e": 1669, "s": 1557, "text": "Sort the regions by order frequency (from step 1) and divide them into high, medium, and low-frequency regions." }, { "code": null, "e": 1998, "s": 1669, "text": "Normally, my selection criteria goes like90-100th percentile of Frequency ~ High-frequency region75-90th percentile of Frequency ~ Medium-frequency region<75th percentile of Frequency ~ Low-frequency regionThis percentile used for region selection is a hyperparameters which can be tuned as per the Business, its type and needs." }, { "code": null, "e": 2178, "s": 1998, "text": "This final step is the heart of the Algorithm. Here we cluster regions based on priority and then move a few regions from one cluster to another to come up with the final ranking." }, { "code": null, "e": 2255, "s": 2178, "text": "Initialize high-priority regions with all high-frequent regions from Step 2." }, { "code": null, "e": 2336, "s": 2255, "text": "Initialize medium-priority regions with all medium-frequent regions from Step 2." }, { "code": null, "e": 2411, "s": 2336, "text": "Initialize low-priority regions with all low-frequent regions from Step 2." }, { "code": null, "e": 2866, "s": 2411, "text": "For all high-priority regions store the intermediate points in the route(at some interval), there are Map Apis which provides that. Find the distance of regions belonging to medium and low priority regions with all these intermediate points. If the shortest distance is anywhere less than a threshold (< 5 miles ~ example), move the region into the high priority cluster. The distance can be Map distance (Road distance) or other distance like Haversine." }, { "code": null, "e": 3064, "s": 2866, "text": "The main reason is that, if there is a medium or low-priority region in the route or near-by of the high-priority region, it can be served with minimal efforts while serving the high-priority ones." }, { "code": null, "e": 3190, "s": 3064, "text": "Similarly, move regions from low to medium-priority clusters that fall on the route or nearby of the medium-priority regions." }, { "code": null, "e": 3490, "s": 3190, "text": "As a result of this step Regions ‘E’, ‘H’, and ‘F’ move to High-priority regions as they are in the route or near-by of the high priority region ‘G’. Intuition is ‘E’, ‘H’, and ‘F’ can be served together with high-priority region ‘G’ with minimal efforts. The final Supplier location map looks like:" }, { "code": null, "e": 3681, "s": 3490, "text": "To quantify the effectiveness of the proposed algorithm, we devise a metric ‘Prioritization Gain’. Prioritization Gain is defined as the ratio of Sales Coverage to that of Distance coverage." }, { "code": null, "e": 3906, "s": 3681, "text": "Let’s say after prioritization of regions and just serving the high-priority ones, we have reduced the distance to 40% to that of actual and sales reduced to 80% to that of actual. ‘Prioritization Gain’ in this case will be:" }, { "code": null, "e": 3945, "s": 3906, "text": "Prioritization Gain = 0.80/0.40 = 2.28" }, { "code": null, "e": 4024, "s": 3945, "text": "Higher the ‘Prioritization Gain’ value, better is the algorithm’s performance." }, { "code": null, "e": 4289, "s": 4024, "text": "With this blog post, We devised a simple and scalable Region Prioritisation algorithm to help a business identify the top-priority(most profitable) regions to serve smartly. Also, we analyzed visually how it works and defined a metric to measure its effectiveness." }, { "code": null, "e": 4479, "s": 4289, "text": "If you have any doubts or queries, do reach out to me. I will be interested to know if you are working on some Route prioritisation or Graph based algorithms and this blog post was helpful." }, { "code": null, "e": 4516, "s": 4479, "text": "My Youtube channel for more content:" }, { "code": null, "e": 4532, "s": 4516, "text": "www.youtube.com" }, { "code": null, "e": 4551, "s": 4532, "text": "About the author-:" }, { "code": null, "e": 4931, "s": 4551, "text": "Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc." }, { "code": null, "e": 5314, "s": 4931, "text": "My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me up at Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs -" }, { "code": null, "e": 5359, "s": 5314, "text": "5 Mistakes every Data Scientist should avoid" }, { "code": null, "e": 5411, "s": 5359, "text": "Decomposing Time Series in a simple & intuitive way" }, { "code": null, "e": 5457, "s": 5411, "text": "How GPU Computing literally saved me at work?" }, { "code": null, "e": 5511, "s": 5457, "text": "Information Theory & KL Divergence Part I and Part II" }, { "code": null, "e": 5577, "s": 5511, "text": "Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets" }, { "code": null, "e": 5628, "s": 5577, "text": "A Semi-Supervised Embedding based Fuzzy Clustering" }, { "code": null, "e": 5681, "s": 5628, "text": "Compare which Machine Learning Model performs Better" }, { "code": null, "e": 5762, "s": 5681, "text": "Analyzing Fitbit Data to Demystify Bodily Pattern Changes Amid Pandemic Lockdown" } ]
Count duplicates records in MySQL table?
You can use if() from MySQL to count duplicate records. The syntax is as follows − SELECT yourColumnName, COUNT(*) AS anyVariableName, IF ( COUNT(*)>1,"Duplicate Records", "Not Duplicate records") as anyVariableName FROM yourTableName group by yourColumnName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table DuplicateRecords -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(30), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into DuplicateRecords(Name) values('Carol'); Query OK, 1 row affected (0.81 sec) mysql> insert into DuplicateRecords(Name) values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into DuplicateRecords(Name) values('Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into DuplicateRecords(Name) values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into DuplicateRecords(Name) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DuplicateRecords(Name) values('Sam'); Query OK, 1 row affected (0.20 sec) mysql> insert into DuplicateRecords(Name) values('John'); Query OK, 1 row affected (0.12 sec) mysql> insert into DuplicateRecords(Name) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into DuplicateRecords(Name) values('Carol'); Query OK, 1 row affected (0.10 sec) mysql> insert into DuplicateRecords(Name) values('Mike'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from DuplicateRecords; The following is the output − +----+-------+ | Id | Name | +----+-------+ | 1 | Carol | | 2 | John | | 3 | Sam | | 4 | John | | 5 | Sam | | 6 | Sam | | 7 | John | | 8 | Carol | | 9 | Carol | | 10 | Mike | +----+-------+ 10 rows in set (0.00 sec) Here is the query to count the duplicate records from the table − mysql> SELECT Name, COUNT(*) AS Repetition, IF (COUNT(*)>1,"Duplicate Records", "Not Duplicate records") as IsDuplicateRecordsOrNot -> from DuplicateRecords group by Name; The following is the output − +-------+------------+-------------------------+ | Name | Repetition | IsDuplicateRecordsOrNot | +-------+------------+-------------------------+ | Carol | 3 | Duplicate Records | | John | 3 | Duplicate Records | | Sam | 3 | Duplicate Records | | Mike | 1 | Not Duplicate records | +-------+------------+-------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1145, "s": 1062, "text": "You can use if() from MySQL to count duplicate records. The syntax is as follows −" }, { "code": null, "e": 1325, "s": 1145, "text": "SELECT yourColumnName, COUNT(*) AS anyVariableName, IF (\n COUNT(*)>1,\"Duplicate Records\", \"Not Duplicate records\") as anyVariableName FROM yourTableName group by yourColumnName;" }, { "code": null, "e": 1424, "s": 1325, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1599, "s": 1424, "text": "mysql> create table DuplicateRecords\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(30),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1680, "s": 1599, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2629, "s": 1680, "text": "mysql> insert into DuplicateRecords(Name) values('Carol');\nQuery OK, 1 row affected (0.81 sec)\n\nmysql> insert into DuplicateRecords(Name) values('John');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Sam');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DuplicateRecords(Name) values('John');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Sam');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Sam');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DuplicateRecords(Name) values('John');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Carol');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Carol');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DuplicateRecords(Name) values('Mike');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2714, "s": 2629, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2752, "s": 2714, "text": "mysql> select *from DuplicateRecords;" }, { "code": null, "e": 2782, "s": 2752, "text": "The following is the output −" }, { "code": null, "e": 3018, "s": 2782, "text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | Carol |\n| 2 | John |\n| 3 | Sam |\n| 4 | John |\n| 5 | Sam |\n| 6 | Sam |\n| 7 | John |\n| 8 | Carol |\n| 9 | Carol |\n| 10 | Mike |\n+----+-------+\n10 rows in set (0.00 sec)" }, { "code": null, "e": 3084, "s": 3018, "text": "Here is the query to count the duplicate records from the table −" }, { "code": null, "e": 3259, "s": 3084, "text": "mysql> SELECT Name, COUNT(*) AS Repetition, IF (COUNT(*)>1,\"Duplicate Records\", \"Not Duplicate records\") as IsDuplicateRecordsOrNot\n -> from DuplicateRecords group by Name;" }, { "code": null, "e": 3289, "s": 3259, "text": "The following is the output −" }, { "code": null, "e": 3706, "s": 3289, "text": "+-------+------------+-------------------------+\n| Name | Repetition | IsDuplicateRecordsOrNot |\n+-------+------------+-------------------------+\n| Carol | 3 | Duplicate Records |\n| John | 3 | Duplicate Records |\n| Sam | 3 | Duplicate Records |\n| Mike | 1 | Not Duplicate records |\n+-------+------------+-------------------------+\n4 rows in set (0.00 sec)" } ]
Deploying Sklearn Machine Learning on AWS Lambda with SAM | by GreekDataGuy | Towards Data Science
Building machine learning models on a laptop is straightforward. Deploying models so they’re available in production is not. Productionizing ML is hard. Not only does it combine SDE, ML and DevOps. But there’s no one-size fits all approach. A company’s setup depends on a combination of business requirements, financial constraints and technical skills. Today we’ll learn to deploy serverless ML on Lambda. While most ML is not a good fit for serverless, it can make sense on occasion. I’ll explain when it makes sense in a moment. Background informationTrain a model locallyPush the model to S3Build a SAM applicationTest the application locallyDeploy the application to AWSTest the APIConclusion Background information Train a model locally Push the model to S3 Build a SAM application Test the application locally Deploy the application to AWS Test the API Conclusion Your ML is a good fit for Lambda if... Your model is small. Lambda reloads your model on each request so a large model is is going to result in slow response times. Data vectors are small. Lambda comes with a 3GB memory ceiling. So if your input data is massive, it’s just going to crash. You model will be sporadically accessed. Lambda scales out (not up) to infinite and charges you per request. So it’s well suited to intermittent “on-the-fly” demand. Low-cost is important. Lambda charges $0.20 per million requests. Otherwise... consider deploying on EC2, or Sagemaker (if money is not a concern). SAM stands for “Serverless Application Model”. It’s an open-source framework for provisioning AWS services via code. As a rule, always choose infrastructure-as-code over setting up infrastructure in the AWS console. The former is more maintainable, reproducible, and allows storing versions in Github. You’ll need a few things setup on your machine. AWS Shell (downloaded and configured) AWS SAM Client Docker The focus of this tutorial is on deployment. So we won’t concern ourselves with training an accurate model. But you can easily replace this with your own more complex model. In Jupyter notebook, start by importing required libraries. from sklearn.datasets import load_wineimport pandas as pdimport numpy as npimport pickle Import data and generate a dataframe. data = load_wine() # import datasetdf = pd.DataFrame(data['data'], columns=data['feature_names']) # build dataframedf['target'] = data['target'] # add dependent variabledf = df.sample(frac=1) # randomize the datadf.head(3) Split data into test and train sets. print("row count:",len(df))train_df = df[:150]test_df = df[150:]#=> row count: 178 Prepare data to train a model. def X_and_y_from_df(df, y_column, X_columns = []): '''Extract data from the dataframe''' X = {} for feature in X_columns: X[feature] = df[feature].tolist() y = df[y_column].tolist() return X, yX_train, y_train = X_and_y_from_df(train_df, 'target', ['alcohol'])X_test, y_test = X_and_y_from_df(test_df, 'target', ['alcohol'])X_train = np.array(X_train['alcohol']).reshape(-1,1)X_test = np.array(X_test['alcohol']).reshape(-1,1) Fit the model. from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression()model.fit(X_train, y_train) Pickle the model. import picklepickle.dump( model, open( "pickled_model.p", "wb" ) ) Great! Now it’s in a format that can be easily stored in S3. Open your command line in the same directory as your notebook above. Create an S3 bucket. $ aws s3 mb s3://sam-sklearn-lambda-123 Note: You’ll need your own globally unique bucket name. Push your pickled model to S3. $ aws s3 cp pickled_model.p s3://lambda-app-bucket-123 Your model is now accessible to AWS services and can be updated or changed without redeploying any other code. On the command line, initialize a SAM application. $ sam init This will ask you 4 questions which will be used to build a starting template for our SAM application. Answer the questions as below. Which template source would you like to use? 1 — AWS Quick Start TemplatesWhich runtime would you like to use? 2 — python3.8Project name [sam-app]: [press “enter” to keep the default name]AWS quick start application templates: 1 — Hello World Example Which template source would you like to use? 1 — AWS Quick Start Templates Which runtime would you like to use? 2 — python3.8 Project name [sam-app]: [press “enter” to keep the default name] AWS quick start application templates: 1 — Hello World Example Now cd into the directory that was just created, and open it with your favorite text editor. I’m using Atom. The directory structure should look like below. Next, let’s change the name of our the subdirectory where our lambda code lives from /hello_world to code/. You can do this with the following command. $ mv hello_world/ code/ Now it’s time to update files. This is the file which tells CloudFormation which services should be provisioned. Update it so it looks like below. AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31Description: 'Serverless wine classifier'Globals: Function: Timeout: 10Resources: WineClassifierFunction: Type: AWS::Serverless::Function Properties: CodeUri: WineClassifierFunction Handler: app.lambda_handler Runtime: python3.8 MemorySize: 1024 Role: arn:aws:iam::421242169512:role/LambdaCanReadS3 Environment: Variables: s3_bucket: lambda-app-bucket-123 model_name: pickled_model.p Events: WineClassifier: Type: Api Properties: Path: /classify Method: postOutputs: WineClassifierApi: Description: API Gateway endpoint URL for Prod stage for WineClassifier function Value: Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/classify/ Note: You’ll need to create an IAM role in AWS which permits Lambda to read files in S3. Mine is called “arn:aws:iam::421242169512:role/LambdaCanReadS3” but you’ll need to replace this with your role’s name. The above provisions both an API Gateway endpoint and a Lambda. It also specifies the language running on the Lambda as Python3.8, sets a few variables that can be accessed in our lambda code, and configures the API Gateway endpoint. This is where our Lambda code lives. import jsonimport sklearnimport boto3import osimport jsonimport pickles3 = boto3.client('s3')s3_bucket = os.environ['s3_bucket']model_name = os.environ['model_name']temp_file_path = '/tmp/' + model_namefrom sklearn.linear_model import LogisticRegressiondef lambda_handler(event, context): # Parse input body = event['body'] input = json.loads(body)['data'] input = float(input ) # Download pickled model from S3 and unpickle s3.download_file(s3_bucket, model_name, temp_file_path) with open(temp_file_path, 'rb') as f: model = pickle.load(f) # Predict class prediction = model.predict([[input]])[0] return { "statusCode": 200, "body": json.dumps({ "prediction": str(prediction), }), } In a nutshell, this imports libraries, pulls your model from S3, parses the input request, classifies it, and returns a response. This is where we specify what libraries should be installed on our Lambda. Below is all we need. requestsboto3sklearn Now run the following on your command line. $ sam build This creates a .aws-sam/build directory, which contains code that will be deployed to AWS. Before deploying, let’s make sure the application works locally. Do not continue until you get a successful response here. Run below to provision the app locally. $ sam local start-api Now hit the endpoint with a curl. $ curl -XPOST http://127.0.0.1:3000/classify -H 'Content-Type: application/json' -d '{"data":".10"}' The response should look like below. {"prediction": "1"} If you’re response looks like above, continue! cd into the .aws-sam/build/ directory. $ cd .aws-sam$ cd build Now run below. This creates a zip file with dependencies that will be deployed (in a moment). This will take a minute. Note: I’m using the name of my S3 bucket but you should use the name of yours. $ sam package --template-file template.yaml --s3-bucket lambda-app-bucket-123 --output-template-file packaged.yaml Then run below to deploy your application. $ sam deploy --template-file packaged.yaml --stack-name SklearnLambdaStack --capabilities CAPABILITY_IAM You should get a confirmation that your application has been deployed. In the previous response from deployment, you’ll be provided with a URL. If everything worked, sending a request to this URL should return the same response as making a request to your app running locally. $ curl -XPOST https://6lsk6c6vw2.execute-api.us-east-1.amazonaws.com/Prod/classify/ -H 'Content-Type: application/json' -d '{"data":".10"}' So the above should return. {"prediction": "1"} Congratulations! You’ve deployed your first serverless ML application! As you can see, deploying ML on serverless architecture is anything but straightforward. The example we walked through is about as simple as it gets; we even skipped API authentication because I didn’t want to detract from the core lesson. There aren’t many great examples on productionizing serverless ML, so I hope this helps speed up your learning process. I fully expect we’ll see more and better tool for productionizing ML in future. But until then, infrastructure is going to be tightly coupled with model deployment. I hope you found this useful. As always, let me know if you get stuck and I’ll try to help!
[ { "code": null, "e": 237, "s": 172, "text": "Building machine learning models on a laptop is straightforward." }, { "code": null, "e": 297, "s": 237, "text": "Deploying models so they’re available in production is not." }, { "code": null, "e": 413, "s": 297, "text": "Productionizing ML is hard. Not only does it combine SDE, ML and DevOps. But there’s no one-size fits all approach." }, { "code": null, "e": 526, "s": 413, "text": "A company’s setup depends on a combination of business requirements, financial constraints and technical skills." }, { "code": null, "e": 579, "s": 526, "text": "Today we’ll learn to deploy serverless ML on Lambda." }, { "code": null, "e": 704, "s": 579, "text": "While most ML is not a good fit for serverless, it can make sense on occasion. I’ll explain when it makes sense in a moment." }, { "code": null, "e": 870, "s": 704, "text": "Background informationTrain a model locallyPush the model to S3Build a SAM applicationTest the application locallyDeploy the application to AWSTest the APIConclusion" }, { "code": null, "e": 893, "s": 870, "text": "Background information" }, { "code": null, "e": 915, "s": 893, "text": "Train a model locally" }, { "code": null, "e": 936, "s": 915, "text": "Push the model to S3" }, { "code": null, "e": 960, "s": 936, "text": "Build a SAM application" }, { "code": null, "e": 989, "s": 960, "text": "Test the application locally" }, { "code": null, "e": 1019, "s": 989, "text": "Deploy the application to AWS" }, { "code": null, "e": 1032, "s": 1019, "text": "Test the API" }, { "code": null, "e": 1043, "s": 1032, "text": "Conclusion" }, { "code": null, "e": 1082, "s": 1043, "text": "Your ML is a good fit for Lambda if..." }, { "code": null, "e": 1208, "s": 1082, "text": "Your model is small. Lambda reloads your model on each request so a large model is is going to result in slow response times." }, { "code": null, "e": 1332, "s": 1208, "text": "Data vectors are small. Lambda comes with a 3GB memory ceiling. So if your input data is massive, it’s just going to crash." }, { "code": null, "e": 1498, "s": 1332, "text": "You model will be sporadically accessed. Lambda scales out (not up) to infinite and charges you per request. So it’s well suited to intermittent “on-the-fly” demand." }, { "code": null, "e": 1564, "s": 1498, "text": "Low-cost is important. Lambda charges $0.20 per million requests." }, { "code": null, "e": 1646, "s": 1564, "text": "Otherwise... consider deploying on EC2, or Sagemaker (if money is not a concern)." }, { "code": null, "e": 1763, "s": 1646, "text": "SAM stands for “Serverless Application Model”. It’s an open-source framework for provisioning AWS services via code." }, { "code": null, "e": 1948, "s": 1763, "text": "As a rule, always choose infrastructure-as-code over setting up infrastructure in the AWS console. The former is more maintainable, reproducible, and allows storing versions in Github." }, { "code": null, "e": 1996, "s": 1948, "text": "You’ll need a few things setup on your machine." }, { "code": null, "e": 2034, "s": 1996, "text": "AWS Shell (downloaded and configured)" }, { "code": null, "e": 2049, "s": 2034, "text": "AWS SAM Client" }, { "code": null, "e": 2056, "s": 2049, "text": "Docker" }, { "code": null, "e": 2230, "s": 2056, "text": "The focus of this tutorial is on deployment. So we won’t concern ourselves with training an accurate model. But you can easily replace this with your own more complex model." }, { "code": null, "e": 2290, "s": 2230, "text": "In Jupyter notebook, start by importing required libraries." }, { "code": null, "e": 2379, "s": 2290, "text": "from sklearn.datasets import load_wineimport pandas as pdimport numpy as npimport pickle" }, { "code": null, "e": 2417, "s": 2379, "text": "Import data and generate a dataframe." }, { "code": null, "e": 2640, "s": 2417, "text": "data = load_wine() # import datasetdf = pd.DataFrame(data['data'], columns=data['feature_names']) # build dataframedf['target'] = data['target'] # add dependent variabledf = df.sample(frac=1) # randomize the datadf.head(3)" }, { "code": null, "e": 2677, "s": 2640, "text": "Split data into test and train sets." }, { "code": null, "e": 2760, "s": 2677, "text": "print(\"row count:\",len(df))train_df = df[:150]test_df = df[150:]#=> row count: 178" }, { "code": null, "e": 2791, "s": 2760, "text": "Prepare data to train a model." }, { "code": null, "e": 3240, "s": 2791, "text": "def X_and_y_from_df(df, y_column, X_columns = []): '''Extract data from the dataframe''' X = {} for feature in X_columns: X[feature] = df[feature].tolist() y = df[y_column].tolist() return X, yX_train, y_train = X_and_y_from_df(train_df, 'target', ['alcohol'])X_test, y_test = X_and_y_from_df(test_df, 'target', ['alcohol'])X_train = np.array(X_train['alcohol']).reshape(-1,1)X_test = np.array(X_test['alcohol']).reshape(-1,1)" }, { "code": null, "e": 3255, "s": 3240, "text": "Fit the model." }, { "code": null, "e": 3362, "s": 3255, "text": "from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression()model.fit(X_train, y_train)" }, { "code": null, "e": 3380, "s": 3362, "text": "Pickle the model." }, { "code": null, "e": 3447, "s": 3380, "text": "import picklepickle.dump( model, open( \"pickled_model.p\", \"wb\" ) )" }, { "code": null, "e": 3508, "s": 3447, "text": "Great! Now it’s in a format that can be easily stored in S3." }, { "code": null, "e": 3577, "s": 3508, "text": "Open your command line in the same directory as your notebook above." }, { "code": null, "e": 3598, "s": 3577, "text": "Create an S3 bucket." }, { "code": null, "e": 3638, "s": 3598, "text": "$ aws s3 mb s3://sam-sklearn-lambda-123" }, { "code": null, "e": 3694, "s": 3638, "text": "Note: You’ll need your own globally unique bucket name." }, { "code": null, "e": 3725, "s": 3694, "text": "Push your pickled model to S3." }, { "code": null, "e": 3780, "s": 3725, "text": "$ aws s3 cp pickled_model.p s3://lambda-app-bucket-123" }, { "code": null, "e": 3891, "s": 3780, "text": "Your model is now accessible to AWS services and can be updated or changed without redeploying any other code." }, { "code": null, "e": 3942, "s": 3891, "text": "On the command line, initialize a SAM application." }, { "code": null, "e": 3953, "s": 3942, "text": "$ sam init" }, { "code": null, "e": 4056, "s": 3953, "text": "This will ask you 4 questions which will be used to build a starting template for our SAM application." }, { "code": null, "e": 4087, "s": 4056, "text": "Answer the questions as below." }, { "code": null, "e": 4338, "s": 4087, "text": "Which template source would you like to use? 1 — AWS Quick Start TemplatesWhich runtime would you like to use? 2 — python3.8Project name [sam-app]: [press “enter” to keep the default name]AWS quick start application templates: 1 — Hello World Example" }, { "code": null, "e": 4413, "s": 4338, "text": "Which template source would you like to use? 1 — AWS Quick Start Templates" }, { "code": null, "e": 4464, "s": 4413, "text": "Which runtime would you like to use? 2 — python3.8" }, { "code": null, "e": 4529, "s": 4464, "text": "Project name [sam-app]: [press “enter” to keep the default name]" }, { "code": null, "e": 4592, "s": 4529, "text": "AWS quick start application templates: 1 — Hello World Example" }, { "code": null, "e": 4701, "s": 4592, "text": "Now cd into the directory that was just created, and open it with your favorite text editor. I’m using Atom." }, { "code": null, "e": 4749, "s": 4701, "text": "The directory structure should look like below." }, { "code": null, "e": 4901, "s": 4749, "text": "Next, let’s change the name of our the subdirectory where our lambda code lives from /hello_world to code/. You can do this with the following command." }, { "code": null, "e": 4926, "s": 4901, "text": "$ mv hello_world/ code/ " }, { "code": null, "e": 4957, "s": 4926, "text": "Now it’s time to update files." }, { "code": null, "e": 5039, "s": 4957, "text": "This is the file which tells CloudFormation which services should be provisioned." }, { "code": null, "e": 5073, "s": 5039, "text": "Update it so it looks like below." }, { "code": null, "e": 5946, "s": 5073, "text": "AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31Description: 'Serverless wine classifier'Globals: Function: Timeout: 10Resources: WineClassifierFunction: Type: AWS::Serverless::Function Properties: CodeUri: WineClassifierFunction Handler: app.lambda_handler Runtime: python3.8 MemorySize: 1024 Role: arn:aws:iam::421242169512:role/LambdaCanReadS3 Environment: Variables: s3_bucket: lambda-app-bucket-123 model_name: pickled_model.p Events: WineClassifier: Type: Api Properties: Path: /classify Method: postOutputs: WineClassifierApi: Description: API Gateway endpoint URL for Prod stage for WineClassifier function Value: Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/classify/" }, { "code": null, "e": 6154, "s": 5946, "text": "Note: You’ll need to create an IAM role in AWS which permits Lambda to read files in S3. Mine is called “arn:aws:iam::421242169512:role/LambdaCanReadS3” but you’ll need to replace this with your role’s name." }, { "code": null, "e": 6218, "s": 6154, "text": "The above provisions both an API Gateway endpoint and a Lambda." }, { "code": null, "e": 6388, "s": 6218, "text": "It also specifies the language running on the Lambda as Python3.8, sets a few variables that can be accessed in our lambda code, and configures the API Gateway endpoint." }, { "code": null, "e": 6425, "s": 6388, "text": "This is where our Lambda code lives." }, { "code": null, "e": 7182, "s": 6425, "text": "import jsonimport sklearnimport boto3import osimport jsonimport pickles3 = boto3.client('s3')s3_bucket = os.environ['s3_bucket']model_name = os.environ['model_name']temp_file_path = '/tmp/' + model_namefrom sklearn.linear_model import LogisticRegressiondef lambda_handler(event, context): # Parse input body = event['body'] input = json.loads(body)['data'] input = float(input ) # Download pickled model from S3 and unpickle s3.download_file(s3_bucket, model_name, temp_file_path) with open(temp_file_path, 'rb') as f: model = pickle.load(f) # Predict class prediction = model.predict([[input]])[0] return { \"statusCode\": 200, \"body\": json.dumps({ \"prediction\": str(prediction), }), }" }, { "code": null, "e": 7312, "s": 7182, "text": "In a nutshell, this imports libraries, pulls your model from S3, parses the input request, classifies it, and returns a response." }, { "code": null, "e": 7409, "s": 7312, "text": "This is where we specify what libraries should be installed on our Lambda. Below is all we need." }, { "code": null, "e": 7430, "s": 7409, "text": "requestsboto3sklearn" }, { "code": null, "e": 7474, "s": 7430, "text": "Now run the following on your command line." }, { "code": null, "e": 7486, "s": 7474, "text": "$ sam build" }, { "code": null, "e": 7577, "s": 7486, "text": "This creates a .aws-sam/build directory, which contains code that will be deployed to AWS." }, { "code": null, "e": 7700, "s": 7577, "text": "Before deploying, let’s make sure the application works locally. Do not continue until you get a successful response here." }, { "code": null, "e": 7740, "s": 7700, "text": "Run below to provision the app locally." }, { "code": null, "e": 7762, "s": 7740, "text": "$ sam local start-api" }, { "code": null, "e": 7796, "s": 7762, "text": "Now hit the endpoint with a curl." }, { "code": null, "e": 7897, "s": 7796, "text": "$ curl -XPOST http://127.0.0.1:3000/classify -H 'Content-Type: application/json' -d '{\"data\":\".10\"}'" }, { "code": null, "e": 7934, "s": 7897, "text": "The response should look like below." }, { "code": null, "e": 7954, "s": 7934, "text": "{\"prediction\": \"1\"}" }, { "code": null, "e": 8001, "s": 7954, "text": "If you’re response looks like above, continue!" }, { "code": null, "e": 8040, "s": 8001, "text": "cd into the .aws-sam/build/ directory." }, { "code": null, "e": 8064, "s": 8040, "text": "$ cd .aws-sam$ cd build" }, { "code": null, "e": 8183, "s": 8064, "text": "Now run below. This creates a zip file with dependencies that will be deployed (in a moment). This will take a minute." }, { "code": null, "e": 8262, "s": 8183, "text": "Note: I’m using the name of my S3 bucket but you should use the name of yours." }, { "code": null, "e": 8377, "s": 8262, "text": "$ sam package --template-file template.yaml --s3-bucket lambda-app-bucket-123 --output-template-file packaged.yaml" }, { "code": null, "e": 8420, "s": 8377, "text": "Then run below to deploy your application." }, { "code": null, "e": 8525, "s": 8420, "text": "$ sam deploy --template-file packaged.yaml --stack-name SklearnLambdaStack --capabilities CAPABILITY_IAM" }, { "code": null, "e": 8596, "s": 8525, "text": "You should get a confirmation that your application has been deployed." }, { "code": null, "e": 8669, "s": 8596, "text": "In the previous response from deployment, you’ll be provided with a URL." }, { "code": null, "e": 8802, "s": 8669, "text": "If everything worked, sending a request to this URL should return the same response as making a request to your app running locally." }, { "code": null, "e": 8942, "s": 8802, "text": "$ curl -XPOST https://6lsk6c6vw2.execute-api.us-east-1.amazonaws.com/Prod/classify/ -H 'Content-Type: application/json' -d '{\"data\":\".10\"}'" }, { "code": null, "e": 8970, "s": 8942, "text": "So the above should return." }, { "code": null, "e": 8990, "s": 8970, "text": "{\"prediction\": \"1\"}" }, { "code": null, "e": 9061, "s": 8990, "text": "Congratulations! You’ve deployed your first serverless ML application!" }, { "code": null, "e": 9150, "s": 9061, "text": "As you can see, deploying ML on serverless architecture is anything but straightforward." }, { "code": null, "e": 9301, "s": 9150, "text": "The example we walked through is about as simple as it gets; we even skipped API authentication because I didn’t want to detract from the core lesson." }, { "code": null, "e": 9421, "s": 9301, "text": "There aren’t many great examples on productionizing serverless ML, so I hope this helps speed up your learning process." }, { "code": null, "e": 9586, "s": 9421, "text": "I fully expect we’ll see more and better tool for productionizing ML in future. But until then, infrastructure is going to be tightly coupled with model deployment." } ]
What is the base class for all data types in C#.NET?
Object is the base class for all data types in C#. The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object is an alias for System.Object class. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. The following is an example showing the usage of object data types − using System; using System.IO; namespace Demo { class objectClass { public int x = 56; } class MyApplication { static void Main() { object obj; obj = 96; Console.WriteLine(obj); obj = new objectClass(); objectClass newRef; newRef = (objectClass)obj; Console.WriteLine(newRef.x); } } }
[ { "code": null, "e": 1255, "s": 1062, "text": "Object is the base class for all data types in C#. The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object is an alias for System.Object class." }, { "code": null, "e": 1418, "s": 1255, "text": "When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing." }, { "code": null, "e": 1487, "s": 1418, "text": "The following is an example showing the usage of object data types −" }, { "code": null, "e": 1869, "s": 1487, "text": "using System;\nusing System.IO;\n\nnamespace Demo {\n class objectClass {\n public int x = 56;\n }\n\n class MyApplication {\n static void Main() {\n object obj;\n obj = 96;\n Console.WriteLine(obj);\n obj = new objectClass();\n objectClass newRef;\n newRef = (objectClass)obj;\n Console.WriteLine(newRef.x);\n }\n } \n}" } ]
What is Conditional Operator (?:) in JavaScript?
The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. You can try to run the following code to understand how Ternary Operator works in JavaScript − <html> <body> <script> var a =10; var b =20; varlinebreak = "<br />"; document.write ("((a > b) ? 100 : 200) => "); result =(a > b) ? 100 : 200; document.write(result); document.write(linebreak); document.write ("((a < b) ? 100 : 200) => "); result =(a < b) ? 100 : 200; document.write(result); document.write(linebreak); </script> </body> </html>
[ { "code": null, "e": 1258, "s": 1062, "text": "The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation." }, { "code": null, "e": 1353, "s": 1258, "text": "You can try to run the following code to understand how Ternary Operator works in JavaScript −" }, { "code": null, "e": 1820, "s": 1353, "text": "<html>\n <body>\n <script>\n var a =10;\n var b =20;\n varlinebreak = \"<br />\";\n\n document.write (\"((a > b) ? 100 : 200) => \");\n result =(a > b) ? 100 : 200;\n document.write(result);\n document.write(linebreak);\n\n document.write (\"((a < b) ? 100 : 200) => \");\n result =(a < b) ? 100 : 200;\n document.write(result);\n document.write(linebreak);\n </script>\n </body>\n</html>" } ]
VB.Net - OpenFileDialog Control
The OpenFileDialog control prompts the user to open a file and allows the user to select a file to open. The user can check if the file exists and then open it. The OpenFileDialog control class inherits from the abstract class FileDialog. If the ShowReadOnly property is set to True, then a read-only check box appears in the dialog box. You can also set the ReadOnlyChecked property to True, so that the read-only check box appears checked. Following is the Open File dialog box − The following are some of the commonly used properties of the OpenFileDialog control − AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension. AutoUpgradeEnabled Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista. CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist. CustomPlaces Gets the custom places collection for this FileDialog instance. DefaultExt Gets or sets the default file name extension. DereferenceLinks Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk). FileName Gets or sets a string containing the file name selected in the file dialog box. FileNames Gets the file names of all selected files in the dialog box. Filter Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box. FilterIndex Gets or sets the index of the filter currently selected in the file dialog box. InitialDirectory Gets or sets the initial directory displayed by the file dialog box. Multiselect Gets or sets a value indicating whether the dialog box allows multiple files to be selected. ReadOnlyChecked Gets or sets a value indicating whether the read-only check box is selected. RestoreDirectory Gets or sets a value indicating whether the dialog box restores the current directory before closing. SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path. SafeFileNames Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path. ShowHelp Gets or sets a value indicating whether the Help button is displayed in the file dialog box. ShowReadOnly Gets or sets a value indicating whether the dialog box contains a read-only check box. SupportMultiDottedExtensions Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions. Title Gets or sets the file dialog box title. ValidateNames Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names. The following are some of the commonly used methods of the OpenFileDialog control − OpenFile Opens the file selected by the user, with read-only permission. The file is specified by the FileName property. Reset Resets all options to their default value. In this example, let's load an image file in a picture box, using the open file dialog box. Take the following steps − Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form. Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form. Set the Text property of the button control to 'Load Image File'. Set the Text property of the button control to 'Load Image File'. Double-click the Load Image File button and modify the code of the Click event: Double-click the Load Image File button and modify the code of the Click event: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName) End If End Sub When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − Click on the Load Image File button to load an image stored in your computer. 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2539, "s": 2300, "text": "The OpenFileDialog control prompts the user to open a file and allows the user to select a file to open. The user can check if the file exists and then open it. The OpenFileDialog control class inherits from the abstract class FileDialog." }, { "code": null, "e": 2742, "s": 2539, "text": "If the ShowReadOnly property is set to True, then a read-only check box appears in the dialog box. You can also set the ReadOnlyChecked property to True, so that the read-only check box appears checked." }, { "code": null, "e": 2782, "s": 2742, "text": "Following is the Open File dialog box −" }, { "code": null, "e": 2869, "s": 2782, "text": "The following are some of the commonly used properties of the OpenFileDialog control −" }, { "code": null, "e": 2882, "s": 2869, "text": "AddExtension" }, { "code": null, "e": 3017, "s": 2882, "text": "Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension." }, { "code": null, "e": 3036, "s": 3017, "text": "AutoUpgradeEnabled" }, { "code": null, "e": 3185, "s": 3036, "text": "Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista." }, { "code": null, "e": 3201, "s": 3185, "text": "CheckFileExists" }, { "code": null, "e": 3330, "s": 3201, "text": "Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist." }, { "code": null, "e": 3346, "s": 3330, "text": "CheckPathExists" }, { "code": null, "e": 3470, "s": 3346, "text": "Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist." }, { "code": null, "e": 3483, "s": 3470, "text": "CustomPlaces" }, { "code": null, "e": 3547, "s": 3483, "text": "Gets the custom places collection for this FileDialog instance." }, { "code": null, "e": 3558, "s": 3547, "text": "DefaultExt" }, { "code": null, "e": 3604, "s": 3558, "text": "Gets or sets the default file name extension." }, { "code": null, "e": 3621, "s": 3604, "text": "DereferenceLinks" }, { "code": null, "e": 3795, "s": 3621, "text": "Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk)." }, { "code": null, "e": 3804, "s": 3795, "text": "FileName" }, { "code": null, "e": 3884, "s": 3804, "text": "Gets or sets a string containing the file name selected in the file dialog box." }, { "code": null, "e": 3894, "s": 3884, "text": "FileNames" }, { "code": null, "e": 3955, "s": 3894, "text": "Gets the file names of all selected files in the dialog box." }, { "code": null, "e": 3962, "s": 3955, "text": "Filter" }, { "code": null, "e": 4122, "s": 3962, "text": "Gets or sets the current file name filter string, which determines the choices that appear in the \"Save as file type\" or \"Files of type\" box in the dialog box." }, { "code": null, "e": 4134, "s": 4122, "text": "FilterIndex" }, { "code": null, "e": 4214, "s": 4134, "text": "Gets or sets the index of the filter currently selected in the file dialog box." }, { "code": null, "e": 4231, "s": 4214, "text": "InitialDirectory" }, { "code": null, "e": 4300, "s": 4231, "text": "Gets or sets the initial directory displayed by the file dialog box." }, { "code": null, "e": 4312, "s": 4300, "text": "Multiselect" }, { "code": null, "e": 4405, "s": 4312, "text": "Gets or sets a value indicating whether the dialog box allows multiple files to be selected." }, { "code": null, "e": 4421, "s": 4405, "text": "ReadOnlyChecked" }, { "code": null, "e": 4498, "s": 4421, "text": "Gets or sets a value indicating whether the read-only check box is selected." }, { "code": null, "e": 4515, "s": 4498, "text": "RestoreDirectory" }, { "code": null, "e": 4617, "s": 4515, "text": "Gets or sets a value indicating whether the dialog box restores the current directory before closing." }, { "code": null, "e": 4630, "s": 4617, "text": "SafeFileName" }, { "code": null, "e": 4745, "s": 4630, "text": "Gets the file name and extension for the file selected in the dialog box. The file name does not include the path." }, { "code": null, "e": 4759, "s": 4745, "text": "SafeFileNames" }, { "code": null, "e": 4888, "s": 4759, "text": "Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path." }, { "code": null, "e": 4897, "s": 4888, "text": "ShowHelp" }, { "code": null, "e": 4990, "s": 4897, "text": "Gets or sets a value indicating whether the Help button is displayed in the file dialog box." }, { "code": null, "e": 5003, "s": 4990, "text": "ShowReadOnly" }, { "code": null, "e": 5090, "s": 5003, "text": "Gets or sets a value indicating whether the dialog box contains a read-only check box." }, { "code": null, "e": 5119, "s": 5090, "text": "SupportMultiDottedExtensions" }, { "code": null, "e": 5233, "s": 5119, "text": "Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions." }, { "code": null, "e": 5239, "s": 5233, "text": "Title" }, { "code": null, "e": 5279, "s": 5239, "text": "Gets or sets the file dialog box title." }, { "code": null, "e": 5293, "s": 5279, "text": "ValidateNames" }, { "code": null, "e": 5385, "s": 5293, "text": "Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names." }, { "code": null, "e": 5469, "s": 5385, "text": "The following are some of the commonly used methods of the OpenFileDialog control −" }, { "code": null, "e": 5478, "s": 5469, "text": "OpenFile" }, { "code": null, "e": 5590, "s": 5478, "text": "Opens the file selected by the user, with read-only permission. The file is specified by the FileName property." }, { "code": null, "e": 5596, "s": 5590, "text": "Reset" }, { "code": null, "e": 5639, "s": 5596, "text": "Resets all options to their default value." }, { "code": null, "e": 5758, "s": 5639, "text": "In this example, let's load an image file in a picture box, using the open file dialog box. Take the following steps −" }, { "code": null, "e": 5853, "s": 5758, "text": "Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form." }, { "code": null, "e": 5948, "s": 5853, "text": "Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form." }, { "code": null, "e": 6014, "s": 5948, "text": "Set the Text property of the button control to 'Load Image File'." }, { "code": null, "e": 6080, "s": 6014, "text": "Set the Text property of the button control to 'Load Image File'." }, { "code": null, "e": 6161, "s": 6080, "text": "Double-click the Load Image File button and modify the code of the Click event:\n" }, { "code": null, "e": 6241, "s": 6161, "text": "Double-click the Load Image File button and modify the code of the Click event:" }, { "code": null, "e": 6483, "s": 6241, "text": "Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then\n PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)\n End If\nEnd Sub" }, { "code": null, "e": 6630, "s": 6483, "text": "When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −" }, { "code": null, "e": 6708, "s": 6630, "text": "Click on the Load Image File button to load an image stored in your computer." }, { "code": null, "e": 6741, "s": 6708, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 6758, "s": 6741, "text": " Frahaan Hussain" }, { "code": null, "e": 6793, "s": 6758, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 6808, "s": 6793, "text": " Arnold Higuit" }, { "code": null, "e": 6843, "s": 6808, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6858, "s": 6843, "text": " Arnold Higuit" }, { "code": null, "e": 6891, "s": 6858, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 6906, "s": 6891, "text": " Arnold Higuit" }, { "code": null, "e": 6913, "s": 6906, "text": " Print" }, { "code": null, "e": 6924, "s": 6913, "text": " Add Notes" } ]
Get value of an input box using Selenium (Python)
We can get the value of an input box with Selenium webdriver. The get_attribute() method is capable of obtaining the value we have entered in an input box. To get the value, we have to pass value as a parameter to the method. First of all, we have to identify the input box with the help of any of the locators like id, class, name, css or xpath. Then we have to type some values inside it with the send_keys() method. Let us consider the below input box where we shall enter some texts - Selenium Python and then fetch the value with get_attribute(). from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.google.com/") #identify element l= driver.find_element_by_name("q") l.send_keys("q") #get_attribute() to get value of input box print("Value of input box: " + l.get_attribute('value')) driver.close()
[ { "code": null, "e": 1288, "s": 1062, "text": "We can get the value of an input box with Selenium webdriver. The get_attribute() method is capable of obtaining the value we have entered in an input box. To get the value, we have to pass value as a parameter to the method." }, { "code": null, "e": 1481, "s": 1288, "text": "First of all, we have to identify the input box with the help of any of the locators like id, class, name, css or xpath. Then we have to type some values inside it with the send_keys() method." }, { "code": null, "e": 1614, "s": 1481, "text": "Let us consider the below input box where we shall enter some texts - Selenium Python and then fetch the value with get_attribute()." }, { "code": null, "e": 1963, "s": 1614, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.google.com/\")\n#identify element\nl= driver.find_element_by_name(\"q\")\nl.send_keys(\"q\")\n#get_attribute() to get value of input box\nprint(\"Value of input box: \" + l.get_attribute('value'))\ndriver.close()" } ]
Binary Heap - GeeksforGeeks
15 Nov, 2021 A Binary Heap is a Binary Tree with following properties.1) It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array. 2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap. Examples of Min Heap: 10 10 / \ / \ 20 100 15 30 / / \ / \ 30 40 50 100 40 How is Binary Heap represented?A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as an array. The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:Arr[(i-1)/2]Returns the parent nodeArr[(2*i)+1]Returns the left child nodeArr[(2*i)+2]Returns the right child nodeThe traversal method use to achieve Array representation is Level OrderPlease refer Array Representation Of Binary Heap for details.Applications of Heaps:1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently.3) Graph Algorithms: The priority queues are especially used in Graph Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree.4) Many problems can be efficiently solved using Heaps. See following for example.a) K’th Largest Element in an array.b) Sort an almost sorted array/c) Merge K Sorted Arrays.Operations on Min Heap:1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root.3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the decreases key value of a node is greater than the parent of the node, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove the key.Below is the implementation of basic heap operations.C++PythonC#C++// A C++ program to demonstrate common Binary Heap Operations#include<iostream>#include<climits>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int *x, int *y); // A class for Min Heapclass MinHeap{ int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: // Constructor MinHeap(int capacity); // to heapify a subtree with the root at given index void MinHeapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of node at index i int left(int i) { return (2*i + 1); } // to get index of right child of node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the minimum element int extractMin(); // Decreases key value of key at index i to new_val void decreaseKey(int i, int new_val); // Returns the minimum key (key at root) from min heap int getMin() { return harr[0]; } // Deletes a key stored at index i void deleteKey(int i); // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from a given array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Decreases value of key at index 'i' to new_val. It is assumed that// new_val is smaller than harr[i].void MinHeap::decreaseKey(int i, int new_val){ harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; MinHeapify(0); return root;} // This function deletes key at index i. It first reduced value to minus// infinite, then calls extractMin()void MinHeap::deleteKey(int i){ decreaseKey(i, INT_MIN); extractMin();} // A recursive method to heapify a subtree with the root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;} // Driver program to test above functionsint main(){ MinHeap h(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); cout << h.extractMin() << " "; cout << h.getMin() << " "; h.decreaseKey(2, 1); cout << h.getMin(); return 0;}Python# A Python program to demonstrate common binary heap operations # Import the heap functions from python libraryfrom heapq import heappush, heappop, heapify # heappop - pop and return the smallest element from heap# heappush - push the value item onto the heap, maintaining# heap invarient# heapify - transform list into heap, in place, in linear time # A class for Min Heapclass MinHeap: # Constructor to initialize a heap def __init__(self): self.heap = [] def parent(self, i): return (i-1)/2 # Inserts a new key 'k' def insertKey(self, k): heappush(self.heap, k) # Decrease value of key at index 'i' to new_val # It is assumed that new_val is smaller than heap[i] def decreaseKey(self, i, new_val): self.heap[i] = new_val while(i != 0 and self.heap[self.parent(i)] > self.heap[i]): # Swap heap[i] with heap[parent(i)] self.heap[i] , self.heap[self.parent(i)] = ( self.heap[self.parent(i)], self.heap[i]) # Method to remove minium element from min heap def extractMin(self): return heappop(self.heap) # This functon deletes key at index i. It first reduces # value to minus infinite and then calls extractMin() def deleteKey(self, i): self.decreaseKey(i, float("-inf")) self.extractMin() # Get the minimum element from the heap def getMin(self): return self.heap[0] # Driver pgoratm to test above functionheapObj = MinHeap()heapObj.insertKey(3)heapObj.insertKey(2)heapObj.deleteKey(1)heapObj.insertKey(15)heapObj.insertKey(5)heapObj.insertKey(4)heapObj.insertKey(45) print heapObj.extractMin(),print heapObj.getMin(),heapObj.decreaseKey(2, 1)print heapObj.getMin() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)C#// C# program to demonstrate common // Binary Heap Operations - Min Heapusing System; // A class for Min Heap class MinHeap{ // To store array of elements in heappublic int[] heapArray{ get; set; } // max size of the heappublic int capacity{ get; set; } // Current number of elements in the heappublic int current_heap_size{ get; set; } // Constructor public MinHeap(int n){ capacity = n; heapArray = new int[capacity]; current_heap_size = 0;} // Swapping using reference public static void Swap<T>(ref T lhs, ref T rhs){ T temp = lhs; lhs = rhs; rhs = temp;} // Get the Parent index for the given indexpublic int Parent(int key) { return (key - 1) / 2;} // Get the Left Child index for the given indexpublic int Left(int key){ return 2 * key + 1;} // Get the Right Child index for the given indexpublic int Right(int key){ return 2 * key + 2;} // Inserts a new keypublic bool insertKey(int key){ if (current_heap_size == capacity) { // heap is full return false; } // First insert the new key at the end int i = current_heap_size; heapArray[i] = key; current_heap_size++; // Fix the min heap property if it is violated while (i != 0 && heapArray[i] < heapArray[Parent(i)]) { Swap(ref heapArray[i], ref heapArray[Parent(i)]); i = Parent(i); } return true;} // Decreases value of given key to new_val. // It is assumed that new_val is smaller // than heapArray[key]. public void decreaseKey(int key, int new_val){ heapArray[key] = new_val; while (key != 0 && heapArray[key] < heapArray[Parent(key)]) { Swap(ref heapArray[key], ref heapArray[Parent(key)]); key = Parent(key); }} // Returns the minimum key (key at// root) from min heap public int getMin(){ return heapArray[0];} // Method to remove minimum element // (or root) from min heap public int extractMin(){ if (current_heap_size <= 0) { return int.MaxValue; } if (current_heap_size == 1) { current_heap_size--; return heapArray[0]; } // Store the minimum value, // and remove it from heap int root = heapArray[0]; heapArray[0] = heapArray[current_heap_size - 1]; current_heap_size--; MinHeapify(0); return root;} // This function deletes key at the // given index. It first reduced value // to minus infinite, then calls extractMin()public void deleteKey(int key){ decreaseKey(key, int.MinValue); extractMin();} // A recursive method to heapify a subtree // with the root at given index // This method assumes that the subtrees// are already heapifiedpublic void MinHeapify(int key){ int l = Left(key); int r = Right(key); int smallest = key; if (l < current_heap_size && heapArray[l] < heapArray[smallest]) { smallest = l; } if (r < current_heap_size && heapArray[r] < heapArray[smallest]) { smallest = r; } if (smallest != key) { Swap(ref heapArray[key], ref heapArray[smallest]); MinHeapify(smallest); }} // Increases value of given key to new_val.// It is assumed that new_val is greater // than heapArray[key]. // Heapify from the given keypublic void increaseKey(int key, int new_val){ heapArray[key] = new_val; MinHeapify(key);} // Changes value on a keypublic void changeValueOnAKey(int key, int new_val){ if (heapArray[key] == new_val) { return; } if (heapArray[key] < new_val) { increaseKey(key, new_val); } else { decreaseKey(key, new_val); }}} static class MinHeapTest{ // Driver codepublic static void Main(string[] args){ MinHeap h = new MinHeap(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); Console.Write(h.extractMin() + " "); Console.Write(h.getMin() + " "); h.decreaseKey(2, 1); Console.Write(h.getMin());}} // This code is contributed by // Dinesh Clinton Albert(dineshclinton)Output:2 4 1YouTubeGeeksforGeeks506K subscribersBinary Heap | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uZj0hetLFHU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Coding Practice on HeapAll Articles on HeapQuiz on HeapPriorityQueue : Binary Heap Implementation in Java LibraryPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave The traversal method use to achieve Array representation is Level Order Please refer Array Representation Of Binary Heap for details. Applications of Heaps:1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time. 2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently. 3) Graph Algorithms: The priority queues are especially used in Graph Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree. 4) Many problems can be efficiently solved using Heaps. See following for example.a) K’th Largest Element in an array.b) Sort an almost sorted array/c) Merge K Sorted Arrays. Operations on Min Heap:1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1). 2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root. 3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the decreases key value of a node is greater than the parent of the node, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property. 4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property. 5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove the key. Below is the implementation of basic heap operations. C++ Python C# // A C++ program to demonstrate common Binary Heap Operations#include<iostream>#include<climits>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int *x, int *y); // A class for Min Heapclass MinHeap{ int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: // Constructor MinHeap(int capacity); // to heapify a subtree with the root at given index void MinHeapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of node at index i int left(int i) { return (2*i + 1); } // to get index of right child of node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the minimum element int extractMin(); // Decreases key value of key at index i to new_val void decreaseKey(int i, int new_val); // Returns the minimum key (key at root) from min heap int getMin() { return harr[0]; } // Deletes a key stored at index i void deleteKey(int i); // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from a given array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Decreases value of key at index 'i' to new_val. It is assumed that// new_val is smaller than harr[i].void MinHeap::decreaseKey(int i, int new_val){ harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; MinHeapify(0); return root;} // This function deletes key at index i. It first reduced value to minus// infinite, then calls extractMin()void MinHeap::deleteKey(int i){ decreaseKey(i, INT_MIN); extractMin();} // A recursive method to heapify a subtree with the root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;} // Driver program to test above functionsint main(){ MinHeap h(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); cout << h.extractMin() << " "; cout << h.getMin() << " "; h.decreaseKey(2, 1); cout << h.getMin(); return 0;} # A Python program to demonstrate common binary heap operations # Import the heap functions from python libraryfrom heapq import heappush, heappop, heapify # heappop - pop and return the smallest element from heap# heappush - push the value item onto the heap, maintaining# heap invarient# heapify - transform list into heap, in place, in linear time # A class for Min Heapclass MinHeap: # Constructor to initialize a heap def __init__(self): self.heap = [] def parent(self, i): return (i-1)/2 # Inserts a new key 'k' def insertKey(self, k): heappush(self.heap, k) # Decrease value of key at index 'i' to new_val # It is assumed that new_val is smaller than heap[i] def decreaseKey(self, i, new_val): self.heap[i] = new_val while(i != 0 and self.heap[self.parent(i)] > self.heap[i]): # Swap heap[i] with heap[parent(i)] self.heap[i] , self.heap[self.parent(i)] = ( self.heap[self.parent(i)], self.heap[i]) # Method to remove minium element from min heap def extractMin(self): return heappop(self.heap) # This functon deletes key at index i. It first reduces # value to minus infinite and then calls extractMin() def deleteKey(self, i): self.decreaseKey(i, float("-inf")) self.extractMin() # Get the minimum element from the heap def getMin(self): return self.heap[0] # Driver pgoratm to test above functionheapObj = MinHeap()heapObj.insertKey(3)heapObj.insertKey(2)heapObj.deleteKey(1)heapObj.insertKey(15)heapObj.insertKey(5)heapObj.insertKey(4)heapObj.insertKey(45) print heapObj.extractMin(),print heapObj.getMin(),heapObj.decreaseKey(2, 1)print heapObj.getMin() # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to demonstrate common // Binary Heap Operations - Min Heapusing System; // A class for Min Heap class MinHeap{ // To store array of elements in heappublic int[] heapArray{ get; set; } // max size of the heappublic int capacity{ get; set; } // Current number of elements in the heappublic int current_heap_size{ get; set; } // Constructor public MinHeap(int n){ capacity = n; heapArray = new int[capacity]; current_heap_size = 0;} // Swapping using reference public static void Swap<T>(ref T lhs, ref T rhs){ T temp = lhs; lhs = rhs; rhs = temp;} // Get the Parent index for the given indexpublic int Parent(int key) { return (key - 1) / 2;} // Get the Left Child index for the given indexpublic int Left(int key){ return 2 * key + 1;} // Get the Right Child index for the given indexpublic int Right(int key){ return 2 * key + 2;} // Inserts a new keypublic bool insertKey(int key){ if (current_heap_size == capacity) { // heap is full return false; } // First insert the new key at the end int i = current_heap_size; heapArray[i] = key; current_heap_size++; // Fix the min heap property if it is violated while (i != 0 && heapArray[i] < heapArray[Parent(i)]) { Swap(ref heapArray[i], ref heapArray[Parent(i)]); i = Parent(i); } return true;} // Decreases value of given key to new_val. // It is assumed that new_val is smaller // than heapArray[key]. public void decreaseKey(int key, int new_val){ heapArray[key] = new_val; while (key != 0 && heapArray[key] < heapArray[Parent(key)]) { Swap(ref heapArray[key], ref heapArray[Parent(key)]); key = Parent(key); }} // Returns the minimum key (key at// root) from min heap public int getMin(){ return heapArray[0];} // Method to remove minimum element // (or root) from min heap public int extractMin(){ if (current_heap_size <= 0) { return int.MaxValue; } if (current_heap_size == 1) { current_heap_size--; return heapArray[0]; } // Store the minimum value, // and remove it from heap int root = heapArray[0]; heapArray[0] = heapArray[current_heap_size - 1]; current_heap_size--; MinHeapify(0); return root;} // This function deletes key at the // given index. It first reduced value // to minus infinite, then calls extractMin()public void deleteKey(int key){ decreaseKey(key, int.MinValue); extractMin();} // A recursive method to heapify a subtree // with the root at given index // This method assumes that the subtrees// are already heapifiedpublic void MinHeapify(int key){ int l = Left(key); int r = Right(key); int smallest = key; if (l < current_heap_size && heapArray[l] < heapArray[smallest]) { smallest = l; } if (r < current_heap_size && heapArray[r] < heapArray[smallest]) { smallest = r; } if (smallest != key) { Swap(ref heapArray[key], ref heapArray[smallest]); MinHeapify(smallest); }} // Increases value of given key to new_val.// It is assumed that new_val is greater // than heapArray[key]. // Heapify from the given keypublic void increaseKey(int key, int new_val){ heapArray[key] = new_val; MinHeapify(key);} // Changes value on a keypublic void changeValueOnAKey(int key, int new_val){ if (heapArray[key] == new_val) { return; } if (heapArray[key] < new_val) { increaseKey(key, new_val); } else { decreaseKey(key, new_val); }}} static class MinHeapTest{ // Driver codepublic static void Main(string[] args){ MinHeap h = new MinHeap(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); Console.Write(h.extractMin() + " "); Console.Write(h.getMin() + " "); h.decreaseKey(2, 1); Console.Write(h.getMin());}} // This code is contributed by // Dinesh Clinton Albert(dineshclinton) 2 4 1 YouTubeGeeksforGeeks506K subscribersBinary Heap | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uZj0hetLFHU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Coding Practice on HeapAll Articles on HeapQuiz on HeapPriorityQueue : Binary Heap Implementation in Java Library Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. dineshclinton Heap Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array Building Heap from Array Insertion and Deletion in Heaps Max Heap in Java Sliding Window Maximum (Maximum of all subarrays of size k) Priority Queue in Python Merge k sorted arrays | Set 1 Priority Queue using Binary Heap
[ { "code": null, "e": 39115, "s": 39087, "text": "\n15 Nov, 2021" }, { "code": null, "e": 39390, "s": 39115, "text": "A Binary Heap is a Binary Tree with following properties.1) It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array." }, { "code": null, "e": 39644, "s": 39390, "text": "2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap." }, { "code": null, "e": 39666, "s": 39644, "text": "Examples of Min Heap:" }, { "code": null, "e": 39890, "s": 39666, "text": " 10 10\n / \\ / \\ \n 20 100 15 30 \n / / \\ / \\\n 30 40 50 100 40\n" }, { "code": null, "e": 40014, "s": 39890, "text": "How is Binary Heap represented?A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as an array." }, { "code": null, "e": 40050, "s": 40014, "text": "The root element will be at Arr[0]." }, { "code": null, "e": 52823, "s": 40050, "text": "Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:Arr[(i-1)/2]Returns the parent nodeArr[(2*i)+1]Returns the left child nodeArr[(2*i)+2]Returns the right child nodeThe traversal method use to achieve Array representation is Level OrderPlease refer Array Representation Of Binary Heap for details.Applications of Heaps:1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently.3) Graph Algorithms: The priority queues are especially used in Graph Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree.4) Many problems can be efficiently solved using Heaps. See following for example.a) K’th Largest Element in an array.b) Sort an almost sorted array/c) Merge K Sorted Arrays.Operations on Min Heap:1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root.3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the decreases key value of a node is greater than the parent of the node, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove the key.Below is the implementation of basic heap operations.C++PythonC#C++// A C++ program to demonstrate common Binary Heap Operations#include<iostream>#include<climits>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int *x, int *y); // A class for Min Heapclass MinHeap{ int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: // Constructor MinHeap(int capacity); // to heapify a subtree with the root at given index void MinHeapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of node at index i int left(int i) { return (2*i + 1); } // to get index of right child of node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the minimum element int extractMin(); // Decreases key value of key at index i to new_val void decreaseKey(int i, int new_val); // Returns the minimum key (key at root) from min heap int getMin() { return harr[0]; } // Deletes a key stored at index i void deleteKey(int i); // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from a given array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << \"\\nOverflow: Could not insertKey\\n\"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Decreases value of key at index 'i' to new_val. It is assumed that// new_val is smaller than harr[i].void MinHeap::decreaseKey(int i, int new_val){ harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; MinHeapify(0); return root;} // This function deletes key at index i. It first reduced value to minus// infinite, then calls extractMin()void MinHeap::deleteKey(int i){ decreaseKey(i, INT_MIN); extractMin();} // A recursive method to heapify a subtree with the root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;} // Driver program to test above functionsint main(){ MinHeap h(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); cout << h.extractMin() << \" \"; cout << h.getMin() << \" \"; h.decreaseKey(2, 1); cout << h.getMin(); return 0;}Python# A Python program to demonstrate common binary heap operations # Import the heap functions from python libraryfrom heapq import heappush, heappop, heapify # heappop - pop and return the smallest element from heap# heappush - push the value item onto the heap, maintaining# heap invarient# heapify - transform list into heap, in place, in linear time # A class for Min Heapclass MinHeap: # Constructor to initialize a heap def __init__(self): self.heap = [] def parent(self, i): return (i-1)/2 # Inserts a new key 'k' def insertKey(self, k): heappush(self.heap, k) # Decrease value of key at index 'i' to new_val # It is assumed that new_val is smaller than heap[i] def decreaseKey(self, i, new_val): self.heap[i] = new_val while(i != 0 and self.heap[self.parent(i)] > self.heap[i]): # Swap heap[i] with heap[parent(i)] self.heap[i] , self.heap[self.parent(i)] = ( self.heap[self.parent(i)], self.heap[i]) # Method to remove minium element from min heap def extractMin(self): return heappop(self.heap) # This functon deletes key at index i. It first reduces # value to minus infinite and then calls extractMin() def deleteKey(self, i): self.decreaseKey(i, float(\"-inf\")) self.extractMin() # Get the minimum element from the heap def getMin(self): return self.heap[0] # Driver pgoratm to test above functionheapObj = MinHeap()heapObj.insertKey(3)heapObj.insertKey(2)heapObj.deleteKey(1)heapObj.insertKey(15)heapObj.insertKey(5)heapObj.insertKey(4)heapObj.insertKey(45) print heapObj.extractMin(),print heapObj.getMin(),heapObj.decreaseKey(2, 1)print heapObj.getMin() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)C#// C# program to demonstrate common // Binary Heap Operations - Min Heapusing System; // A class for Min Heap class MinHeap{ // To store array of elements in heappublic int[] heapArray{ get; set; } // max size of the heappublic int capacity{ get; set; } // Current number of elements in the heappublic int current_heap_size{ get; set; } // Constructor public MinHeap(int n){ capacity = n; heapArray = new int[capacity]; current_heap_size = 0;} // Swapping using reference public static void Swap<T>(ref T lhs, ref T rhs){ T temp = lhs; lhs = rhs; rhs = temp;} // Get the Parent index for the given indexpublic int Parent(int key) { return (key - 1) / 2;} // Get the Left Child index for the given indexpublic int Left(int key){ return 2 * key + 1;} // Get the Right Child index for the given indexpublic int Right(int key){ return 2 * key + 2;} // Inserts a new keypublic bool insertKey(int key){ if (current_heap_size == capacity) { // heap is full return false; } // First insert the new key at the end int i = current_heap_size; heapArray[i] = key; current_heap_size++; // Fix the min heap property if it is violated while (i != 0 && heapArray[i] < heapArray[Parent(i)]) { Swap(ref heapArray[i], ref heapArray[Parent(i)]); i = Parent(i); } return true;} // Decreases value of given key to new_val. // It is assumed that new_val is smaller // than heapArray[key]. public void decreaseKey(int key, int new_val){ heapArray[key] = new_val; while (key != 0 && heapArray[key] < heapArray[Parent(key)]) { Swap(ref heapArray[key], ref heapArray[Parent(key)]); key = Parent(key); }} // Returns the minimum key (key at// root) from min heap public int getMin(){ return heapArray[0];} // Method to remove minimum element // (or root) from min heap public int extractMin(){ if (current_heap_size <= 0) { return int.MaxValue; } if (current_heap_size == 1) { current_heap_size--; return heapArray[0]; } // Store the minimum value, // and remove it from heap int root = heapArray[0]; heapArray[0] = heapArray[current_heap_size - 1]; current_heap_size--; MinHeapify(0); return root;} // This function deletes key at the // given index. It first reduced value // to minus infinite, then calls extractMin()public void deleteKey(int key){ decreaseKey(key, int.MinValue); extractMin();} // A recursive method to heapify a subtree // with the root at given index // This method assumes that the subtrees// are already heapifiedpublic void MinHeapify(int key){ int l = Left(key); int r = Right(key); int smallest = key; if (l < current_heap_size && heapArray[l] < heapArray[smallest]) { smallest = l; } if (r < current_heap_size && heapArray[r] < heapArray[smallest]) { smallest = r; } if (smallest != key) { Swap(ref heapArray[key], ref heapArray[smallest]); MinHeapify(smallest); }} // Increases value of given key to new_val.// It is assumed that new_val is greater // than heapArray[key]. // Heapify from the given keypublic void increaseKey(int key, int new_val){ heapArray[key] = new_val; MinHeapify(key);} // Changes value on a keypublic void changeValueOnAKey(int key, int new_val){ if (heapArray[key] == new_val) { return; } if (heapArray[key] < new_val) { increaseKey(key, new_val); } else { decreaseKey(key, new_val); }}} static class MinHeapTest{ // Driver codepublic static void Main(string[] args){ MinHeap h = new MinHeap(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); Console.Write(h.extractMin() + \" \"); Console.Write(h.getMin() + \" \"); h.decreaseKey(2, 1); Console.Write(h.getMin());}} // This code is contributed by // Dinesh Clinton Albert(dineshclinton)Output:2 4 1YouTubeGeeksforGeeks506K subscribersBinary Heap | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uZj0hetLFHU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Coding Practice on HeapAll Articles on HeapQuiz on HeapPriorityQueue : Binary Heap Implementation in Java LibraryPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 52895, "s": 52823, "text": "The traversal method use to achieve Array representation is Level Order" }, { "code": null, "e": 52957, "s": 52895, "text": "Please refer Array Representation Of Binary Heap for details." }, { "code": null, "e": 53055, "s": 52957, "text": "Applications of Heaps:1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time." }, { "code": null, "e": 53352, "s": 53055, "text": "2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently." }, { "code": null, "e": 53497, "s": 53352, "text": "3) Graph Algorithms: The priority queues are especially used in Graph Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree." }, { "code": null, "e": 53672, "s": 53497, "text": "4) Many problems can be efficiently solved using Heaps. See following for example.a) K’th Largest Element in an array.b) Sort an almost sorted array/c) Merge K Sorted Arrays." }, { "code": null, "e": 53793, "s": 53672, "text": "Operations on Min Heap:1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1)." }, { "code": null, "e": 53995, "s": 53793, "text": "2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root." }, { "code": null, "e": 54268, "s": 53995, "text": "3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the decreases key value of a node is greater than the parent of the node, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property." }, { "code": null, "e": 54505, "s": 54268, "text": "4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property." }, { "code": null, "e": 54743, "s": 54505, "text": "5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove the key." }, { "code": null, "e": 54797, "s": 54743, "text": "Below is the implementation of basic heap operations." }, { "code": null, "e": 54801, "s": 54797, "text": "C++" }, { "code": null, "e": 54808, "s": 54801, "text": "Python" }, { "code": null, "e": 54811, "s": 54808, "text": "C#" }, { "code": "// A C++ program to demonstrate common Binary Heap Operations#include<iostream>#include<climits>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int *x, int *y); // A class for Min Heapclass MinHeap{ int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: // Constructor MinHeap(int capacity); // to heapify a subtree with the root at given index void MinHeapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of node at index i int left(int i) { return (2*i + 1); } // to get index of right child of node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the minimum element int extractMin(); // Decreases key value of key at index i to new_val void decreaseKey(int i, int new_val); // Returns the minimum key (key at root) from min heap int getMin() { return harr[0]; } // Deletes a key stored at index i void deleteKey(int i); // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from a given array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << \"\\nOverflow: Could not insertKey\\n\"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Decreases value of key at index 'i' to new_val. It is assumed that// new_val is smaller than harr[i].void MinHeap::decreaseKey(int i, int new_val){ harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; MinHeapify(0); return root;} // This function deletes key at index i. It first reduced value to minus// infinite, then calls extractMin()void MinHeap::deleteKey(int i){ decreaseKey(i, INT_MIN); extractMin();} // A recursive method to heapify a subtree with the root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;} // Driver program to test above functionsint main(){ MinHeap h(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); cout << h.extractMin() << \" \"; cout << h.getMin() << \" \"; h.decreaseKey(2, 1); cout << h.getMin(); return 0;}", "e": 58347, "s": 54811, "text": null }, { "code": "# A Python program to demonstrate common binary heap operations # Import the heap functions from python libraryfrom heapq import heappush, heappop, heapify # heappop - pop and return the smallest element from heap# heappush - push the value item onto the heap, maintaining# heap invarient# heapify - transform list into heap, in place, in linear time # A class for Min Heapclass MinHeap: # Constructor to initialize a heap def __init__(self): self.heap = [] def parent(self, i): return (i-1)/2 # Inserts a new key 'k' def insertKey(self, k): heappush(self.heap, k) # Decrease value of key at index 'i' to new_val # It is assumed that new_val is smaller than heap[i] def decreaseKey(self, i, new_val): self.heap[i] = new_val while(i != 0 and self.heap[self.parent(i)] > self.heap[i]): # Swap heap[i] with heap[parent(i)] self.heap[i] , self.heap[self.parent(i)] = ( self.heap[self.parent(i)], self.heap[i]) # Method to remove minium element from min heap def extractMin(self): return heappop(self.heap) # This functon deletes key at index i. It first reduces # value to minus infinite and then calls extractMin() def deleteKey(self, i): self.decreaseKey(i, float(\"-inf\")) self.extractMin() # Get the minimum element from the heap def getMin(self): return self.heap[0] # Driver pgoratm to test above functionheapObj = MinHeap()heapObj.insertKey(3)heapObj.insertKey(2)heapObj.deleteKey(1)heapObj.insertKey(15)heapObj.insertKey(5)heapObj.insertKey(4)heapObj.insertKey(45) print heapObj.extractMin(),print heapObj.getMin(),heapObj.decreaseKey(2, 1)print heapObj.getMin() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 60184, "s": 58347, "text": null }, { "code": "// C# program to demonstrate common // Binary Heap Operations - Min Heapusing System; // A class for Min Heap class MinHeap{ // To store array of elements in heappublic int[] heapArray{ get; set; } // max size of the heappublic int capacity{ get; set; } // Current number of elements in the heappublic int current_heap_size{ get; set; } // Constructor public MinHeap(int n){ capacity = n; heapArray = new int[capacity]; current_heap_size = 0;} // Swapping using reference public static void Swap<T>(ref T lhs, ref T rhs){ T temp = lhs; lhs = rhs; rhs = temp;} // Get the Parent index for the given indexpublic int Parent(int key) { return (key - 1) / 2;} // Get the Left Child index for the given indexpublic int Left(int key){ return 2 * key + 1;} // Get the Right Child index for the given indexpublic int Right(int key){ return 2 * key + 2;} // Inserts a new keypublic bool insertKey(int key){ if (current_heap_size == capacity) { // heap is full return false; } // First insert the new key at the end int i = current_heap_size; heapArray[i] = key; current_heap_size++; // Fix the min heap property if it is violated while (i != 0 && heapArray[i] < heapArray[Parent(i)]) { Swap(ref heapArray[i], ref heapArray[Parent(i)]); i = Parent(i); } return true;} // Decreases value of given key to new_val. // It is assumed that new_val is smaller // than heapArray[key]. public void decreaseKey(int key, int new_val){ heapArray[key] = new_val; while (key != 0 && heapArray[key] < heapArray[Parent(key)]) { Swap(ref heapArray[key], ref heapArray[Parent(key)]); key = Parent(key); }} // Returns the minimum key (key at// root) from min heap public int getMin(){ return heapArray[0];} // Method to remove minimum element // (or root) from min heap public int extractMin(){ if (current_heap_size <= 0) { return int.MaxValue; } if (current_heap_size == 1) { current_heap_size--; return heapArray[0]; } // Store the minimum value, // and remove it from heap int root = heapArray[0]; heapArray[0] = heapArray[current_heap_size - 1]; current_heap_size--; MinHeapify(0); return root;} // This function deletes key at the // given index. It first reduced value // to minus infinite, then calls extractMin()public void deleteKey(int key){ decreaseKey(key, int.MinValue); extractMin();} // A recursive method to heapify a subtree // with the root at given index // This method assumes that the subtrees// are already heapifiedpublic void MinHeapify(int key){ int l = Left(key); int r = Right(key); int smallest = key; if (l < current_heap_size && heapArray[l] < heapArray[smallest]) { smallest = l; } if (r < current_heap_size && heapArray[r] < heapArray[smallest]) { smallest = r; } if (smallest != key) { Swap(ref heapArray[key], ref heapArray[smallest]); MinHeapify(smallest); }} // Increases value of given key to new_val.// It is assumed that new_val is greater // than heapArray[key]. // Heapify from the given keypublic void increaseKey(int key, int new_val){ heapArray[key] = new_val; MinHeapify(key);} // Changes value on a keypublic void changeValueOnAKey(int key, int new_val){ if (heapArray[key] == new_val) { return; } if (heapArray[key] < new_val) { increaseKey(key, new_val); } else { decreaseKey(key, new_val); }}} static class MinHeapTest{ // Driver codepublic static void Main(string[] args){ MinHeap h = new MinHeap(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); Console.Write(h.extractMin() + \" \"); Console.Write(h.getMin() + \" \"); h.decreaseKey(2, 1); Console.Write(h.getMin());}} // This code is contributed by // Dinesh Clinton Albert(dineshclinton)", "e": 64323, "s": 60184, "text": null }, { "code": null, "e": 64329, "s": 64323, "text": "2 4 1" }, { "code": null, "e": 65139, "s": 64329, "text": "YouTubeGeeksforGeeks506K subscribersBinary Heap | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uZj0hetLFHU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 65253, "s": 65139, "text": "Coding Practice on HeapAll Articles on HeapQuiz on HeapPriorityQueue : Binary Heap Implementation in Java Library" }, { "code": null, "e": 65378, "s": 65253, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 65392, "s": 65378, "text": "dineshclinton" }, { "code": null, "e": 65397, "s": 65392, "text": "Heap" }, { "code": null, "e": 65402, "s": 65397, "text": "Heap" }, { "code": null, "e": 65500, "s": 65402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 65531, "s": 65500, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 65587, "s": 65531, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 65631, "s": 65587, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 65656, "s": 65631, "text": "Building Heap from Array" }, { "code": null, "e": 65688, "s": 65656, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 65705, "s": 65688, "text": "Max Heap in Java" }, { "code": null, "e": 65765, "s": 65705, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 65790, "s": 65765, "text": "Priority Queue in Python" }, { "code": null, "e": 65820, "s": 65790, "text": "Merge k sorted arrays | Set 1" } ]
Anomaly Detection with Time Series Forecasting | by adithya krishnan | Towards Data Science
Hi, this is a follow-up article on anomaly detection(Link to the previous article: https://medium.com/myntra-engineering/anomaly-detection-with-isolation-forest-visualization-23cd75c281e2 where we did anomaly detection using unsupervised learning). Here we will see about detecting anomalies with time series forecasting. Time series is any data which is associated with time(daily, hourly, monthly etc). For eg: revenue at a store every day is a time series data at a day level. Many use cases like demand estimation, sales forecasting is a typical time series forecasting problem which could be solved by algorithms like SARIMA, LSTM, Holtwinters etc. Time series forecasting helps us in preparing us for future needs by estimating them with the current data. Once we have the forecast we can use that data to detect anomalies on comparing them with actuals. Let’s implement it and look at its pros and cons. Installing and importing libraries for visualization #Installing specific version of plotly to avoid Invalid property for color error in recent version which needs change in layout!pip install plotly==2.7.0import pandas as pdimport numpy as npfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.plotly as pyimport matplotlib.pyplot as pltfrom matplotlib import pyplotimport plotly.graph_objs as goinit_notebook_mode(connected=True)time_series_df=pd.read_csv('../input/time-series-data/time_series_data.csv')time_series_df.head() The order of data here is important and should be **chronological** as we are going to forecast the next point. Convert the load_date column to datetime format and sort the data based on date. time_series_df.load_date = pd.to_datetime(time_series_df.load_date, format='%Y%m%d')time_series_df = time_series_df.sort_values(by="load_date")time_series_df = time_series_df.reset_index(drop=True)time_series_df.head() Extract the values and apply log transform to stabilize the variance in the data or to make it stationary before feeding it to the model. actual_vals = time_series_df.actuals.valuesactual_log = np.log10(actual_vals) Divide the data to train and test with 70 points in test data. First let’s try to apply SARIMA algorithm for forecasting. SARIMA stands for Seasonal Auto Regressive Integrated Moving Average. It has a seasonal parameter which we initialize as 7 due to weekly seasonality of our sales data. Other parameters are p,d,q which are identified based on ACF and PACF plots or ideally we should use the parameters with minimal error in forecasting. More details can be found here: https://people.duke.edu/~rnau/arimrule.htm I m not getting into the problem of getting the right set of parameters here which we will solve later using Auto Arima which allows us to get the best set of parameters in a range with minimal error. Here I m specifying the differencing factor(d) as 1. It helps us to remove trends and cycles in the data. import mathimport statsmodels.api as smimport statsmodels.tsa.api as smtfrom sklearn.metrics import mean_squared_errorfrom matplotlib import pyplotimport matplotlib.pyplot as pltimport plotly.plotly as pyimport plotly.tools as tlstrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)my_order = (1, 1, 1)my_seasonal_order = (0, 1, 1, 7) At a time we predict the next data point and we loop through train data to predict the next data and add the next data point after prediction for further forecasting. This is like a moving window daily level data(For eg: Previous 90 points are used to predict the next point at any given time). Convert the predicted data back to scale by power 10 transform and plot the results. history = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) model_fit = model.fit(disp=0) output = model_fit.forecast() predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) # print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show() This is a good time series forecast. Trend, Seasonality are two important factors in time series data and if your algorithm is able to capture the trend of your data(upward/downward) and in case your data is seasonal(weekly,daily,yearly pattern) visually then your algorithm fits your case. Here we can observe our SARIMA algorithm captures the trend from the spikes(not by replicating it but by just capturing the spike) and predicts well with the actuals during normal days. The parameter we specified here seems to work well for the metric but it would be an exhaustive task to do the plots verify and tune the parameters. A solution to this is Auto Arima which returns the best set of parameters for the algorithm in our specified range. Install pyramid-arima for auto arima. !pip install pyramid-arimafrom pyramid.arima import auto_arimastepwise_model = auto_arima(train_log, start_p=1, start_q=1, max_p=3, max_q=3, m=7, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True) Let’s find p and q parameters using auto_arima and specify d as 1 for first order differencing and seasonality as 7 for weekly seasonality. Now the auto arima model can be used for stepwise forecast by the same process we performed above: import mathimport statsmodels.api as smimport statsmodels.tsa.api as smtfrom sklearn.metrics import mean_squared_errortrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)# split data into train and test-setshistory = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): #model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) stepwise_model.fit(history) output = stepwise_model.predict(n_periods=1) predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) #print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show() In this scenario, auto arima and our initial SARIMA does well in forecasting also by not too much chasing the actuals. Next to visualize let’s create a dataframe with actuals data available and results of prediction predicted_df=pd.DataFrame()predicted_df['load_date']=time_series_df['load_date'][-70:]predicted_df['actuals']=testpredicted_df['predicted']=predictionspredicted_df.reset_index(inplace=True)del predicted_df['index']predicted_df.head() We have results of forecast and actuals, to detect anomalies using this information, I m using a property of the distribution of data. Note this will work only if the data is distributed normal/gaussian. Steps I do to detect anomalies:1. Compute the error term(actual- predicted).2. Compute the rolling mean and rolling standard deviation(window is a week).3. Classify data with an error of 1.5,1.75 and 2 standard deviations as limits for low,medium and high anomalies. (5% of data point would be identified anomalies based on this property) I have used lambda function for classifying anomalies based error and standard deviation rather than having separate loops and function for it. import numpy as npdef detect_classify_anomalies(df,window): df.replace([np.inf, -np.inf], np.NaN, inplace=True) df.fillna(0,inplace=True) df['error']=df['actuals']-df['predicted'] df['percentage_change'] = ((df['actuals'] - df['predicted']) / df['actuals']) * 100 df['meanval'] = df['error'].rolling(window=window).mean() df['deviation'] = df['error'].rolling(window=window).std() df['-3s'] = df['meanval'] - (2 * df['deviation']) df['3s'] = df['meanval'] + (2 * df['deviation']) df['-2s'] = df['meanval'] - (1.75 * df['deviation']) df['2s'] = df['meanval'] + (1.75 * df['deviation']) df['-1s'] = df['meanval'] - (1.5 * df['deviation']) df['1s'] = df['meanval'] + (1.5 * df['deviation']) cut_list = df[['error', '-3s', '-2s', '-1s', 'meanval', '1s', '2s', '3s']] cut_values = cut_list.values cut_sort = np.sort(cut_values) df['impact'] = [(lambda x: np.where(cut_sort == df['error'][x])[1][0])(x) for x in range(len(df['error']))] severity = {0: 3, 1: 2, 2: 1, 3: 0, 4: 0, 5: 1, 6: 2, 7: 3} region = {0: "NEGATIVE", 1: "NEGATIVE", 2: "NEGATIVE", 3: "NEGATIVE", 4: "POSITIVE", 5: "POSITIVE", 6: "POSITIVE", 7: "POSITIVE"} df['color'] = df['impact'].map(severity) df['region'] = df['impact'].map(region) df['anomaly_points'] = np.where(df['color'] == 3, df['error'], np.nan) df = df.sort_values(by='load_date', ascending=False) df.load_date = pd.to_datetime(df['load_date'].astype(str), format="%Y-%m-%d")return df Below is a function to visualize the results. Again the importance of clear comprehensive visualization helps business users give feedback on anomalies and makes the results actionable. The first plot has the error term with the upper and lower limit boundary specified. The plot of actuals with anomalies highlighted would be easy for a user to interpret/validate. So the second plot has actuals and predicted values with anomalies highlighted. Blue line- Actuals Orange Line- Predicted Red- Error Green — Moving Average Dotted lines — Upper and Lower bound for normal behavior def plot_anomaly(df,metric_name): #error = pd.DataFrame(Order_results.error.values) #df = df.sort_values(by='load_date', ascending=False) #df.load_date = pd.to_datetime(df['load_date'].astype(str), format="%Y%m%d") dates = df.load_date #meanval = error.rolling(window=window).mean() #deviation = error.rolling(window=window).std() #res = error#upper_bond=meanval + (2 * deviation) #lower_bond=meanval - (2 * deviation)#anomalies = pd.DataFrame(index=res.index, columns=res.columns) #anomalies[res < lower_bond] = res[res < lower_bond] #anomalies[res > upper_bond] = res[res > upper_bond] bool_array = (abs(df['anomaly_points']) > 0)#And a subplot of the Actual Values. actuals = df["actuals"][-len(bool_array):] anomaly_points = bool_array * actuals anomaly_points[anomaly_points == 0] = np.nan#Order_results['meanval']=meanval #Order_results['deviation']=deviationcolor_map= {0: "'rgba(228, 222, 249, 0.65)'", 1: "yellow", 2: "orange", 3: "red"} table = go.Table( domain=dict(x=[0, 1], y=[0, 0.3]), columnwidth=[1, 2 ], #columnorder=[0, 1, 2,], header = dict(height = 20, values = [['<b>Date</b>'],['<b>Actual Values </b>'], ['<b>Predicted</b>'], ['<b>% Difference</b>'],['<b>Severity (0-3)</b>']], font = dict(color=['rgb(45, 45, 45)'] * 5, size=14), fill = dict(color='#d562be')), cells = dict(values = [df.round(3)[k].tolist() for k in ['load_date', 'actuals', 'predicted', 'percentage_change','color']], line = dict(color='#506784'), align = ['center'] * 5, font = dict(color=['rgb(40, 40, 40)'] * 5, size=12), #format = [None] + [",.4f"] + [',.4f'],#suffix=[None] * 4, suffix=[None] + [''] + [''] + ['%'] + [''], height = 27, #fill = dict(color=['rgb(235, 193, 238)', 'rgba(228, 222, 249, 0.65)'])) fill=dict(color= # ['rgb(245,245,245)',#unique color for the first column [df['color'].map(color_map)], ) ))#df['ano'] = np.where(df['color']==3, df['error'], np.nan)anomalies = go.Scatter(name="Anomaly", x=dates, xaxis='x1', yaxis='y1', y=df['anomaly_points'], mode='markers', marker = dict(color ='red', size = 11,line = dict( color = "red", width = 2)))upper_bound = go.Scatter(hoverinfo="skip", x=dates, showlegend =False, xaxis='x1', yaxis='y1', y=df['3s'], marker=dict(color="#444"), line=dict( color=('rgb(23, 96, 167)'), width=2, dash='dash'), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty')lower_bound = go.Scatter(name='Confidence Interval', x=dates, xaxis='x1', yaxis='y1', y=df['-3s'], marker=dict(color="#444"), line=dict( color=('rgb(23, 96, 167)'), width=2, dash='dash'), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty')Actuals = go.Scatter(name= 'Actuals', x= dates, y= df['actuals'], xaxis='x2', yaxis='y2', mode='line', marker=dict(size=12, line=dict(width=1), color="blue"))Predicted = go.Scatter(name= 'Predicted', x= dates, y= df['predicted'], xaxis='x2', yaxis='y2', mode='line', marker=dict(size=12, line=dict(width=1), color="orange"))# create plot for error... Error = go.Scatter(name="Error", x=dates, y=df['error'], xaxis='x1', yaxis='y1', mode='line', marker=dict(size=12, line=dict(width=1), color="red"), text="Error")anomalies_map = go.Scatter(name = "anomaly actual", showlegend=False, x=dates, y=anomaly_points, mode='markers', xaxis='x2', yaxis='y2', marker = dict(color ="red", size = 11, line = dict( color = "red", width = 2)))Mvingavrg = go.Scatter(name="Moving Average", x=dates, y=df['meanval'], mode='line', xaxis='x1', yaxis='y1', marker=dict(size=12, line=dict(width=1), color="green"), text="Moving average")axis=dict( showline=True, zeroline=False, showgrid=True, mirror=True, ticklen=4, gridcolor='#ffffff', tickfont=dict(size=10))layout = dict( width=1000, height=865, autosize=False, title= metric_name, margin = dict(t=75), showlegend=True, xaxis1=dict(axis, **dict(domain=[0, 1], anchor='y1', showticklabels=True)), xaxis2=dict(axis, **dict(domain=[0, 1], anchor='y2', showticklabels=True)), yaxis1=dict(axis, **dict(domain=[2 * 0.21 + 0.20 + 0.09, 1], anchor='x1', hoverformat='.2f')), yaxis2=dict(axis, **dict(domain=[0.21 + 0.12, 2 * 0.31 + 0.02], anchor='x2', hoverformat='.2f')))fig = go.Figure(data = [table,anomalies,anomalies_map, upper_bound,lower_bound,Actuals,Predicted, Mvingavrg,Error], layout = layout)iplot(fig)pyplot.show()classify_df=detect_classify_anomalies(predicted_df,7)classify_df.reset_index(inplace=True)del classify_df['index']plot_anomaly(classify_df,"metric_name") By using a rolling mean and standard deviation here we are able to avoid continuous false anomalies during scenarios like big sale days. The first spike or dip is highlighted after which the thresholds get adjusted. Also, the table which provides actual data, predicted the change and conditional formatting based on the level of anomalies. Next, we also try forecasting using LSTM which is a recurrent neural network. https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ is a really good tutorial of time series forecasting using LSTM and we are going to use some parts of the code here for our use case. Below are helper functions for differencing,scaling along with inverse of them and Training, forecasting of the **LSTM**. from pandas import DataFramefrom pandas import Seriesfrom pandas import concatfrom pandas import read_csvfrom pandas import datetimefrom sklearn.metrics import mean_squared_errorfrom sklearn.preprocessing import MinMaxScalerfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom math import sqrt# frame a sequence as a supervised learning problemdef timeseries_to_supervised(data, lag=1): df = DataFrame(data) columns = [df.shift(i) for i in range(1, lag+1)] columns.append(df) df = concat(columns, axis=1) df.fillna(0, inplace=True) return df# create a differenced seriesdef difference(dataset, interval=1): diff = list() for i in range(interval, len(dataset)): value = dataset[i] - dataset[i - interval] diff.append(value) return Series(diff)# invert differenced valuedef inverse_difference(history, yhat, interval=1): return yhat + history[-interval]# scale train and test data to [-1, 1]def scale(train, test): # fit scaler scaler = MinMaxScaler(feature_range=(-1, 1)) scaler = scaler.fit(train) # transform train train = train.reshape(train.shape[0], train.shape[1]) train_scaled = scaler.transform(train) # transform test test = test.reshape(test.shape[0], test.shape[1]) test_scaled = scaler.transform(test) return scaler, train_scaled, test_scaled# inverse scaling for a forecasted valuedef invert_scale(scaler, X, value): new_row = [x for x in X] + [value] array = np.array(new_row) array = array.reshape(1, len(array)) inverted = scaler.inverse_transform(array) return inverted[0, -1]# fit an LSTM network to training datadef fit_lstm(train, batch_size, nb_epoch, neurons): X, y = train[:, 0:-1], train[:, -1] X = X.reshape(X.shape[0], 1, X.shape[1]) model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') for i in range(nb_epoch): model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False) model.reset_states() return model# make a one-step forecastdef forecast_lstm(model, batch_size, X): X = X.reshape(1, 1, len(X)) yhat = model.predict(X, batch_size=batch_size) return yhat[0,0]#### LSTMsupervised = timeseries_to_supervised(actual_log, 1)supervised_values = supervised.values# split data into train and test-setstrain_lstm, test_lstm = supervised_values[0:-70], supervised_values[-70:]# transform the scale of the datascaler, train_scaled_lstm, test_scaled_lstm = scale(train_lstm, test_lstm)# fit the model batch,Epoch,Neuronslstm_model = fit_lstm(train_scaled_lstm, 1, 850 , 3)# forecast the entire training dataset to build up state for forecastingtrain_reshaped = train_scaled_lstm[:, 0].reshape(len(train_scaled_lstm), 1, 1)#lstm_model.predict(train_reshaped, batch_size=1) Forecast data using LSTM and plot the results from matplotlib import pyplotimport matplotlib.pyplot as pltimport plotly.plotly as pyimport plotly.tools as tls# walk-forward validation on the test datapredictions = list()for i in range(len(test_scaled_lstm)):#make one-step forecast X, y = test_scaled_lstm[i, 0:-1], test_scaled_lstm[i, -1] yhat = forecast_lstm(lstm_model, 1, X) # invert scaling yhat = invert_scale(scaler, X, yhat) # invert differencing #yhat = inverse_difference(raw_values, yhat, len(test_scaled)+1-i) # store forecast predictions.append(10**yhat) expected = actual_log[len(train_lstm) + i ]# line plot of observed vs predictedfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(actual_vals[-70:],label='Actuals')pyplot.plot(predictions, color = "red",label='Predicted')pyplot.legend(loc='upper right')pyplot.show() The LSTM too works well for this metric. The important parameters of LSTM neural network are the activation function, the number of neurons,batch size and epoch which needs to be tuned for better results. Now lets try this out in a different metric data. The data is for same time period. tf_df=pd.read_csv('../input/forecast-metric2/time_series_metric2.csv')tf_df.head() With the same procedure followed above, we use auto arima to get the best parameters and forecast stepwise. Plot the results of actuals and predictions made. actual_vals = tf_df.actuals.valuestrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)from pyramid.arima import auto_arimastepwise_model = auto_arima(train_log, start_p=1, start_q=1, max_p=3, max_q=3, m=7, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True)history = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): #model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) stepwise_model.fit(history,enforce_stationarity=False,enforce_invertibility=False) output = stepwise_model.predict(n_periods=1) predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) #print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show() Here the algorithm tries to chase down the actuals. Though this might be a good forecast where the error is low but the anomalous behavior in the actuals cant be identified using this. This is a problem of using forecasting techniques for anomaly detection. We are trying to capture trends/seasonality in data along with not optimizing too much on the error to get an exact replica of actuals(which makes us difficult to find anomalies). Every metric needs to be validated with parameters fine-tuned so that anomalies are detected when using forecasting for detecting anomalies. Also for metrics with a different distribution of data a different approach in identifying anomalies needs to be followed. One more con is, Isolation forest we detected anomalies for a use case which comprised of multiple metrics at a time and we drilled down to anomalies on individual metrics in them. Whereas using forecasting mechanism we need a separate correlation logic as forecasting is individual for metrics. Whereas an algorithm like isolation forest separates out anomalous behavior from the data which can be used to generalize to multiple metrics.
[ { "code": null, "e": 420, "s": 171, "text": "Hi, this is a follow-up article on anomaly detection(Link to the previous article: https://medium.com/myntra-engineering/anomaly-detection-with-isolation-forest-visualization-23cd75c281e2 where we did anomaly detection using unsupervised learning)." }, { "code": null, "e": 1082, "s": 420, "text": "Here we will see about detecting anomalies with time series forecasting. Time series is any data which is associated with time(daily, hourly, monthly etc). For eg: revenue at a store every day is a time series data at a day level. Many use cases like demand estimation, sales forecasting is a typical time series forecasting problem which could be solved by algorithms like SARIMA, LSTM, Holtwinters etc. Time series forecasting helps us in preparing us for future needs by estimating them with the current data. Once we have the forecast we can use that data to detect anomalies on comparing them with actuals. Let’s implement it and look at its pros and cons." }, { "code": null, "e": 1135, "s": 1082, "text": "Installing and importing libraries for visualization" }, { "code": null, "e": 1650, "s": 1135, "text": "#Installing specific version of plotly to avoid Invalid property for color error in recent version which needs change in layout!pip install plotly==2.7.0import pandas as pdimport numpy as npfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.plotly as pyimport matplotlib.pyplot as pltfrom matplotlib import pyplotimport plotly.graph_objs as goinit_notebook_mode(connected=True)time_series_df=pd.read_csv('../input/time-series-data/time_series_data.csv')time_series_df.head()" }, { "code": null, "e": 1762, "s": 1650, "text": "The order of data here is important and should be **chronological** as we are going to forecast the next point." }, { "code": null, "e": 1843, "s": 1762, "text": "Convert the load_date column to datetime format and sort the data based on date." }, { "code": null, "e": 2062, "s": 1843, "text": "time_series_df.load_date = pd.to_datetime(time_series_df.load_date, format='%Y%m%d')time_series_df = time_series_df.sort_values(by=\"load_date\")time_series_df = time_series_df.reset_index(drop=True)time_series_df.head()" }, { "code": null, "e": 2200, "s": 2062, "text": "Extract the values and apply log transform to stabilize the variance in the data or to make it stationary before feeding it to the model." }, { "code": null, "e": 2278, "s": 2200, "text": "actual_vals = time_series_df.actuals.valuesactual_log = np.log10(actual_vals)" }, { "code": null, "e": 2341, "s": 2278, "text": "Divide the data to train and test with 70 points in test data." }, { "code": null, "e": 2719, "s": 2341, "text": "First let’s try to apply SARIMA algorithm for forecasting. SARIMA stands for Seasonal Auto Regressive Integrated Moving Average. It has a seasonal parameter which we initialize as 7 due to weekly seasonality of our sales data. Other parameters are p,d,q which are identified based on ACF and PACF plots or ideally we should use the parameters with minimal error in forecasting." }, { "code": null, "e": 3103, "s": 2719, "text": "More details can be found here: https://people.duke.edu/~rnau/arimrule.htm I m not getting into the problem of getting the right set of parameters here which we will solve later using Auto Arima which allows us to get the best set of parameters in a range with minimal error. Here I m specifying the differencing factor(d) as 1. It helps us to remove trends and cycles in the data." }, { "code": null, "e": 3490, "s": 3103, "text": "import mathimport statsmodels.api as smimport statsmodels.tsa.api as smtfrom sklearn.metrics import mean_squared_errorfrom matplotlib import pyplotimport matplotlib.pyplot as pltimport plotly.plotly as pyimport plotly.tools as tlstrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)my_order = (1, 1, 1)my_seasonal_order = (0, 1, 1, 7)" }, { "code": null, "e": 3657, "s": 3490, "text": "At a time we predict the next data point and we loop through train data to predict the next data and add the next data point after prediction for further forecasting." }, { "code": null, "e": 3785, "s": 3657, "text": "This is like a moving window daily level data(For eg: Previous 90 points are used to predict the next point at any given time)." }, { "code": null, "e": 3870, "s": 3785, "text": "Convert the predicted data back to scale by power 10 transform and plot the results." }, { "code": null, "e": 4639, "s": 3870, "text": "history = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) model_fit = model.fit(disp=0) output = model_fit.forecast() predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) # print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show()" }, { "code": null, "e": 4930, "s": 4639, "text": "This is a good time series forecast. Trend, Seasonality are two important factors in time series data and if your algorithm is able to capture the trend of your data(upward/downward) and in case your data is seasonal(weekly,daily,yearly pattern) visually then your algorithm fits your case." }, { "code": null, "e": 5116, "s": 4930, "text": "Here we can observe our SARIMA algorithm captures the trend from the spikes(not by replicating it but by just capturing the spike) and predicts well with the actuals during normal days." }, { "code": null, "e": 5381, "s": 5116, "text": "The parameter we specified here seems to work well for the metric but it would be an exhaustive task to do the plots verify and tune the parameters. A solution to this is Auto Arima which returns the best set of parameters for the algorithm in our specified range." }, { "code": null, "e": 5419, "s": 5381, "text": "Install pyramid-arima for auto arima." }, { "code": null, "e": 5834, "s": 5419, "text": "!pip install pyramid-arimafrom pyramid.arima import auto_arimastepwise_model = auto_arima(train_log, start_p=1, start_q=1, max_p=3, max_q=3, m=7, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True)" }, { "code": null, "e": 5974, "s": 5834, "text": "Let’s find p and q parameters using auto_arima and specify d as 1 for first order differencing and seasonality as 7 for weekly seasonality." }, { "code": null, "e": 6073, "s": 5974, "text": "Now the auto arima model can be used for stepwise forecast by the same process we performed above:" }, { "code": null, "e": 7115, "s": 6073, "text": "import mathimport statsmodels.api as smimport statsmodels.tsa.api as smtfrom sklearn.metrics import mean_squared_errortrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)# split data into train and test-setshistory = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): #model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) stepwise_model.fit(history) output = stepwise_model.predict(n_periods=1) predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) #print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show()" }, { "code": null, "e": 7234, "s": 7115, "text": "In this scenario, auto arima and our initial SARIMA does well in forecasting also by not too much chasing the actuals." }, { "code": null, "e": 7331, "s": 7234, "text": "Next to visualize let’s create a dataframe with actuals data available and results of prediction" }, { "code": null, "e": 7565, "s": 7331, "text": "predicted_df=pd.DataFrame()predicted_df['load_date']=time_series_df['load_date'][-70:]predicted_df['actuals']=testpredicted_df['predicted']=predictionspredicted_df.reset_index(inplace=True)del predicted_df['index']predicted_df.head()" }, { "code": null, "e": 7769, "s": 7565, "text": "We have results of forecast and actuals, to detect anomalies using this information, I m using a property of the distribution of data. Note this will work only if the data is distributed normal/gaussian." }, { "code": null, "e": 8108, "s": 7769, "text": "Steps I do to detect anomalies:1. Compute the error term(actual- predicted).2. Compute the rolling mean and rolling standard deviation(window is a week).3. Classify data with an error of 1.5,1.75 and 2 standard deviations as limits for low,medium and high anomalies. (5% of data point would be identified anomalies based on this property)" }, { "code": null, "e": 8252, "s": 8108, "text": "I have used lambda function for classifying anomalies based error and standard deviation rather than having separate loops and function for it." }, { "code": null, "e": 9778, "s": 8252, "text": "import numpy as npdef detect_classify_anomalies(df,window): df.replace([np.inf, -np.inf], np.NaN, inplace=True) df.fillna(0,inplace=True) df['error']=df['actuals']-df['predicted'] df['percentage_change'] = ((df['actuals'] - df['predicted']) / df['actuals']) * 100 df['meanval'] = df['error'].rolling(window=window).mean() df['deviation'] = df['error'].rolling(window=window).std() df['-3s'] = df['meanval'] - (2 * df['deviation']) df['3s'] = df['meanval'] + (2 * df['deviation']) df['-2s'] = df['meanval'] - (1.75 * df['deviation']) df['2s'] = df['meanval'] + (1.75 * df['deviation']) df['-1s'] = df['meanval'] - (1.5 * df['deviation']) df['1s'] = df['meanval'] + (1.5 * df['deviation']) cut_list = df[['error', '-3s', '-2s', '-1s', 'meanval', '1s', '2s', '3s']] cut_values = cut_list.values cut_sort = np.sort(cut_values) df['impact'] = [(lambda x: np.where(cut_sort == df['error'][x])[1][0])(x) for x in range(len(df['error']))] severity = {0: 3, 1: 2, 2: 1, 3: 0, 4: 0, 5: 1, 6: 2, 7: 3} region = {0: \"NEGATIVE\", 1: \"NEGATIVE\", 2: \"NEGATIVE\", 3: \"NEGATIVE\", 4: \"POSITIVE\", 5: \"POSITIVE\", 6: \"POSITIVE\", 7: \"POSITIVE\"} df['color'] = df['impact'].map(severity) df['region'] = df['impact'].map(region) df['anomaly_points'] = np.where(df['color'] == 3, df['error'], np.nan) df = df.sort_values(by='load_date', ascending=False) df.load_date = pd.to_datetime(df['load_date'].astype(str), format=\"%Y-%m-%d\")return df" }, { "code": null, "e": 9964, "s": 9778, "text": "Below is a function to visualize the results. Again the importance of clear comprehensive visualization helps business users give feedback on anomalies and makes the results actionable." }, { "code": null, "e": 10049, "s": 9964, "text": "The first plot has the error term with the upper and lower limit boundary specified." }, { "code": null, "e": 10224, "s": 10049, "text": "The plot of actuals with anomalies highlighted would be easy for a user to interpret/validate. So the second plot has actuals and predicted values with anomalies highlighted." }, { "code": null, "e": 10243, "s": 10224, "text": "Blue line- Actuals" }, { "code": null, "e": 10266, "s": 10243, "text": "Orange Line- Predicted" }, { "code": null, "e": 10277, "s": 10266, "text": "Red- Error" }, { "code": null, "e": 10300, "s": 10277, "text": "Green — Moving Average" }, { "code": null, "e": 10357, "s": 10300, "text": "Dotted lines — Upper and Lower bound for normal behavior" }, { "code": null, "e": 17147, "s": 10357, "text": "def plot_anomaly(df,metric_name): #error = pd.DataFrame(Order_results.error.values) #df = df.sort_values(by='load_date', ascending=False) #df.load_date = pd.to_datetime(df['load_date'].astype(str), format=\"%Y%m%d\") dates = df.load_date #meanval = error.rolling(window=window).mean() #deviation = error.rolling(window=window).std() #res = error#upper_bond=meanval + (2 * deviation) #lower_bond=meanval - (2 * deviation)#anomalies = pd.DataFrame(index=res.index, columns=res.columns) #anomalies[res < lower_bond] = res[res < lower_bond] #anomalies[res > upper_bond] = res[res > upper_bond] bool_array = (abs(df['anomaly_points']) > 0)#And a subplot of the Actual Values. actuals = df[\"actuals\"][-len(bool_array):] anomaly_points = bool_array * actuals anomaly_points[anomaly_points == 0] = np.nan#Order_results['meanval']=meanval #Order_results['deviation']=deviationcolor_map= {0: \"'rgba(228, 222, 249, 0.65)'\", 1: \"yellow\", 2: \"orange\", 3: \"red\"} table = go.Table( domain=dict(x=[0, 1], y=[0, 0.3]), columnwidth=[1, 2 ], #columnorder=[0, 1, 2,], header = dict(height = 20, values = [['<b>Date</b>'],['<b>Actual Values </b>'], ['<b>Predicted</b>'], ['<b>% Difference</b>'],['<b>Severity (0-3)</b>']], font = dict(color=['rgb(45, 45, 45)'] * 5, size=14), fill = dict(color='#d562be')), cells = dict(values = [df.round(3)[k].tolist() for k in ['load_date', 'actuals', 'predicted', 'percentage_change','color']], line = dict(color='#506784'), align = ['center'] * 5, font = dict(color=['rgb(40, 40, 40)'] * 5, size=12), #format = [None] + [\",.4f\"] + [',.4f'],#suffix=[None] * 4, suffix=[None] + [''] + [''] + ['%'] + [''], height = 27, #fill = dict(color=['rgb(235, 193, 238)', 'rgba(228, 222, 249, 0.65)'])) fill=dict(color= # ['rgb(245,245,245)',#unique color for the first column [df['color'].map(color_map)], ) ))#df['ano'] = np.where(df['color']==3, df['error'], np.nan)anomalies = go.Scatter(name=\"Anomaly\", x=dates, xaxis='x1', yaxis='y1', y=df['anomaly_points'], mode='markers', marker = dict(color ='red', size = 11,line = dict( color = \"red\", width = 2)))upper_bound = go.Scatter(hoverinfo=\"skip\", x=dates, showlegend =False, xaxis='x1', yaxis='y1', y=df['3s'], marker=dict(color=\"#444\"), line=dict( color=('rgb(23, 96, 167)'), width=2, dash='dash'), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty')lower_bound = go.Scatter(name='Confidence Interval', x=dates, xaxis='x1', yaxis='y1', y=df['-3s'], marker=dict(color=\"#444\"), line=dict( color=('rgb(23, 96, 167)'), width=2, dash='dash'), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty')Actuals = go.Scatter(name= 'Actuals', x= dates, y= df['actuals'], xaxis='x2', yaxis='y2', mode='line', marker=dict(size=12, line=dict(width=1), color=\"blue\"))Predicted = go.Scatter(name= 'Predicted', x= dates, y= df['predicted'], xaxis='x2', yaxis='y2', mode='line', marker=dict(size=12, line=dict(width=1), color=\"orange\"))# create plot for error... Error = go.Scatter(name=\"Error\", x=dates, y=df['error'], xaxis='x1', yaxis='y1', mode='line', marker=dict(size=12, line=dict(width=1), color=\"red\"), text=\"Error\")anomalies_map = go.Scatter(name = \"anomaly actual\", showlegend=False, x=dates, y=anomaly_points, mode='markers', xaxis='x2', yaxis='y2', marker = dict(color =\"red\", size = 11, line = dict( color = \"red\", width = 2)))Mvingavrg = go.Scatter(name=\"Moving Average\", x=dates, y=df['meanval'], mode='line', xaxis='x1', yaxis='y1', marker=dict(size=12, line=dict(width=1), color=\"green\"), text=\"Moving average\")axis=dict( showline=True, zeroline=False, showgrid=True, mirror=True, ticklen=4, gridcolor='#ffffff', tickfont=dict(size=10))layout = dict( width=1000, height=865, autosize=False, title= metric_name, margin = dict(t=75), showlegend=True, xaxis1=dict(axis, **dict(domain=[0, 1], anchor='y1', showticklabels=True)), xaxis2=dict(axis, **dict(domain=[0, 1], anchor='y2', showticklabels=True)), yaxis1=dict(axis, **dict(domain=[2 * 0.21 + 0.20 + 0.09, 1], anchor='x1', hoverformat='.2f')), yaxis2=dict(axis, **dict(domain=[0.21 + 0.12, 2 * 0.31 + 0.02], anchor='x2', hoverformat='.2f')))fig = go.Figure(data = [table,anomalies,anomalies_map, upper_bound,lower_bound,Actuals,Predicted, Mvingavrg,Error], layout = layout)iplot(fig)pyplot.show()classify_df=detect_classify_anomalies(predicted_df,7)classify_df.reset_index(inplace=True)del classify_df['index']plot_anomaly(classify_df,\"metric_name\")" }, { "code": null, "e": 17284, "s": 17147, "text": "By using a rolling mean and standard deviation here we are able to avoid continuous false anomalies during scenarios like big sale days." }, { "code": null, "e": 17363, "s": 17284, "text": "The first spike or dip is highlighted after which the thresholds get adjusted." }, { "code": null, "e": 17488, "s": 17363, "text": "Also, the table which provides actual data, predicted the change and conditional formatting based on the level of anomalies." }, { "code": null, "e": 17566, "s": 17488, "text": "Next, we also try forecasting using LSTM which is a recurrent neural network." }, { "code": null, "e": 17803, "s": 17566, "text": "https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ is a really good tutorial of time series forecasting using LSTM and we are going to use some parts of the code here for our use case." }, { "code": null, "e": 17925, "s": 17803, "text": "Below are helper functions for differencing,scaling along with inverse of them and Training, forecasting of the **LSTM**." }, { "code": null, "e": 20872, "s": 17925, "text": "from pandas import DataFramefrom pandas import Seriesfrom pandas import concatfrom pandas import read_csvfrom pandas import datetimefrom sklearn.metrics import mean_squared_errorfrom sklearn.preprocessing import MinMaxScalerfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom math import sqrt# frame a sequence as a supervised learning problemdef timeseries_to_supervised(data, lag=1): df = DataFrame(data) columns = [df.shift(i) for i in range(1, lag+1)] columns.append(df) df = concat(columns, axis=1) df.fillna(0, inplace=True) return df# create a differenced seriesdef difference(dataset, interval=1): diff = list() for i in range(interval, len(dataset)): value = dataset[i] - dataset[i - interval] diff.append(value) return Series(diff)# invert differenced valuedef inverse_difference(history, yhat, interval=1): return yhat + history[-interval]# scale train and test data to [-1, 1]def scale(train, test): # fit scaler scaler = MinMaxScaler(feature_range=(-1, 1)) scaler = scaler.fit(train) # transform train train = train.reshape(train.shape[0], train.shape[1]) train_scaled = scaler.transform(train) # transform test test = test.reshape(test.shape[0], test.shape[1]) test_scaled = scaler.transform(test) return scaler, train_scaled, test_scaled# inverse scaling for a forecasted valuedef invert_scale(scaler, X, value): new_row = [x for x in X] + [value] array = np.array(new_row) array = array.reshape(1, len(array)) inverted = scaler.inverse_transform(array) return inverted[0, -1]# fit an LSTM network to training datadef fit_lstm(train, batch_size, nb_epoch, neurons): X, y = train[:, 0:-1], train[:, -1] X = X.reshape(X.shape[0], 1, X.shape[1]) model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') for i in range(nb_epoch): model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False) model.reset_states() return model# make a one-step forecastdef forecast_lstm(model, batch_size, X): X = X.reshape(1, 1, len(X)) yhat = model.predict(X, batch_size=batch_size) return yhat[0,0]#### LSTMsupervised = timeseries_to_supervised(actual_log, 1)supervised_values = supervised.values# split data into train and test-setstrain_lstm, test_lstm = supervised_values[0:-70], supervised_values[-70:]# transform the scale of the datascaler, train_scaled_lstm, test_scaled_lstm = scale(train_lstm, test_lstm)# fit the model batch,Epoch,Neuronslstm_model = fit_lstm(train_scaled_lstm, 1, 850 , 3)# forecast the entire training dataset to build up state for forecastingtrain_reshaped = train_scaled_lstm[:, 0].reshape(len(train_scaled_lstm), 1, 1)#lstm_model.predict(train_reshaped, batch_size=1)" }, { "code": null, "e": 20918, "s": 20872, "text": "Forecast data using LSTM and plot the results" }, { "code": null, "e": 21737, "s": 20918, "text": "from matplotlib import pyplotimport matplotlib.pyplot as pltimport plotly.plotly as pyimport plotly.tools as tls# walk-forward validation on the test datapredictions = list()for i in range(len(test_scaled_lstm)):#make one-step forecast X, y = test_scaled_lstm[i, 0:-1], test_scaled_lstm[i, -1] yhat = forecast_lstm(lstm_model, 1, X) # invert scaling yhat = invert_scale(scaler, X, yhat) # invert differencing #yhat = inverse_difference(raw_values, yhat, len(test_scaled)+1-i) # store forecast predictions.append(10**yhat) expected = actual_log[len(train_lstm) + i ]# line plot of observed vs predictedfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(actual_vals[-70:],label='Actuals')pyplot.plot(predictions, color = \"red\",label='Predicted')pyplot.legend(loc='upper right')pyplot.show()" }, { "code": null, "e": 21942, "s": 21737, "text": "The LSTM too works well for this metric. The important parameters of LSTM neural network are the activation function, the number of neurons,batch size and epoch which needs to be tuned for better results." }, { "code": null, "e": 22026, "s": 21942, "text": "Now lets try this out in a different metric data. The data is for same time period." }, { "code": null, "e": 22109, "s": 22026, "text": "tf_df=pd.read_csv('../input/forecast-metric2/time_series_metric2.csv')tf_df.head()" }, { "code": null, "e": 22217, "s": 22109, "text": "With the same procedure followed above, we use auto arima to get the best parameters and forecast stepwise." }, { "code": null, "e": 22267, "s": 22217, "text": "Plot the results of actuals and predictions made." }, { "code": null, "e": 23631, "s": 22267, "text": "actual_vals = tf_df.actuals.valuestrain, test = actual_vals[0:-70], actual_vals[-70:]train_log, test_log = np.log10(train), np.log10(test)from pyramid.arima import auto_arimastepwise_model = auto_arima(train_log, start_p=1, start_q=1, max_p=3, max_q=3, m=7, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True)history = [x for x in train_log]predictions = list()predict_log=list()for t in range(len(test_log)): #model = sm.tsa.SARIMAX(history, order=my_order, seasonal_order=my_seasonal_order,enforce_stationarity=False,enforce_invertibility=False) stepwise_model.fit(history,enforce_stationarity=False,enforce_invertibility=False) output = stepwise_model.predict(n_periods=1) predict_log.append(output[0]) yhat = 10**output[0] predictions.append(yhat) obs = test_log[t] history.append(obs) #print('predicted=%f, expected=%f' % (output[0], obs))#error = math.sqrt(mean_squared_error(test_log, predict_log))#print('Test rmse: %.3f' % error)# plotfigsize=(12, 7)plt.figure(figsize=figsize)pyplot.plot(test,label='Actuals')pyplot.plot(predictions, color='red',label='Predicted')pyplot.legend(loc='upper right')pyplot.show()" }, { "code": null, "e": 23816, "s": 23631, "text": "Here the algorithm tries to chase down the actuals. Though this might be a good forecast where the error is low but the anomalous behavior in the actuals cant be identified using this." }, { "code": null, "e": 24069, "s": 23816, "text": "This is a problem of using forecasting techniques for anomaly detection. We are trying to capture trends/seasonality in data along with not optimizing too much on the error to get an exact replica of actuals(which makes us difficult to find anomalies)." }, { "code": null, "e": 24333, "s": 24069, "text": "Every metric needs to be validated with parameters fine-tuned so that anomalies are detected when using forecasting for detecting anomalies. Also for metrics with a different distribution of data a different approach in identifying anomalies needs to be followed." }, { "code": null, "e": 24629, "s": 24333, "text": "One more con is, Isolation forest we detected anomalies for a use case which comprised of multiple metrics at a time and we drilled down to anomalies on individual metrics in them. Whereas using forecasting mechanism we need a separate correlation logic as forecasting is individual for metrics." } ]
Cows of FooLand | Practice | GeeksforGeeks
Cows in the FooLand city are interesting animals. One of their specialities is related to producing offsprings. A cow in FooLand produces its first calve (female calf) at the age of two years and proceeds to produce other calves (one female calf a year). Now the farmer Harold wants to know how many animals would he have at the end of N years, if we assume that none of the calves dies, given that initially, he has only one female calf? Since the answer can be huge, print it modulo 109+7. Example 1: Input: N = 2 Output: 2 Explanation: At the end of 1 year, he will have only 1 cow, at the end of 2 years he will have 2 animals (one parent cow C1 and other baby calf B1 which is the offspring of cow C1). Example 2: Input: N = 4 Output: 5 Explanation: At the end of 1 year, he will have only 1 cow, at the end of 2 years he will have 2 animals (one parent cow C1 and other baby calf B1 which is the offspring of cow C1). At the end of 3 years, he will have 3 animals (one parent cow C1 and 2 female calves B1 and B2, C1 is the parent of B1 and B2).At the end of 4 years,he will have 5 animals (one parent cow C1, 3 offsprings of C1 i.e. B1, B2, B3 and one offspring of B1). Your Task: You don't need to read or print anything. Your task is to complete the function TotalAnimal() which takes N as input parameter and returns the total number of animals at the end of N years modulo 109 + 7. Expected Time Complexity: O(log2N) Expected Space Complexity: O(1) Constraints: 1 <= N <= 1018 +3 gauravtiwari30017 months ago https://medium.com/codebrace/starred-problem-2-nth-fibonacci-number-in-log-n-time-821ea9a18296 This is a very good post on Medium explaining how to find a fibonacci Number in Logn time. Though I am posting the solution. Don't just blindly copy, paste and submit. Do give this post a read and understand it. void multiply(long long int mat[2][2],long long int m[2][2]){ long long int temp[2][2]; long long int x = 1000000007; temp[0][0]=mat[0][0]*m[0][0]+mat[0][1]*m[1][0]; temp[0][1]= mat[0][0]*m[0][1]+mat[0][1]*m[1][1]; temp[1][0]= mat[1][0]*m[0][0]+mat[1][1]*m[1][0]; temp[1][1]= mat[1][0]*m[0][1]+mat[1][1]*m[1][1]; mat[0][0]=temp[0][0]%x; mat[0][1]=temp[0][1]%x; mat[1][0]=temp[1][0]%x; mat[1][1]=temp[1][1]%x; } void mat_power(long long int mat[2][2],long long int n){ if(n==1) return; // n==0 will never come mat_power(mat,n/2); multiply(mat,mat); long long int m[2][2]={ {1,1}, {1,0} }; if(n%2!=0) multiply(mat,m); } ////////////////////////////////////////////* int TotalAnimal(long long int n){ long long int mat[2][2]={ {1,1}, {1,0} }; if(n==0) return 1; mat_power(mat,n+1); return mat[0][1]; // Code here } }; +1 gauravtiwari30017 months ago https://medium.com/codebrace/starred-problem-2-nth-fibonacci-number-in-log-n-time-821ea9a18296 This is a very good post on Medium explaining how to find a fibonacci Number in Logn time. Though I am posting the solution. Don't just blindly copy, paste and submit. Do give this post a read and understand it. void multiply(long long int mat[2][2],long long int m[2][2]){ long long int temp[2][2]; long long int x = 1000000007; temp[0][0]=mat[0][0]*m[0][0]+mat[0][1]*m[1][0]; temp[0][1]= mat[0][0]*m[0][1]+mat[0][1]*m[1][1]; temp[1][0]= mat[1][0]*m[0][0]+mat[1][1]*m[1][0]; temp[1][1]= mat[1][0]*m[0][1]+mat[1][1]*m[1][1]; mat[0][0]=temp[0][0]%x; mat[0][1]=temp[0][1]%x; mat[1][0]=temp[1][0]%x; mat[1][1]=temp[1][1]%x; } void mat_power(long long int mat[2][2],long long int n){ if(n==1) return; // n==0 will never come mat_power(mat,n/2); multiply(mat,mat); long long int m[2][2]={ {1,1}, {1,0} }; if(n%2!=0) multiply(mat,m); } ////////////////////////////////////////////* int TotalAnimal(long long int n){ long long int mat[2][2]={ {1,1}, {1,0} }; if(n==0) return 1; mat_power(mat,n+1); return mat[0][1]; // Code here } }; 0 shikhars31457 months ago Can anybody explain how this question is same as fibonacci series? +2 aijazhera27627 months ago Easy explanation for solving the Fibonacci Sequence with Matrix Exponentiation https://www.youtube.com/watch?v=EEb6JP3NXBI 0 aijazhera2762 This comment was deleted. 0 aijazhera2762 This comment was deleted. -1 mridultyagi80 This comment was deleted. +3 ritintiwari4177 months ago If you Program is working till 43 and giving you wrong answer for above, refer this article : https://www.geeksforgeeks.org/modulo-1097-1000000007/ +1 nishaanjum119 This comment was deleted. 0 bhupeshbhatt82227 months ago I am using the concept of fibonacci number, f(n) = f(n) + f(n-1) This code is working fine for smaller numbers , but not workinbg for larger numbers . Can anyone tell the isssue? int TotalAnimal(long long int N){ // Code here if(N==1||N==2||N==3) return N; int prev = 1, p_prev=1, curr; long long int i; int sum =3; for( i =3 ; i<N; i++) { curr= prev + p_prev; p_prev= prev; prev= curr; sum+=curr; } return sum;} 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": 481, "s": 226, "text": "Cows in the FooLand city are interesting animals. One of their specialities is related to producing offsprings. A cow in FooLand produces its first calve (female calf) at the age of two years and proceeds to produce other calves (one female calf a year)." }, { "code": null, "e": 665, "s": 481, "text": "Now the farmer Harold wants to know how many animals would he have at the end of N years, if we assume that none of the calves dies, given that initially, he has only one female calf?" }, { "code": null, "e": 720, "s": 665, "text": "Since the answer can be huge, print it modulo 109+7.\n " }, { "code": null, "e": 731, "s": 720, "text": "Example 1:" }, { "code": null, "e": 940, "s": 731, "text": "Input: N = 2\nOutput: 2\nExplanation: At the end of 1 year, he will have \nonly 1 cow, at the end of 2 years he will have \n2 animals (one parent cow C1 and other baby \ncalf B1 which is the offspring of cow C1).\n" }, { "code": null, "e": 951, "s": 940, "text": "Example 2:" }, { "code": null, "e": 1412, "s": 951, "text": "Input: N = 4\nOutput: 5\nExplanation: At the end of 1 year, he will have\nonly 1 cow, at the end of 2 years he will have\n2 animals (one parent cow C1 and other baby\ncalf B1 which is the offspring of cow C1). At\nthe end of 3 years, he will have 3 animals (one\nparent cow C1 and 2 female calves B1 and B2, C1\nis the parent of B1 and B2).At the end of 4 \nyears,he will have 5 animals (one parent cow C1,\n3 offsprings of C1 i.e. B1, B2, B3 and one \noffspring of B1).\n" }, { "code": null, "e": 1632, "s": 1414, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function TotalAnimal() which takes N as input parameter and returns the total number of animals at the end of N years modulo 109 + 7.\n " }, { "code": null, "e": 1701, "s": 1632, "text": "Expected Time Complexity: O(log2N)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 1729, "s": 1701, "text": "Constraints:\n1 <= N <= 1018" }, { "code": null, "e": 1732, "s": 1729, "text": "+3" }, { "code": null, "e": 1761, "s": 1732, "text": "gauravtiwari30017 months ago" }, { "code": null, "e": 1856, "s": 1761, "text": "https://medium.com/codebrace/starred-problem-2-nth-fibonacci-number-in-log-n-time-821ea9a18296" }, { "code": null, "e": 1947, "s": 1856, "text": "This is a very good post on Medium explaining how to find a fibonacci Number in Logn time." }, { "code": null, "e": 2024, "s": 1947, "text": "Though I am posting the solution. Don't just blindly copy, paste and submit." }, { "code": null, "e": 2068, "s": 2024, "text": "Do give this post a read and understand it." }, { "code": null, "e": 3034, "s": 2068, "text": " \nvoid multiply(long long int mat[2][2],long long int m[2][2]){\n long long int temp[2][2];\n long long int x = 1000000007;\n temp[0][0]=mat[0][0]*m[0][0]+mat[0][1]*m[1][0];\n temp[0][1]= mat[0][0]*m[0][1]+mat[0][1]*m[1][1];\n temp[1][0]= mat[1][0]*m[0][0]+mat[1][1]*m[1][0];\n temp[1][1]= mat[1][0]*m[0][1]+mat[1][1]*m[1][1];\n mat[0][0]=temp[0][0]%x;\n mat[0][1]=temp[0][1]%x;\n mat[1][0]=temp[1][0]%x;\n mat[1][1]=temp[1][1]%x;\n}\n\nvoid mat_power(long long int mat[2][2],long long int n){\n if(n==1) return; // n==0 will never come\n \n mat_power(mat,n/2);\n multiply(mat,mat);\n \n long long int m[2][2]={\n {1,1},\n {1,0}\n }; \n if(n%2!=0)\n\t multiply(mat,m);\n}\n\n\n\t\n\t\n\t////////////////////////////////////////////*\n\tint TotalAnimal(long long int n){\n\t \n\t long long int mat[2][2]={\n {1,1},\n {1,0}\n }; \n if(n==0) return 1;\n mat_power(mat,n+1);\n return mat[0][1];\n\t // Code here\n\t}\n};" }, { "code": null, "e": 3037, "s": 3034, "text": "+1" }, { "code": null, "e": 3066, "s": 3037, "text": "gauravtiwari30017 months ago" }, { "code": null, "e": 3161, "s": 3066, "text": "https://medium.com/codebrace/starred-problem-2-nth-fibonacci-number-in-log-n-time-821ea9a18296" }, { "code": null, "e": 3252, "s": 3161, "text": "This is a very good post on Medium explaining how to find a fibonacci Number in Logn time." }, { "code": null, "e": 3329, "s": 3252, "text": "Though I am posting the solution. Don't just blindly copy, paste and submit." }, { "code": null, "e": 3373, "s": 3329, "text": "Do give this post a read and understand it." }, { "code": null, "e": 4339, "s": 3373, "text": " \nvoid multiply(long long int mat[2][2],long long int m[2][2]){\n long long int temp[2][2];\n long long int x = 1000000007;\n temp[0][0]=mat[0][0]*m[0][0]+mat[0][1]*m[1][0];\n temp[0][1]= mat[0][0]*m[0][1]+mat[0][1]*m[1][1];\n temp[1][0]= mat[1][0]*m[0][0]+mat[1][1]*m[1][0];\n temp[1][1]= mat[1][0]*m[0][1]+mat[1][1]*m[1][1];\n mat[0][0]=temp[0][0]%x;\n mat[0][1]=temp[0][1]%x;\n mat[1][0]=temp[1][0]%x;\n mat[1][1]=temp[1][1]%x;\n}\n\nvoid mat_power(long long int mat[2][2],long long int n){\n if(n==1) return; // n==0 will never come\n \n mat_power(mat,n/2);\n multiply(mat,mat);\n \n long long int m[2][2]={\n {1,1},\n {1,0}\n }; \n if(n%2!=0)\n\t multiply(mat,m);\n}\n\n\n\t\n\t\n\t////////////////////////////////////////////*\n\tint TotalAnimal(long long int n){\n\t \n\t long long int mat[2][2]={\n {1,1},\n {1,0}\n }; \n if(n==0) return 1;\n mat_power(mat,n+1);\n return mat[0][1];\n\t // Code here\n\t}\n};" }, { "code": null, "e": 4341, "s": 4339, "text": "0" }, { "code": null, "e": 4366, "s": 4341, "text": "shikhars31457 months ago" }, { "code": null, "e": 4433, "s": 4366, "text": "Can anybody explain how this question is same as fibonacci series?" }, { "code": null, "e": 4436, "s": 4433, "text": "+2" }, { "code": null, "e": 4462, "s": 4436, "text": "aijazhera27627 months ago" }, { "code": null, "e": 4541, "s": 4462, "text": "Easy explanation for solving the Fibonacci Sequence with Matrix Exponentiation" }, { "code": null, "e": 4585, "s": 4541, "text": "https://www.youtube.com/watch?v=EEb6JP3NXBI" }, { "code": null, "e": 4587, "s": 4585, "text": "0" }, { "code": null, "e": 4601, "s": 4587, "text": "aijazhera2762" }, { "code": null, "e": 4627, "s": 4601, "text": "This comment was deleted." }, { "code": null, "e": 4629, "s": 4627, "text": "0" }, { "code": null, "e": 4643, "s": 4629, "text": "aijazhera2762" }, { "code": null, "e": 4669, "s": 4643, "text": "This comment was deleted." }, { "code": null, "e": 4672, "s": 4669, "text": "-1" }, { "code": null, "e": 4686, "s": 4672, "text": "mridultyagi80" }, { "code": null, "e": 4712, "s": 4686, "text": "This comment was deleted." }, { "code": null, "e": 4715, "s": 4712, "text": "+3" }, { "code": null, "e": 4742, "s": 4715, "text": "ritintiwari4177 months ago" }, { "code": null, "e": 4890, "s": 4742, "text": "If you Program is working till 43 and giving you wrong answer for above, refer this article : https://www.geeksforgeeks.org/modulo-1097-1000000007/" }, { "code": null, "e": 4893, "s": 4890, "text": "+1" }, { "code": null, "e": 4907, "s": 4893, "text": "nishaanjum119" }, { "code": null, "e": 4933, "s": 4907, "text": "This comment was deleted." }, { "code": null, "e": 4935, "s": 4933, "text": "0" }, { "code": null, "e": 4964, "s": 4935, "text": "bhupeshbhatt82227 months ago" }, { "code": null, "e": 5029, "s": 4964, "text": "I am using the concept of fibonacci number, f(n) = f(n) + f(n-1)" }, { "code": null, "e": 5143, "s": 5029, "text": "This code is working fine for smaller numbers , but not workinbg for larger numbers . Can anyone tell the isssue?" }, { "code": null, "e": 5470, "s": 5145, "text": " int TotalAnimal(long long int N){ // Code here if(N==1||N==2||N==3) return N; int prev = 1, p_prev=1, curr; long long int i; int sum =3; for( i =3 ; i<N; i++) { curr= prev + p_prev; p_prev= prev; prev= curr; sum+=curr; } return sum;}" }, { "code": null, "e": 5616, "s": 5470, "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": 5652, "s": 5616, "text": " Login to access your submissions. " }, { "code": null, "e": 5662, "s": 5652, "text": "\nProblem\n" }, { "code": null, "e": 5672, "s": 5662, "text": "\nContest\n" }, { "code": null, "e": 5735, "s": 5672, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5883, "s": 5735, "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": 6091, "s": 5883, "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": 6197, "s": 6091, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Building a blood cell classification model using Keras and tfjs | by Narasimha Prasanna HN | Towards Data Science
AI is really a major game changer. Applications of AI are huge and it’s scope in the field of healthcare is vast. Advanced AI tools can assist doctors and lab technicians to diagnose diseases with better accuracy, for example a doctor in Nigeria can use this tool to identify a disease from a sample of blood which he is not at all aware of, this helps him to better understand the disease and thus cures can be developed in a faster way, this is one such advantage of democratizing AI, because AI models and tools are accessible world wide , a doctor in Nigeria can use the same tools and technologies that are being used by research scholars in MIT or any other great universities in the world. Machine Learning is of course the major ingredient of today’s AI advancements. But democratizing AI means making an infrastructure that allows anyone to build powerful tools using same techniques across the world. The two major problems that might forbid anyone from building AI are Computation Power and unavailability of datasets for training. But these problems are being addressed in interesting ways, they are as follows : Kaggle (Home of datasets) : Unavailability of datasets is one of the major problem, but Kaggle is the best place where people can create datasets and host them to make it available for others, people have built amazing things using these tools. Google co-lab : Google co-lab is the major driver of Machine Learning that allows anyone with google account to access a GPU. Without these GPUs it is impossible for anyone to train ML models that require huge computation. Dataset is like a gold-mine for Data Scientist, if dataset is available for a particular problem , it reduces a lot of effort required by engineering team , because there is no need for developing an infrastructure to collect and store data. Few months back I thought of developing this system , Kaggle helped me a lot to obtain the dataset. This is the dataset I found on Kaggle, thanks to Paul Mooney for making this available. Dataset Structure : The dataset contains 12,500 augmented images of blood cells. The dataset is comprised of 4 classes as shown below : Each of the class contains 3000 images. The figure shows sample images from each class: I reduced the size of each image to (80x80x3) to make it more easier to train. Kaggle requires you to login before downloading the dataset, since we are using colab, it is not required to download the dataset on our local machine, instead we pull it to our google colab instance. In simple words Google co-lab provides a cloud based python notebook with a virtual instance tied to a GPU runtime, the GPU runtime of google colab is powered by NVIDIA k-80, a powerful GPU and expensive too. But co-lab allows us to use the GPU for free without having to pay for it. Maximum time of an instance is 12 hours, after 12 hours the instance will be destroyed and new one will be created, so we can perform only those computations that doesn’t last longer than 12 hours. Let’s look at how we can use colab to train our Neural Network. Authenticate with Kaggle : Kaggle CLI allows you to download datasets and submit code/notebooks to competitions. Once you register for kaggle, you can download kaggle.json file which contains all credentials, kaggle CLI uses these credentials for authorization. Create a new cell and create a hidden directory called .kaggle , use the command !mkdir .kaggle Install Kaggle CLI using pip : In a new cell — !pip install kaggle Download the dataset: !kaggle datasets download -d paulthimothymooney/blood-cells Make sure all the directories are present in the downloaded dataset !ls dataset2-master/images You should see 3 directories : TEST, TEST_SIMPLE and TRAIN The directory TRAIN contains training images, we will be using this directory for training images. Pre-processing : We need to load images as numpy arrays and provide it to the neural network we are training. We will be using Keras to build a neural network, Keras provides a built-in ImageDataGenerator which handles most of the preprocessing tasks. We import some objects required for developing the model : from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Dropout, MaxPool2D, Flattenfrom keras.preprocessing import image keras.preprocessing provides methods and objects required to handle various types of datasets. from image module we create an ImageDataGenerator with all the required configuration. generator = image.ImageDataGenerator( rescale = 1./255, featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False) As stated in the previous section, the training data is present in `dataset2-master/images/TRAIN directory, we provide this path to ImageDataGenerator so that all our configurations and augmentations are applied on the training images. dataset = generator.flow_from_directory( shuffle = True, batch_size = 32, target_size = (80, 80), directory = 'dataset2-master/images/TRAIN') This is all about preprocessing, you can tweak these parameters to make even more better fit by either decreasing or increasing the effect of image augmentation, there is always a scope for improvement. A CNN (Convolution Neural network) is a Neural network, that contains a set of Convolution layers and a feed forward network attached to it. Convolution operation is not a new one, it is being used in Image Processing since many years. The major role of a Convolution operation is to extract edges from an image, in other terms, they can be used to extract important features of an image, if so called Filter Values are known, it is not possible for anyone to identify optimal filter values for any image , because we are using Convolution along with a Neural network, gradient descent will automatically optimize filter values to extract most important features of an image. Andrew Ng’s course deeplearning.ai helps you to better understand the working of such networks. As it is out of the scope of this article. CNNs are must required for this task, because it is not possible for a simple feed forward network to learn the unique features present in the each classes of the dataset. The architecture of the CNN we used is as shown below : I created a function model() that returns a sequential model as shown below: def model(): model = Sequential() model.add(Conv2D(80, (3,3), strides = (1, 1), activation = 'relu')) model.add(Conv2D(64, (3,3), strides = (1, 1), activation = 'relu', input_shape = (80, 80, 3))) model.add(MaxPool2D(pool_size = (2,2))) model.add(Conv2D(64, (3,3), strides = (1,1), activation = 'relu')) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation = 'relu')) model.add(Dropout(0.5)) model.add(Dense(4, activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = 'adadelta', metrics = ['accuracy']) return model Finally we train the model as shown : nn = model()nn.fit_generator(dataset, steps_per_epoch = None, epochs = 30, verbose = 1)nn.save('Model.h5') The model was trained for 30 epochs and accuracy of 92.67% was obtained, well this is a good accuracy, you can add more layers or perform hyperparameter tuning to improve the accuracy. Once training is done, we need to deploy the model to production, so that everyone can use it, There are various strategies available for deploying a machine learning system. I wanted to run the entire inference on client-machine, so I started building a web app which can do so. We require following requirements to build a client app , the app has following architecture : Install node and npm and have an environment set up , install following dependencies in same order : npm install -g create-react-appcreate-react-app app_namecd app_namenpm install --save @tensorflow/tfjs//on server side:mkdir servercd servernpm init//fill up the details, make sure package.json is creatednpm install express --save Model Server : This is a express.js REST endpoint, clients can request for the model file by sending a REST GET request. (on server side) Model Storage : We need to create a model that is compatible with tfjs, tensorflow provides a tool called tensorflowjs, it is a python toolkit that contains utilities, we can use following command to install it: pip install tensorflowjs once done, we can use tensorflowjs_converter to convert the model to tfjs format using below command : $tensorflowjs_converter --input_format keras \ Model.h5 \ ModelData/model_data// Model.h5 is the downloaded model after training, last argument is the target folder, where we need to store the model files. Once converted, it will create a group of files called shards, shards are obtained by splitting the model based on layers, each shard contains weights of a particular layer. Using shards is very helpful, as each shard can be stored on different places and can be downloaded when required, so we can build a distributed storage for out machine learning model. model.json is of course the file that contains information of each shard. We can modify this file if in case we change the directory of a shard. On API call we only send model.json file to the client, tfjs will automatically fetch each shard to assemble a model on the client machine, i.e the browser. In this section, I will not be stressing much on the UI design, instead I will stress upon the inference part, i.e how to run inference using tfjs , we installed. Go the react app directory. Create a model container class : I first created a wrapper class for our model. An instance of this class represents a model that is ready for inference. The code of this model class is self understandable : An inference function : I defined a function that can take model object and input image source, the input source can be HTML img , or a URL , or a byte stream of an image. The code is as shown: Initializing model object : We now have to create model object that can hold a model for inference. let modelCache = new ModelContainer(null);modelCache.loadFromURL('http://192.168.0.105:5443/model_metadata') Running inference : Once we have a model object, we can run inference anytime we want, According to the UI I designed, the inference should be executed whenever user clicks on predict button. So the part of React component which runs prediction is as shown below: This project was really a great experience for me, I learnt how to use google colab for training ML models on the cloud, I also learnt how to deploy ML models for production. This is an open source project, feel free to make changes : REPO URL : react-client Cloud Notebook (For model training): training.ipynb Thank you so much for spending your valuable time for reading this article. Kindly start the repo, if you are interested. You can also connect with me on Linkedin.
[ { "code": null, "e": 869, "s": 172, "text": "AI is really a major game changer. Applications of AI are huge and it’s scope in the field of healthcare is vast. Advanced AI tools can assist doctors and lab technicians to diagnose diseases with better accuracy, for example a doctor in Nigeria can use this tool to identify a disease from a sample of blood which he is not at all aware of, this helps him to better understand the disease and thus cures can be developed in a faster way, this is one such advantage of democratizing AI, because AI models and tools are accessible world wide , a doctor in Nigeria can use the same tools and technologies that are being used by research scholars in MIT or any other great universities in the world." }, { "code": null, "e": 1297, "s": 869, "text": "Machine Learning is of course the major ingredient of today’s AI advancements. But democratizing AI means making an infrastructure that allows anyone to build powerful tools using same techniques across the world. The two major problems that might forbid anyone from building AI are Computation Power and unavailability of datasets for training. But these problems are being addressed in interesting ways, they are as follows :" }, { "code": null, "e": 1542, "s": 1297, "text": "Kaggle (Home of datasets) : Unavailability of datasets is one of the major problem, but Kaggle is the best place where people can create datasets and host them to make it available for others, people have built amazing things using these tools." }, { "code": null, "e": 1765, "s": 1542, "text": "Google co-lab : Google co-lab is the major driver of Machine Learning that allows anyone with google account to access a GPU. Without these GPUs it is impossible for anyone to train ML models that require huge computation." }, { "code": null, "e": 2195, "s": 1765, "text": "Dataset is like a gold-mine for Data Scientist, if dataset is available for a particular problem , it reduces a lot of effort required by engineering team , because there is no need for developing an infrastructure to collect and store data. Few months back I thought of developing this system , Kaggle helped me a lot to obtain the dataset. This is the dataset I found on Kaggle, thanks to Paul Mooney for making this available." }, { "code": null, "e": 2331, "s": 2195, "text": "Dataset Structure : The dataset contains 12,500 augmented images of blood cells. The dataset is comprised of 4 classes as shown below :" }, { "code": null, "e": 2419, "s": 2331, "text": "Each of the class contains 3000 images. The figure shows sample images from each class:" }, { "code": null, "e": 2498, "s": 2419, "text": "I reduced the size of each image to (80x80x3) to make it more easier to train." }, { "code": null, "e": 2699, "s": 2498, "text": "Kaggle requires you to login before downloading the dataset, since we are using colab, it is not required to download the dataset on our local machine, instead we pull it to our google colab instance." }, { "code": null, "e": 3245, "s": 2699, "text": "In simple words Google co-lab provides a cloud based python notebook with a virtual instance tied to a GPU runtime, the GPU runtime of google colab is powered by NVIDIA k-80, a powerful GPU and expensive too. But co-lab allows us to use the GPU for free without having to pay for it. Maximum time of an instance is 12 hours, after 12 hours the instance will be destroyed and new one will be created, so we can perform only those computations that doesn’t last longer than 12 hours. Let’s look at how we can use colab to train our Neural Network." }, { "code": null, "e": 3272, "s": 3245, "text": "Authenticate with Kaggle :" }, { "code": null, "e": 3507, "s": 3272, "text": "Kaggle CLI allows you to download datasets and submit code/notebooks to competitions. Once you register for kaggle, you can download kaggle.json file which contains all credentials, kaggle CLI uses these credentials for authorization." }, { "code": null, "e": 3603, "s": 3507, "text": "Create a new cell and create a hidden directory called .kaggle , use the command !mkdir .kaggle" }, { "code": null, "e": 3670, "s": 3603, "text": "Install Kaggle CLI using pip : In a new cell — !pip install kaggle" }, { "code": null, "e": 3752, "s": 3670, "text": "Download the dataset: !kaggle datasets download -d paulthimothymooney/blood-cells" }, { "code": null, "e": 3847, "s": 3752, "text": "Make sure all the directories are present in the downloaded dataset !ls dataset2-master/images" }, { "code": null, "e": 3906, "s": 3847, "text": "You should see 3 directories : TEST, TEST_SIMPLE and TRAIN" }, { "code": null, "e": 4005, "s": 3906, "text": "The directory TRAIN contains training images, we will be using this directory for training images." }, { "code": null, "e": 4022, "s": 4005, "text": "Pre-processing :" }, { "code": null, "e": 4257, "s": 4022, "text": "We need to load images as numpy arrays and provide it to the neural network we are training. We will be using Keras to build a neural network, Keras provides a built-in ImageDataGenerator which handles most of the preprocessing tasks." }, { "code": null, "e": 4316, "s": 4257, "text": "We import some objects required for developing the model :" }, { "code": null, "e": 4456, "s": 4316, "text": "from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Dropout, MaxPool2D, Flattenfrom keras.preprocessing import image" }, { "code": null, "e": 4638, "s": 4456, "text": "keras.preprocessing provides methods and objects required to handle various types of datasets. from image module we create an ImageDataGenerator with all the required configuration." }, { "code": null, "e": 5398, "s": 4638, "text": "generator = image.ImageDataGenerator( rescale = 1./255, featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False)" }, { "code": null, "e": 5634, "s": 5398, "text": "As stated in the previous section, the training data is present in `dataset2-master/images/TRAIN directory, we provide this path to ImageDataGenerator so that all our configurations and augmentations are applied on the training images." }, { "code": null, "e": 5788, "s": 5634, "text": "dataset = generator.flow_from_directory( shuffle = True, batch_size = 32, target_size = (80, 80), directory = 'dataset2-master/images/TRAIN')" }, { "code": null, "e": 5991, "s": 5788, "text": "This is all about preprocessing, you can tweak these parameters to make even more better fit by either decreasing or increasing the effect of image augmentation, there is always a scope for improvement." }, { "code": null, "e": 6806, "s": 5991, "text": "A CNN (Convolution Neural network) is a Neural network, that contains a set of Convolution layers and a feed forward network attached to it. Convolution operation is not a new one, it is being used in Image Processing since many years. The major role of a Convolution operation is to extract edges from an image, in other terms, they can be used to extract important features of an image, if so called Filter Values are known, it is not possible for anyone to identify optimal filter values for any image , because we are using Convolution along with a Neural network, gradient descent will automatically optimize filter values to extract most important features of an image. Andrew Ng’s course deeplearning.ai helps you to better understand the working of such networks. As it is out of the scope of this article." }, { "code": null, "e": 7034, "s": 6806, "text": "CNNs are must required for this task, because it is not possible for a simple feed forward network to learn the unique features present in the each classes of the dataset. The architecture of the CNN we used is as shown below :" }, { "code": null, "e": 7111, "s": 7034, "text": "I created a function model() that returns a sequential model as shown below:" }, { "code": null, "e": 7722, "s": 7111, "text": "def model(): model = Sequential() model.add(Conv2D(80, (3,3), strides = (1, 1), activation = 'relu')) model.add(Conv2D(64, (3,3), strides = (1, 1), activation = 'relu', input_shape = (80, 80, 3))) model.add(MaxPool2D(pool_size = (2,2))) model.add(Conv2D(64, (3,3), strides = (1,1), activation = 'relu')) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation = 'relu')) model.add(Dropout(0.5)) model.add(Dense(4, activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = 'adadelta', metrics = ['accuracy']) return model" }, { "code": null, "e": 7760, "s": 7722, "text": "Finally we train the model as shown :" }, { "code": null, "e": 7867, "s": 7760, "text": "nn = model()nn.fit_generator(dataset, steps_per_epoch = None, epochs = 30, verbose = 1)nn.save('Model.h5')" }, { "code": null, "e": 8052, "s": 7867, "text": "The model was trained for 30 epochs and accuracy of 92.67% was obtained, well this is a good accuracy, you can add more layers or perform hyperparameter tuning to improve the accuracy." }, { "code": null, "e": 8332, "s": 8052, "text": "Once training is done, we need to deploy the model to production, so that everyone can use it, There are various strategies available for deploying a machine learning system. I wanted to run the entire inference on client-machine, so I started building a web app which can do so." }, { "code": null, "e": 8427, "s": 8332, "text": "We require following requirements to build a client app , the app has following architecture :" }, { "code": null, "e": 8528, "s": 8427, "text": "Install node and npm and have an environment set up , install following dependencies in same order :" }, { "code": null, "e": 8759, "s": 8528, "text": "npm install -g create-react-appcreate-react-app app_namecd app_namenpm install --save @tensorflow/tfjs//on server side:mkdir servercd servernpm init//fill up the details, make sure package.json is creatednpm install express --save" }, { "code": null, "e": 8897, "s": 8759, "text": "Model Server : This is a express.js REST endpoint, clients can request for the model file by sending a REST GET request. (on server side)" }, { "code": null, "e": 9134, "s": 8897, "text": "Model Storage : We need to create a model that is compatible with tfjs, tensorflow provides a tool called tensorflowjs, it is a python toolkit that contains utilities, we can use following command to install it: pip install tensorflowjs" }, { "code": null, "e": 9237, "s": 9134, "text": "once done, we can use tensorflowjs_converter to convert the model to tfjs format using below command :" }, { "code": null, "e": 9489, "s": 9237, "text": "$tensorflowjs_converter --input_format keras \\ Model.h5 \\ ModelData/model_data// Model.h5 is the downloaded model after training, last argument is the target folder, where we need to store the model files." }, { "code": null, "e": 10150, "s": 9489, "text": "Once converted, it will create a group of files called shards, shards are obtained by splitting the model based on layers, each shard contains weights of a particular layer. Using shards is very helpful, as each shard can be stored on different places and can be downloaded when required, so we can build a distributed storage for out machine learning model. model.json is of course the file that contains information of each shard. We can modify this file if in case we change the directory of a shard. On API call we only send model.json file to the client, tfjs will automatically fetch each shard to assemble a model on the client machine, i.e the browser." }, { "code": null, "e": 10341, "s": 10150, "text": "In this section, I will not be stressing much on the UI design, instead I will stress upon the inference part, i.e how to run inference using tfjs , we installed. Go the react app directory." }, { "code": null, "e": 10549, "s": 10341, "text": "Create a model container class : I first created a wrapper class for our model. An instance of this class represents a model that is ready for inference. The code of this model class is self understandable :" }, { "code": null, "e": 10721, "s": 10549, "text": "An inference function : I defined a function that can take model object and input image source, the input source can be HTML img , or a URL , or a byte stream of an image." }, { "code": null, "e": 10743, "s": 10721, "text": "The code is as shown:" }, { "code": null, "e": 10843, "s": 10743, "text": "Initializing model object : We now have to create model object that can hold a model for inference." }, { "code": null, "e": 10952, "s": 10843, "text": "let modelCache = new ModelContainer(null);modelCache.loadFromURL('http://192.168.0.105:5443/model_metadata')" }, { "code": null, "e": 11216, "s": 10952, "text": "Running inference : Once we have a model object, we can run inference anytime we want, According to the UI I designed, the inference should be executed whenever user clicks on predict button. So the part of React component which runs prediction is as shown below:" }, { "code": null, "e": 11391, "s": 11216, "text": "This project was really a great experience for me, I learnt how to use google colab for training ML models on the cloud, I also learnt how to deploy ML models for production." }, { "code": null, "e": 11451, "s": 11391, "text": "This is an open source project, feel free to make changes :" }, { "code": null, "e": 11475, "s": 11451, "text": "REPO URL : react-client" }, { "code": null, "e": 11527, "s": 11475, "text": "Cloud Notebook (For model training): training.ipynb" } ]
Cross-Validation in R programming - GeeksforGeeks
15 Sep, 2021 The major challenge in designing a machine learning model is to make it work accurately on the unseen data. To know whether the designed model is working fine or not, we have to test it against those data points which were not present during the training of the model. These data points will serve the purpose of unseen data for the model, and it becomes easy to evaluate the model’s accuracy. One of the finest techniques to check the effectiveness of a machine learning model is Cross-validation techniques which can be easily implemented by using the R programming language. In this, a portion of the data set is reserved which will not be used in training the model. Once the model is ready, that reserved data set is used for testing purposes. Values of the dependent variable are predicted during the testing phase and the model accuracy is calculated on the basis of prediction error i.e., the difference in actual values and predicted values of the dependent variable. There are several statistical metrics that are used for evaluating the accuracy of regression models: Root Mean Squared Error (RMSE): As the name suggests it is the square root of the averaged squared difference between the actual value and the predicted value of the target variable. It gives the average prediction error made by the model, thus decrease the RMSE value to increase the accuracy of the model.Mean Absolute Error (MAE): This metric gives the absolute difference between the actual values and the values predicted by the model for the target variable. If the value of the outliers does not have much to do with the accuracy of the model, then MAE can be used to evaluate the performance of the model. Its value must be less in order to make better models.R2 Error: The value of the R-squared metric gives an idea about how much percentage of variance in the dependent variable is explained collectively by the independent variables. In other words, it reflects the relationship strength between the target variable and the model on a scale of 0 – 100%. So, a better model should have a high value of R-squared. Root Mean Squared Error (RMSE): As the name suggests it is the square root of the averaged squared difference between the actual value and the predicted value of the target variable. It gives the average prediction error made by the model, thus decrease the RMSE value to increase the accuracy of the model. Mean Absolute Error (MAE): This metric gives the absolute difference between the actual values and the values predicted by the model for the target variable. If the value of the outliers does not have much to do with the accuracy of the model, then MAE can be used to evaluate the performance of the model. Its value must be less in order to make better models. R2 Error: The value of the R-squared metric gives an idea about how much percentage of variance in the dependent variable is explained collectively by the independent variables. In other words, it reflects the relationship strength between the target variable and the model on a scale of 0 – 100%. So, a better model should have a high value of R-squared. During the process of partitioning the complete dataset into the training set and the validation set, there are chances of losing some important and crucial data points for the training purpose. Since those data are not included in the training set, the model has not got the chance to detect some patterns. This situation can lead to overfitting or under fitting of the model. To avoid this, there are different types of cross-validation techniques that guarantees the random sampling of training and validation data set and maximizes the accuracy of the model. Some of the most popular cross-validation techniques are Validation Set Approach Leave one out cross-validation(LOOCV) K-fold cross-Validation Repeated K-fold cross-validation To implement linear regression, we are using a marketing dataset which is an inbuilt dataset in R programming language. Below is the code to import this dataset into your R programming environment. R # loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # installing package to# import desired datasetinstall.packages("datarium") # loading the datasetdata("marketing", package = "datarium") # inspecting the datasethead(marketing) Output: youtube facebook newspaper sales 1 276.12 45.36 83.04 26.52 2 53.40 47.16 54.12 12.48 3 20.64 55.08 83.16 11.16 4 181.80 49.56 70.20 22.20 5 216.96 12.96 70.08 15.48 6 10.44 58.68 90.00 8.64 In this method, the dataset is divided randomly into training and testing sets. Following steps are performed to implement this technique: A random sampling of the datasetModel is trained on the training data setThe resultant model is applied to the testing data setCalculate prediction error by using model performance metrics A random sampling of the dataset Model is trained on the training data set The resultant model is applied to the testing data set Calculate prediction error by using model performance metrics Below is the implementation of this method: R # R program to implement# validation set approach # setting seed to generate a# reproducible random samplingset.seed(123) # creating training data as 80% of the datasetrandom_sample <- createDataPartition(marketing $ sales, p = 0.8, list = FALSE) # generating training dataset# from the random_sampletraining_dataset <- marketing[random_sample, ] # generating testing dataset# from rows which are not# included in random_sampletesting_dataset <- marketing[-random_sample, ] # Building the model # training the model by assigning sales column# as target variable and rest other columns# as independent variablesmodel <- lm(sales ~., data = training_dataset) # predicting the target variablepredictions <- predict(model, testing_dataset) # computing model performance metricsdata.frame( R2 = R2(predictions, testing_dataset $ sales), RMSE = RMSE(predictions, testing_dataset $ sales), MAE = MAE(predictions, testing_dataset $ sales)) Output: R2 RMSE MAE 1 0.9049049 1.965508 1.433609 Advantages: One of the most basic and simple techniques for evaluating a model. No complex steps for implementation. Disadvantages: Predictions done by the model is highly dependent upon the subset of observations used for training and validation. Using only one subset of the data for training purposes can make the model biased. This method also splits the dataset into 2 parts but it overcomes the drawbacks of the Validation set approach. LOOCV carry out the cross-validation in the following way: Train the model on N-1 data pointsTesting the model against that one data points which was left in the previous stepCalculate prediction errorRepeat above 3 steps until the model is not trained and tested on all data pointsGenerate overall prediction error by taking the average of prediction errors in every case Train the model on N-1 data points Testing the model against that one data points which was left in the previous step Calculate prediction error Repeat above 3 steps until the model is not trained and tested on all data points Generate overall prediction error by taking the average of prediction errors in every case Below is the implementation of this method: R # R program to implement# Leave one out cross validation # defining training control# as Leave One Out Cross Validationtrain_control <- trainControl(method = "LOOCV") # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = "lm", trControl = train_control) # printing model performance metrics# along with other detailsprint(model) Output: Linear Regression 200 samples 3 predictor No pre-processing Resampling: Leave-One-Out Cross-Validation Summary of sample sizes: 199, 199, 199, 199, 199, 199, ... Resampling results: RMSE Rsquared MAE 2.059984 0.8912074 1.539441 Tuning parameter 'intercept' was held constant at a value of TRUE Advantages: Less bias model as almost every data point is used for training. No randomness in the value of performance metrics because LOOCV runs multiple times on the dataset Disadvantages: Training the model N times leads to expensive computation time if the dataset is large. This cross-validation technique divides the data into K subsets(folds) of almost equal size. Out of these K folds, one subset is used as a validation set, and rest others are involved in training the model. Following are the complete working procedure of this method: Split the dataset into K subsets randomlyUse K-1 subsets for training the modelTest the model against that one subset that was left in the previous stepRepeat the above steps for K times i.e., until the model is not trained and tested on all subsetsGenerate overall prediction error by taking the average of prediction errors in every case Split the dataset into K subsets randomly Use K-1 subsets for training the model Test the model against that one subset that was left in the previous step Repeat the above steps for K times i.e., until the model is not trained and tested on all subsets Generate overall prediction error by taking the average of prediction errors in every case Below is the implementation of this method: R # R program to implement# K-fold cross-validation # setting seed to generate a# reproducible random samplingset.seed(125) # defining training control# as cross-validation and# value of K equal to 10train_control <- trainControl(method = "cv", number = 10) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = "lm", trControl = train_control) # printing model performance metrics# along with other detailsprint(model) Output: Linear Regression 200 samples 3 predictor No pre-processing Resampling: Cross-Validated (10 fold) Summary of sample sizes: 181, 180, 180, 179, 180, 180, ... Resampling results: RMSE Rsquared MAE 2.027409 0.9041909 1.539866 Tuning parameter 'intercept' was held constant at a value of TRUE Advantages: Fast computation speed. A very effective method to estimate the prediction error and the accuracy of a model. Disadvantages: A lower value of K leads to a biased model and a higher value of K can lead to variability in the performance metrics of the model. Thus, it is very important to use the correct value of K for the model(generally K = 5 and K = 10 is desirable). As the name suggests, in this method the K-fold cross-validation algorithm is repeated a certain number of times. Below is the implementation of this method: R # R program to implement# repeated K-fold cross-validation # setting seed to generate a# reproducible random samplingset.seed(125) # defining training control as# repeated cross-validation and# value of K is 10 and repetition is 3 timestrain_control <- trainControl(method = "repeatedcv", number = 10, repeats = 3) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = "lm", trControl = train_control) # printing model performance metrics# along with other detailsprint(model) Output: Linear Regression 200 samples 3 predictor No pre-processing Resampling: Cross-Validated (10 fold, repeated 3 times) Summary of sample sizes: 181, 180, 180, 179, 180, 180, ... Resampling results: RMSE Rsquared MAE 2.020061 0.9038559 1.541517 Tuning parameter 'intercept' was held constant at a value of TRUE Advantages: In each repetition, the data sample is shuffled which results in developing different splits of the sample data. Disadvantages: With each repetition, the algorithm has to train the model from scratch which means the computation time to evaluate the model increases by the times of repetition. Note: The most preferred cross-validation technique is repeated K-fold cross-validation for both regression and classification machine learning model. arorakashish0911 simranarora5sos R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Printing Output of an R Program How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming
[ { "code": null, "e": 26503, "s": 26475, "text": "\n15 Sep, 2021" }, { "code": null, "e": 27582, "s": 26503, "text": "The major challenge in designing a machine learning model is to make it work accurately on the unseen data. To know whether the designed model is working fine or not, we have to test it against those data points which were not present during the training of the model. These data points will serve the purpose of unseen data for the model, and it becomes easy to evaluate the model’s accuracy. One of the finest techniques to check the effectiveness of a machine learning model is Cross-validation techniques which can be easily implemented by using the R programming language. In this, a portion of the data set is reserved which will not be used in training the model. Once the model is ready, that reserved data set is used for testing purposes. Values of the dependent variable are predicted during the testing phase and the model accuracy is calculated on the basis of prediction error i.e., the difference in actual values and predicted values of the dependent variable. There are several statistical metrics that are used for evaluating the accuracy of regression models:" }, { "code": null, "e": 28606, "s": 27582, "text": "Root Mean Squared Error (RMSE): As the name suggests it is the square root of the averaged squared difference between the actual value and the predicted value of the target variable. It gives the average prediction error made by the model, thus decrease the RMSE value to increase the accuracy of the model.Mean Absolute Error (MAE): This metric gives the absolute difference between the actual values and the values predicted by the model for the target variable. If the value of the outliers does not have much to do with the accuracy of the model, then MAE can be used to evaluate the performance of the model. Its value must be less in order to make better models.R2 Error: The value of the R-squared metric gives an idea about how much percentage of variance in the dependent variable is explained collectively by the independent variables. In other words, it reflects the relationship strength between the target variable and the model on a scale of 0 – 100%. So, a better model should have a high value of R-squared." }, { "code": null, "e": 28914, "s": 28606, "text": "Root Mean Squared Error (RMSE): As the name suggests it is the square root of the averaged squared difference between the actual value and the predicted value of the target variable. It gives the average prediction error made by the model, thus decrease the RMSE value to increase the accuracy of the model." }, { "code": null, "e": 29276, "s": 28914, "text": "Mean Absolute Error (MAE): This metric gives the absolute difference between the actual values and the values predicted by the model for the target variable. If the value of the outliers does not have much to do with the accuracy of the model, then MAE can be used to evaluate the performance of the model. Its value must be less in order to make better models." }, { "code": null, "e": 29632, "s": 29276, "text": "R2 Error: The value of the R-squared metric gives an idea about how much percentage of variance in the dependent variable is explained collectively by the independent variables. In other words, it reflects the relationship strength between the target variable and the model on a scale of 0 – 100%. So, a better model should have a high value of R-squared." }, { "code": null, "e": 30252, "s": 29632, "text": "During the process of partitioning the complete dataset into the training set and the validation set, there are chances of losing some important and crucial data points for the training purpose. Since those data are not included in the training set, the model has not got the chance to detect some patterns. This situation can lead to overfitting or under fitting of the model. To avoid this, there are different types of cross-validation techniques that guarantees the random sampling of training and validation data set and maximizes the accuracy of the model. Some of the most popular cross-validation techniques are" }, { "code": null, "e": 30276, "s": 30252, "text": "Validation Set Approach" }, { "code": null, "e": 30314, "s": 30276, "text": "Leave one out cross-validation(LOOCV)" }, { "code": null, "e": 30338, "s": 30314, "text": "K-fold cross-Validation" }, { "code": null, "e": 30371, "s": 30338, "text": "Repeated K-fold cross-validation" }, { "code": null, "e": 30569, "s": 30371, "text": "To implement linear regression, we are using a marketing dataset which is an inbuilt dataset in R programming language. Below is the code to import this dataset into your R programming environment." }, { "code": null, "e": 30571, "s": 30569, "text": "R" }, { "code": "# loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # installing package to# import desired datasetinstall.packages(\"datarium\") # loading the datasetdata(\"marketing\", package = \"datarium\") # inspecting the datasethead(marketing)", "e": 30915, "s": 30571, "text": null }, { "code": null, "e": 30923, "s": 30915, "text": "Output:" }, { "code": null, "e": 31169, "s": 30923, "text": " youtube facebook newspaper sales\n1 276.12 45.36 83.04 26.52\n2 53.40 47.16 54.12 12.48\n3 20.64 55.08 83.16 11.16\n4 181.80 49.56 70.20 22.20\n5 216.96 12.96 70.08 15.48\n6 10.44 58.68 90.00 8.64" }, { "code": null, "e": 31308, "s": 31169, "text": "In this method, the dataset is divided randomly into training and testing sets. Following steps are performed to implement this technique:" }, { "code": null, "e": 31497, "s": 31308, "text": "A random sampling of the datasetModel is trained on the training data setThe resultant model is applied to the testing data setCalculate prediction error by using model performance metrics" }, { "code": null, "e": 31530, "s": 31497, "text": "A random sampling of the dataset" }, { "code": null, "e": 31572, "s": 31530, "text": "Model is trained on the training data set" }, { "code": null, "e": 31627, "s": 31572, "text": "The resultant model is applied to the testing data set" }, { "code": null, "e": 31689, "s": 31627, "text": "Calculate prediction error by using model performance metrics" }, { "code": null, "e": 31733, "s": 31689, "text": "Below is the implementation of this method:" }, { "code": null, "e": 31735, "s": 31733, "text": "R" }, { "code": "# R program to implement# validation set approach # setting seed to generate a# reproducible random samplingset.seed(123) # creating training data as 80% of the datasetrandom_sample <- createDataPartition(marketing $ sales, p = 0.8, list = FALSE) # generating training dataset# from the random_sampletraining_dataset <- marketing[random_sample, ] # generating testing dataset# from rows which are not# included in random_sampletesting_dataset <- marketing[-random_sample, ] # Building the model # training the model by assigning sales column# as target variable and rest other columns# as independent variablesmodel <- lm(sales ~., data = training_dataset) # predicting the target variablepredictions <- predict(model, testing_dataset) # computing model performance metricsdata.frame( R2 = R2(predictions, testing_dataset $ sales), RMSE = RMSE(predictions, testing_dataset $ sales), MAE = MAE(predictions, testing_dataset $ sales))", "e": 32721, "s": 31735, "text": null }, { "code": null, "e": 32729, "s": 32721, "text": "Output:" }, { "code": null, "e": 32787, "s": 32729, "text": " R2 RMSE MAE\n1 0.9049049 1.965508 1.433609" }, { "code": null, "e": 32799, "s": 32787, "text": "Advantages:" }, { "code": null, "e": 32867, "s": 32799, "text": "One of the most basic and simple techniques for evaluating a model." }, { "code": null, "e": 32904, "s": 32867, "text": "No complex steps for implementation." }, { "code": null, "e": 32919, "s": 32904, "text": "Disadvantages:" }, { "code": null, "e": 33035, "s": 32919, "text": "Predictions done by the model is highly dependent upon the subset of observations used for training and validation." }, { "code": null, "e": 33118, "s": 33035, "text": "Using only one subset of the data for training purposes can make the model biased." }, { "code": null, "e": 33289, "s": 33118, "text": "This method also splits the dataset into 2 parts but it overcomes the drawbacks of the Validation set approach. LOOCV carry out the cross-validation in the following way:" }, { "code": null, "e": 33603, "s": 33289, "text": "Train the model on N-1 data pointsTesting the model against that one data points which was left in the previous stepCalculate prediction errorRepeat above 3 steps until the model is not trained and tested on all data pointsGenerate overall prediction error by taking the average of prediction errors in every case" }, { "code": null, "e": 33638, "s": 33603, "text": "Train the model on N-1 data points" }, { "code": null, "e": 33721, "s": 33638, "text": "Testing the model against that one data points which was left in the previous step" }, { "code": null, "e": 33748, "s": 33721, "text": "Calculate prediction error" }, { "code": null, "e": 33830, "s": 33748, "text": "Repeat above 3 steps until the model is not trained and tested on all data points" }, { "code": null, "e": 33921, "s": 33830, "text": "Generate overall prediction error by taking the average of prediction errors in every case" }, { "code": null, "e": 33965, "s": 33921, "text": "Below is the implementation of this method:" }, { "code": null, "e": 33967, "s": 33965, "text": "R" }, { "code": "# R program to implement# Leave one out cross validation # defining training control# as Leave One Out Cross Validationtrain_control <- trainControl(method = \"LOOCV\") # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = \"lm\", trControl = train_control) # printing model performance metrics# along with other detailsprint(model)", "e": 34435, "s": 33967, "text": null }, { "code": null, "e": 34444, "s": 34435, "text": "Output: " }, { "code": null, "e": 34765, "s": 34444, "text": "Linear Regression \n\n200 samples\n 3 predictor\n\nNo pre-processing\nResampling: Leave-One-Out Cross-Validation \nSummary of sample sizes: 199, 199, 199, 199, 199, 199, ... \nResampling results:\n\n RMSE Rsquared MAE \n 2.059984 0.8912074 1.539441\n\nTuning parameter 'intercept' was held constant at a value of TRUE" }, { "code": null, "e": 34777, "s": 34765, "text": "Advantages:" }, { "code": null, "e": 34842, "s": 34777, "text": "Less bias model as almost every data point is used for training." }, { "code": null, "e": 34941, "s": 34842, "text": "No randomness in the value of performance metrics because LOOCV runs multiple times on the dataset" }, { "code": null, "e": 34956, "s": 34941, "text": "Disadvantages:" }, { "code": null, "e": 35044, "s": 34956, "text": "Training the model N times leads to expensive computation time if the dataset is large." }, { "code": null, "e": 35312, "s": 35044, "text": "This cross-validation technique divides the data into K subsets(folds) of almost equal size. Out of these K folds, one subset is used as a validation set, and rest others are involved in training the model. Following are the complete working procedure of this method:" }, { "code": null, "e": 35652, "s": 35312, "text": "Split the dataset into K subsets randomlyUse K-1 subsets for training the modelTest the model against that one subset that was left in the previous stepRepeat the above steps for K times i.e., until the model is not trained and tested on all subsetsGenerate overall prediction error by taking the average of prediction errors in every case" }, { "code": null, "e": 35694, "s": 35652, "text": "Split the dataset into K subsets randomly" }, { "code": null, "e": 35733, "s": 35694, "text": "Use K-1 subsets for training the model" }, { "code": null, "e": 35807, "s": 35733, "text": "Test the model against that one subset that was left in the previous step" }, { "code": null, "e": 35905, "s": 35807, "text": "Repeat the above steps for K times i.e., until the model is not trained and tested on all subsets" }, { "code": null, "e": 35996, "s": 35905, "text": "Generate overall prediction error by taking the average of prediction errors in every case" }, { "code": null, "e": 36040, "s": 35996, "text": "Below is the implementation of this method:" }, { "code": null, "e": 36042, "s": 36040, "text": "R" }, { "code": "# R program to implement# K-fold cross-validation # setting seed to generate a# reproducible random samplingset.seed(125) # defining training control# as cross-validation and# value of K equal to 10train_control <- trainControl(method = \"cv\", number = 10) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = \"lm\", trControl = train_control) # printing model performance metrics# along with other detailsprint(model)", "e": 36628, "s": 36042, "text": null }, { "code": null, "e": 36636, "s": 36628, "text": "Output:" }, { "code": null, "e": 36952, "s": 36636, "text": "Linear Regression \n\n200 samples\n 3 predictor\n\nNo pre-processing\nResampling: Cross-Validated (10 fold) \nSummary of sample sizes: 181, 180, 180, 179, 180, 180, ... \nResampling results:\n\n RMSE Rsquared MAE \n 2.027409 0.9041909 1.539866\n\nTuning parameter 'intercept' was held constant at a value of TRUE" }, { "code": null, "e": 36964, "s": 36952, "text": "Advantages:" }, { "code": null, "e": 36988, "s": 36964, "text": "Fast computation speed." }, { "code": null, "e": 37074, "s": 36988, "text": "A very effective method to estimate the prediction error and the accuracy of a model." }, { "code": null, "e": 37089, "s": 37074, "text": "Disadvantages:" }, { "code": null, "e": 37334, "s": 37089, "text": "A lower value of K leads to a biased model and a higher value of K can lead to variability in the performance metrics of the model. Thus, it is very important to use the correct value of K for the model(generally K = 5 and K = 10 is desirable)." }, { "code": null, "e": 37492, "s": 37334, "text": "As the name suggests, in this method the K-fold cross-validation algorithm is repeated a certain number of times. Below is the implementation of this method:" }, { "code": null, "e": 37494, "s": 37492, "text": "R" }, { "code": "# R program to implement# repeated K-fold cross-validation # setting seed to generate a# reproducible random samplingset.seed(125) # defining training control as# repeated cross-validation and# value of K is 10 and repetition is 3 timestrain_control <- trainControl(method = \"repeatedcv\", number = 10, repeats = 3) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = \"lm\", trControl = train_control) # printing model performance metrics# along with other detailsprint(model)", "e": 38137, "s": 37494, "text": null }, { "code": null, "e": 38145, "s": 38137, "text": "Output:" }, { "code": null, "e": 38479, "s": 38145, "text": "Linear Regression \n\n200 samples\n 3 predictor\n\nNo pre-processing\nResampling: Cross-Validated (10 fold, repeated 3 times) \nSummary of sample sizes: 181, 180, 180, 179, 180, 180, ... \nResampling results:\n\n RMSE Rsquared MAE \n 2.020061 0.9038559 1.541517\n\nTuning parameter 'intercept' was held constant at a value of TRUE" }, { "code": null, "e": 38491, "s": 38479, "text": "Advantages:" }, { "code": null, "e": 38604, "s": 38491, "text": "In each repetition, the data sample is shuffled which results in developing different splits of the sample data." }, { "code": null, "e": 38619, "s": 38604, "text": "Disadvantages:" }, { "code": null, "e": 38784, "s": 38619, "text": "With each repetition, the algorithm has to train the model from scratch which means the computation time to evaluate the model increases by the times of repetition." }, { "code": null, "e": 38935, "s": 38784, "text": "Note: The most preferred cross-validation technique is repeated K-fold cross-validation for both regression and classification machine learning model." }, { "code": null, "e": 38954, "s": 38937, "text": "arorakashish0911" }, { "code": null, "e": 38970, "s": 38954, "text": "simranarora5sos" }, { "code": null, "e": 38985, "s": 38970, "text": "R Data-science" }, { "code": null, "e": 39004, "s": 38985, "text": "R Machine-Learning" }, { "code": null, "e": 39015, "s": 39004, "text": "R Language" }, { "code": null, "e": 39113, "s": 39015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39171, "s": 39113, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 39223, "s": 39171, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 39255, "s": 39223, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 39299, "s": 39255, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 39351, "s": 39299, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 39386, "s": 39351, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 39424, "s": 39386, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 39456, "s": 39424, "text": "Printing Output of an R Program" }, { "code": null, "e": 39514, "s": 39456, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
What is an Intent in Android?
An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity. Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. (First Activity layout) <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout 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"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:gravity = "center" android:orientation = "vertical"> <Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Send to another activitys" android:id = "@+id/send"/> </LinearLayout> </android.support.constraint.ConstraintLayout> Step 3 − Create a new layout in res/layout/ folder and add the following code to res/layout/activity_main.xml. (Second Activity layout ) <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_centerInParent = "true" android:layout_centerHorizontal = "true" tools:context = ".SecondActivity"> <TextView android:id = "@+id/data" android:textSize = "20sp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </android.support.constraint.ConstraintLayout> Step 4 − Add the following code to src/MainActivity.java (First activity) import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button send = findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent send = new Intent(MainActivity.this, SecondActivity.class); startActivity(send); } }); } } In the above activity we are starting new activity using startActivity(). To start activity, we need to create new intent and we have to pass current activity and new activity as shown below. Intent send = new Intent(MainActivity.this, SecondActivity.class); startActivity(send); Step 4 − Create a new activity and add the following code to src/SecondActivity.java (Second Activity) package com.example.andy.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView data=findViewById(R.id.data); data.setText("This is second activity"); } } Step5 − Add the following code to AndroidManifest.xml. <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <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> <activity android:name = ".SecondActivity"></activity> </application> </manifest> In the above code, we have declare MainActivity and SecondActivity as shown below. <activity android:name = ".SecondActivity"></activity> <activity android:name = ".MainActivity""></activity> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. Now click on Button to start new activity as shown below. Click here to download the project code
[ { "code": null, "e": 1379, "s": 1062, "text": "An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity." }, { "code": null, "e": 1507, "s": 1379, "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": 1596, "s": 1507, "text": "Step 2 − Add the following code to res/layout/activity_main.xml. (First Activity layout)" }, { "code": null, "e": 2284, "s": 1596, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\nxmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n<LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <Button\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Send to another activitys\"\n android:id = \"@+id/send\"/>\n</LinearLayout>\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2421, "s": 2284, "text": "Step 3 − Create a new layout in res/layout/ folder and add the following code to res/layout/activity_main.xml. (Second Activity layout )" }, { "code": null, "e": 3101, "s": 2421, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_centerInParent = \"true\"\n android:layout_centerHorizontal = \"true\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/data\"\n android:textSize = \"20sp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 3175, "s": 3101, "text": "Step 4 − Add the following code to src/MainActivity.java (First activity)" }, { "code": null, "e": 3850, "s": 3175, "text": "import android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button send = findViewById(R.id.send);\n send.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent send = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(send);\n }\n });\n }\n}" }, { "code": null, "e": 4042, "s": 3850, "text": "In the above activity we are starting new activity using startActivity(). To start activity, we need to create new intent and we have to pass current activity and new activity as shown below." }, { "code": null, "e": 4130, "s": 4042, "text": "Intent send = new Intent(MainActivity.this, SecondActivity.class);\nstartActivity(send);" }, { "code": null, "e": 4233, "s": 4130, "text": "Step 4 − Create a new activity and add the following code to src/SecondActivity.java (Second Activity)" }, { "code": null, "e": 4694, "s": 4233, "text": "package com.example.andy.myapplication;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView data=findViewById(R.id.data);\n data.setText(\"This is second activity\");\n }\n}" }, { "code": null, "e": 4749, "s": 4694, "text": "Step5 − Add the following code to AndroidManifest.xml." }, { "code": null, "e": 5525, "s": 4749, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\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 <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 5608, "s": 5525, "text": "In the above code, we have declare MainActivity and SecondActivity as shown below." }, { "code": null, "e": 5717, "s": 5608, "text": "<activity android:name = \".SecondActivity\"></activity>\n<activity android:name = \".MainActivity\"\"></activity>" }, { "code": null, "e": 6063, "s": 5717, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." }, { "code": null, "e": 6121, "s": 6063, "text": "Now click on Button to start new activity as shown below." }, { "code": null, "e": 6161, "s": 6121, "text": "Click here to download the project code" } ]
Python - Get list of files in directory sorted by size - GeeksforGeeks
28 Jul, 2021 In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir() function Using glob() functions os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then a list of files and directories in the current working directory will be returned. Syntax: os.listdir(path) Parameters: path (optional) : path of the directory Return: This method returns the list of all files and directories in the specified path. The return type of this method is list. In this method, we will create a list of filenames in a folder sorted by file size. We will pass lambda x: os.stat(os.path.join(dir_name, x)).st_size as the key argument to the sorted() function which will sort the files in directory by size. Python3 import os name_of_dir = 'dir_path' # Storing list of all files# in the given directory in list_of_fileslist_of_files = filter( lambda x: os.path.isfile (os.path.join(name_of_dir, x)), os.listdir(dir_name) ) # Sort list of file names by size list_of_files = sorted( list_of_files, key = lambda x: os.stat (os.path.join(name_of_dir, x)).st_size) # Iterate over sorted list of file # names and print them along with size one by one for name_of_file in list_of_files: path_of_file = os.path.join(name_of_dir, name_of_file) size_of_file = os.stat(path_of_file).st_size print(size_of_file, ' -->', name_of_file) Output: 366 --> descript.ion 1688 --> readme.txt 3990 --> License.txt 15360 --> Uninstall.exe 48844 --> History.txt 50688 --> 7-zip32.dll 78336 --> 7-zip.dll 108074 --> 7-zip.chm 186880 --> 7zCon.sfx 205824 --> 7z.sfx 468992 --> 7z.exe 581632 --> 7zG.exe 867840 --> 7zFM.exe 1679360 --> 7z.dll In python programming language we have the glob module which provides a function called glob() which is used to find files or directories in a given directory based on the matching pattern. Using the glob() function we can use wildcards and regular expression to match and find few files in a directory or all files in a directory. In this method, we will use glob() function to get a list of all files in a directory along with the size. The steps are as follows, First, we will get list of all files in a directory using glob(), then we will sort the list of files based on the size of files using sorted() function. We will use os.stat(file_path).st_size to fetch the file size from stat object of file. Then we will pass the encapsulated size in a lambda function as the key argument in the sorted() function. Python3 import globimport os name_of_dir = 'dir_path/' # Storing list of all files (file paths)# in the given directory in list_of_fileslist_of_files = filter( os.path.isfile, glob.glob(name_of_dir + '*') ) # Sort list of files in directory by size list_of_files = sorted( list_of_files, key = lambda x: os.stat(x).st_size) # Iterate over sorted list of file names# and print them along with size one by one for path_of_file in list_of_files: size_of_file = os.stat(path_of_file).st_size print(size_of_file, ' -->', path_of_file) Output: 366 --> C:/Program Files/7-Zip\descript.ion 1688 --> C:/Program Files/7-Zip\readme.txt 3990 --> C:/Program Files/7-Zip\License.txt 15360 --> C:/Program Files/7-Zip\Uninstall.exe 48844 --> C:/Program Files/7-Zip\History.txt 50688 --> C:/Program Files/7-Zip\7-zip32.dll 78336 --> C:/Program Files/7-Zip\7-zip.dll 108074 --> C:/Program Files/7-Zip\7-zip.chm 186880 --> C:/Program Files/7-Zip\7zCon.sfx 205824 --> C:/Program Files/7-Zip\7z.sfx 468992 --> C:/Program Files/7-Zip\7z.exe 581632 --> C:/Program Files/7-Zip\7zG.exe 867840 --> C:/Program Files/7-Zip\7zFM.exe 1679360 --> C:/Program Files/7-Zip\7z.dll Picked Python directory-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25691, "s": 25663, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25871, "s": 25691, "text": "In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language." }, { "code": null, "e": 25974, "s": 25871, "text": "The two different approaches to get the list of files in a directory are sorted by size is as follows:" }, { "code": null, "e": 26002, "s": 25974, "text": "Using os.listdir() function" }, { "code": null, "e": 26026, "s": 26002, "text": "Using glob() functions " }, { "code": null, "e": 26260, "s": 26026, "text": "os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then a list of files and directories in the current working directory will be returned." }, { "code": null, "e": 26285, "s": 26260, "text": "Syntax: os.listdir(path)" }, { "code": null, "e": 26337, "s": 26285, "text": "Parameters: path (optional) : path of the directory" }, { "code": null, "e": 26466, "s": 26337, "text": "Return: This method returns the list of all files and directories in the specified path. The return type of this method is list." }, { "code": null, "e": 26709, "s": 26466, "text": "In this method, we will create a list of filenames in a folder sorted by file size. We will pass lambda x: os.stat(os.path.join(dir_name, x)).st_size as the key argument to the sorted() function which will sort the files in directory by size." }, { "code": null, "e": 26717, "s": 26709, "text": "Python3" }, { "code": "import os name_of_dir = 'dir_path' # Storing list of all files# in the given directory in list_of_fileslist_of_files = filter( lambda x: os.path.isfile (os.path.join(name_of_dir, x)), os.listdir(dir_name) ) # Sort list of file names by size list_of_files = sorted( list_of_files, key = lambda x: os.stat (os.path.join(name_of_dir, x)).st_size) # Iterate over sorted list of file # names and print them along with size one by one for name_of_file in list_of_files: path_of_file = os.path.join(name_of_dir, name_of_file) size_of_file = os.stat(path_of_file).st_size print(size_of_file, ' -->', name_of_file)", "e": 27429, "s": 26717, "text": null }, { "code": null, "e": 27437, "s": 27429, "text": "Output:" }, { "code": null, "e": 27737, "s": 27437, "text": "366 --> descript.ion\n1688 --> readme.txt\n3990 --> License.txt\n15360 --> Uninstall.exe\n48844 --> History.txt\n50688 --> 7-zip32.dll\n78336 --> 7-zip.dll\n108074 --> 7-zip.chm\n186880 --> 7zCon.sfx\n205824 --> 7z.sfx\n468992 --> 7z.exe\n581632 --> 7zG.exe\n867840 --> 7zFM.exe\n1679360 --> 7z.dll" }, { "code": null, "e": 28202, "s": 27737, "text": "In python programming language we have the glob module which provides a function called glob() which is used to find files or directories in a given directory based on the matching pattern. Using the glob() function we can use wildcards and regular expression to match and find few files in a directory or all files in a directory. In this method, we will use glob() function to get a list of all files in a directory along with the size. The steps are as follows," }, { "code": null, "e": 28357, "s": 28202, "text": "First, we will get list of all files in a directory using glob(), then we will sort the list of files based on the size of files using sorted() function. " }, { "code": null, "e": 28552, "s": 28357, "text": "We will use os.stat(file_path).st_size to fetch the file size from stat object of file. Then we will pass the encapsulated size in a lambda function as the key argument in the sorted() function." }, { "code": null, "e": 28560, "s": 28552, "text": "Python3" }, { "code": "import globimport os name_of_dir = 'dir_path/' # Storing list of all files (file paths)# in the given directory in list_of_fileslist_of_files = filter( os.path.isfile, glob.glob(name_of_dir + '*') ) # Sort list of files in directory by size list_of_files = sorted( list_of_files, key = lambda x: os.stat(x).st_size) # Iterate over sorted list of file names# and print them along with size one by one for path_of_file in list_of_files: size_of_file = os.stat(path_of_file).st_size print(size_of_file, ' -->', path_of_file) ", "e": 29144, "s": 28560, "text": null }, { "code": null, "e": 29152, "s": 29144, "text": "Output:" }, { "code": null, "e": 29774, "s": 29152, "text": "366 --> C:/Program Files/7-Zip\\descript.ion\n1688 --> C:/Program Files/7-Zip\\readme.txt\n3990 --> C:/Program Files/7-Zip\\License.txt\n15360 --> C:/Program Files/7-Zip\\Uninstall.exe\n48844 --> C:/Program Files/7-Zip\\History.txt\n50688 --> C:/Program Files/7-Zip\\7-zip32.dll\n78336 --> C:/Program Files/7-Zip\\7-zip.dll\n108074 --> C:/Program Files/7-Zip\\7-zip.chm\n186880 --> C:/Program Files/7-Zip\\7zCon.sfx\n205824 --> C:/Program Files/7-Zip\\7z.sfx\n468992 --> C:/Program Files/7-Zip\\7z.exe\n581632 --> C:/Program Files/7-Zip\\7zG.exe\n867840 --> C:/Program Files/7-Zip\\7zFM.exe\n1679360 --> C:/Program Files/7-Zip\\7z.dll" }, { "code": null, "e": 29781, "s": 29774, "text": "Picked" }, { "code": null, "e": 29806, "s": 29781, "text": "Python directory-program" }, { "code": null, "e": 29813, "s": 29806, "text": "Python" }, { "code": null, "e": 29911, "s": 29813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29943, "s": 29911, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29985, "s": 29943, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30027, "s": 29985, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30083, "s": 30027, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30110, "s": 30083, "text": "Python Classes and Objects" }, { "code": null, "e": 30141, "s": 30110, "text": "Python | os.path.join() method" }, { "code": null, "e": 30170, "s": 30141, "text": "Create a directory in Python" }, { "code": null, "e": 30192, "s": 30170, "text": "Defaultdict in Python" }, { "code": null, "e": 30231, "s": 30192, "text": "Python | Get unique values from a list" } ]
Enhance your Power BI report with images on axis | by Nikola Ilic | Towards Data Science
If you follow my stories on a regular basis, you should have noticed that I’m often trying to enhance built-in visualizations provided by Power BI. In my opinion, there are certain scenarios when you, as a Power BI developer, can go above and beyond, and push your users’ experience to a new level, using simple tricks. Not so long ago, I was working on creating a report solution for our customer support department. Basically, support agents perform four different types of interactions with the customers — chats, emails, phone calls, and surveys. And, managers need to have a report to measure the number of interactions per specific type, so they can identify peak times and assign agents to specific tasks. For this example, I’ll keep things simple. There is a single table containing interaction unique id, date of interaction, and type of interaction. The first step is to create an explicit measure that will count the number of interactions. Total Interactions = COUNT(Sheet1[Interaction ID]) And, here is how my visual looks at the moment: As you see, nothing special here, “classic” column bar chart. So, let’s try to bring some life into it. I’ve already written about UNICHAR() function in DAX, and how you can take advantage of this function in some scenarios. This function returns the Unicode character, as a representation of the numeric value you provided. Now, the idea is to substitute text values: chats, emails, surveys, and phone calls, with visual representations of these words. There is a whole range of different symbols that can be expressed as Unicode. Here is the very comprehensive list of the symbols, together with their Unicode values. The first step is to create a new table in the Power BI data model, that will hold data about Unicode values. After I’ve loaded the table into the data model, I’ll switch to Model view and establish a “one-to-many” relationship between this table and my original table: After that, I’ll go and create a new DAX column within my Interaction Unicodes table. And, here is where the magic happens — we will use UNICHAR() function, and as an argument, we will provide the value from the Unicode column: Interaction Type Icon = UNICHAR('Interactions Unicodes'[Unicode]) And, voila, look at the values in this column now! As we established a relationship between the tables, let’s grab this column and put it on the x-axis of our column bar chart: That looks cool, right? You can increase/decrease the font size of the x-axis, same as you would do with the “normal” text — and your icons will be resized! Moreover, we can use these icons as slicers too! Let me show you how this can be used to enhance your users’ experience. As you see in the illustration above, I’ve nicely formatted the slicer to look like a group of buttons (by using Horizontal orientation), so I can now slice my data by clicking on it! I’ve also created a Matrix visual and you see that our icons are there, behaving like regular text columns. In the end, UNICHAR() function will return text value, and you can handle it like you would handle normal text. The key thing to keep in mind: don’t let this trick become the main “modus operandi” when you’re creating Power BI reports! Of course, in most cases, you should stick with the traditional way of displaying values in your visuals. However, there are certain situations when applying this technique can enhance the user experience. In my opinion, two things are of key importance if you decide to use this trick: A limited number of categories to deal with — as you saw in my example, there is a fixed number of possible categories (chats, phone calls, emails, and surveys), so there is no danger of the axis/slicer becoming cluttered with too many icons Icons MUST provide the context of the “regular” text value — the user has to unambiguously understand what each icon represents. If that’s not the case, your report will cause confusion instead of clarity, and that is another valid reason to think twice before using this technique As usual, try to find the right balance between enhancing your user’s experience and additional overhead that can be caused by using these non-standard techniques. Thanks for reading! Become a member and read every story on Medium!
[ { "code": null, "e": 491, "s": 171, "text": "If you follow my stories on a regular basis, you should have noticed that I’m often trying to enhance built-in visualizations provided by Power BI. In my opinion, there are certain scenarios when you, as a Power BI developer, can go above and beyond, and push your users’ experience to a new level, using simple tricks." }, { "code": null, "e": 884, "s": 491, "text": "Not so long ago, I was working on creating a report solution for our customer support department. Basically, support agents perform four different types of interactions with the customers — chats, emails, phone calls, and surveys. And, managers need to have a report to measure the number of interactions per specific type, so they can identify peak times and assign agents to specific tasks." }, { "code": null, "e": 1123, "s": 884, "text": "For this example, I’ll keep things simple. There is a single table containing interaction unique id, date of interaction, and type of interaction. The first step is to create an explicit measure that will count the number of interactions." }, { "code": null, "e": 1174, "s": 1123, "text": "Total Interactions = COUNT(Sheet1[Interaction ID])" }, { "code": null, "e": 1222, "s": 1174, "text": "And, here is how my visual looks at the moment:" }, { "code": null, "e": 1547, "s": 1222, "text": "As you see, nothing special here, “classic” column bar chart. So, let’s try to bring some life into it. I’ve already written about UNICHAR() function in DAX, and how you can take advantage of this function in some scenarios. This function returns the Unicode character, as a representation of the numeric value you provided." }, { "code": null, "e": 1842, "s": 1547, "text": "Now, the idea is to substitute text values: chats, emails, surveys, and phone calls, with visual representations of these words. There is a whole range of different symbols that can be expressed as Unicode. Here is the very comprehensive list of the symbols, together with their Unicode values." }, { "code": null, "e": 1952, "s": 1842, "text": "The first step is to create a new table in the Power BI data model, that will hold data about Unicode values." }, { "code": null, "e": 2112, "s": 1952, "text": "After I’ve loaded the table into the data model, I’ll switch to Model view and establish a “one-to-many” relationship between this table and my original table:" }, { "code": null, "e": 2340, "s": 2112, "text": "After that, I’ll go and create a new DAX column within my Interaction Unicodes table. And, here is where the magic happens — we will use UNICHAR() function, and as an argument, we will provide the value from the Unicode column:" }, { "code": null, "e": 2406, "s": 2340, "text": "Interaction Type Icon = UNICHAR('Interactions Unicodes'[Unicode])" }, { "code": null, "e": 2457, "s": 2406, "text": "And, voila, look at the values in this column now!" }, { "code": null, "e": 2583, "s": 2457, "text": "As we established a relationship between the tables, let’s grab this column and put it on the x-axis of our column bar chart:" }, { "code": null, "e": 2740, "s": 2583, "text": "That looks cool, right? You can increase/decrease the font size of the x-axis, same as you would do with the “normal” text — and your icons will be resized!" }, { "code": null, "e": 2861, "s": 2740, "text": "Moreover, we can use these icons as slicers too! Let me show you how this can be used to enhance your users’ experience." }, { "code": null, "e": 3265, "s": 2861, "text": "As you see in the illustration above, I’ve nicely formatted the slicer to look like a group of buttons (by using Horizontal orientation), so I can now slice my data by clicking on it! I’ve also created a Matrix visual and you see that our icons are there, behaving like regular text columns. In the end, UNICHAR() function will return text value, and you can handle it like you would handle normal text." }, { "code": null, "e": 3595, "s": 3265, "text": "The key thing to keep in mind: don’t let this trick become the main “modus operandi” when you’re creating Power BI reports! Of course, in most cases, you should stick with the traditional way of displaying values in your visuals. However, there are certain situations when applying this technique can enhance the user experience." }, { "code": null, "e": 3676, "s": 3595, "text": "In my opinion, two things are of key importance if you decide to use this trick:" }, { "code": null, "e": 3918, "s": 3676, "text": "A limited number of categories to deal with — as you saw in my example, there is a fixed number of possible categories (chats, phone calls, emails, and surveys), so there is no danger of the axis/slicer becoming cluttered with too many icons" }, { "code": null, "e": 4200, "s": 3918, "text": "Icons MUST provide the context of the “regular” text value — the user has to unambiguously understand what each icon represents. If that’s not the case, your report will cause confusion instead of clarity, and that is another valid reason to think twice before using this technique" }, { "code": null, "e": 4364, "s": 4200, "text": "As usual, try to find the right balance between enhancing your user’s experience and additional overhead that can be caused by using these non-standard techniques." }, { "code": null, "e": 4384, "s": 4364, "text": "Thanks for reading!" } ]
ReactJS - State Management API
As we learned earlier, React component maintains and expose it’s state through this.state of the component. React provides a single API to maintain state in the component. The API is this.setState(). It accepts either a JavaScript object or a function that returns a JavaScript object. The signature of the setState API is as follows − this.setState( { ... object ...} ); A simple example to set / update name is as follows − this.setState( { name: 'John' } ) The signature of the setState with function is as follows − this.setState( (state, props) => ... function returning JavaScript object ... ); Here, state refers the current state of the React component state refers the current state of the React component props refers the current properties of the React component. props refers the current properties of the React component. React recommends to use setState API with function as it works correctly in async environment. Instead of lambda function, normal JavaScript function can be used as well. this.setState( function(state, props) { return ... JavaScript object ... } A simple example to update the amount using function is as follows − this.setState( (state, props) => ({ amount: this.state.amount + this.props.additionaAmount }) React state should not be modified directly through this.state member variable and updating the state through member variable does not re-render the component. A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data. A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data. For example, let us consider that the internal state contains a student record. { name: 'John', age: 16 } We can update only the age using setState API, which will automatically merge the new object with the existing student record object. this.setState( (state, props) => ({ age: 18 }); 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2319, "s": 2033, "text": "As we learned earlier, React component maintains and expose it’s state through this.state of the component. React provides a single API to maintain state in the component. The API is this.setState(). It accepts either a JavaScript object or a function that returns a JavaScript object." }, { "code": null, "e": 2369, "s": 2319, "text": "The signature of the setState API is as follows −" }, { "code": null, "e": 2406, "s": 2369, "text": "this.setState( { ... object ...} );\n" }, { "code": null, "e": 2460, "s": 2406, "text": "A simple example to set / update name is as follows −" }, { "code": null, "e": 2495, "s": 2460, "text": "this.setState( { name: 'John' } )\n" }, { "code": null, "e": 2555, "s": 2495, "text": "The signature of the setState with function is as follows −" }, { "code": null, "e": 2641, "s": 2555, "text": "this.setState( (state, props) => \n ... function returning JavaScript object ... );\n" }, { "code": null, "e": 2647, "s": 2641, "text": "Here," }, { "code": null, "e": 2701, "s": 2647, "text": "state refers the current state of the React component" }, { "code": null, "e": 2755, "s": 2701, "text": "state refers the current state of the React component" }, { "code": null, "e": 2815, "s": 2755, "text": "props refers the current properties of the React component." }, { "code": null, "e": 2875, "s": 2815, "text": "props refers the current properties of the React component." }, { "code": null, "e": 3046, "s": 2875, "text": "React recommends to use setState API with function as it works correctly in async environment. Instead of lambda function, normal JavaScript function can be used as well." }, { "code": null, "e": 3127, "s": 3046, "text": "this.setState( function(state, props) { \n return ... JavaScript object ... \n}\n" }, { "code": null, "e": 3196, "s": 3127, "text": "A simple example to update the amount using function is as follows −" }, { "code": null, "e": 3296, "s": 3196, "text": "this.setState( (state, props) => ({ \n amount: this.state.amount + this.props.additionaAmount \n})\n" }, { "code": null, "e": 3456, "s": 3296, "text": "React state should not be modified directly through this.state member variable and updating the state through member variable does not re-render the component." }, { "code": null, "e": 3760, "s": 3456, "text": "A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data." }, { "code": null, "e": 4064, "s": 3760, "text": "A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data." }, { "code": null, "e": 4144, "s": 4064, "text": "For example, let us consider that the internal state contains a student record." }, { "code": null, "e": 4176, "s": 4144, "text": "{ \n name: 'John', age: 16 \n}\n" }, { "code": null, "e": 4310, "s": 4176, "text": "We can update only the age using setState API, which will automatically merge the new object with the existing student record object." }, { "code": null, "e": 4364, "s": 4310, "text": "this.setState( (state, props) => ({ \n age: 18 \n});\n" }, { "code": null, "e": 4399, "s": 4364, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4413, "s": 4399, "text": " Anadi Sharma" }, { "code": null, "e": 4448, "s": 4413, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4468, "s": 4448, "text": " Skillbakerystudios" }, { "code": null, "e": 4503, "s": 4468, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 4526, "s": 4503, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 4561, "s": 4526, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4577, "s": 4561, "text": " TELCOMA Global" }, { "code": null, "e": 4610, "s": 4577, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4628, "s": 4610, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 4635, "s": 4628, "text": " Print" }, { "code": null, "e": 4646, "s": 4635, "text": " Add Notes" } ]
Building a row from a dictionary in PySpark - GeeksforGeeks
18 Jul, 2021 In this article, we will discuss how to build a row from the dictionary in PySpark For doing this, we will pass the dictionary to the Row() method. Syntax: Syntax: Row(dict) Example 1: Build a row with key-value pair (Dictionary) as arguments. Here, we are going to pass the Row with Dictionary Syntax: Row({‘Key’:”value”, ‘Key’:”value”,’Key’:”value”}) Python3 # import Rowfrom pyspark.sql import Row # dictdic = {'First_name':"Sravan", 'Last_name':"Kumar", 'address':"hyderabad"} # create a row with three values# as dictionary.row = Row(dic) # display rowprint(row) Output: <Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})> Example 2: Python program to build two Rows with dictionary. Syntax: Row(dict, dict) Code: Python3 # import Rowfrom pyspark.sql import Row dic_1 = {'First_name':"Sravan", 'Last_name':"Kumar", 'address':"hyderabad"} dic_2 = {'First_name':"Bobby", 'Last_name':"Gottumukkala", 'address':"Ponnur"} # create two rows with# three values as dictionary.row = [Row(dic_1), Row(dic_2)]# display rowprint(row) Output: [<Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})>, <Row({‘First_name’: ‘Bobby’, ‘Last_name’: ‘Gottumukkala’, ‘address’: ‘Ponnur’})>] Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python Classes and Objects Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24390, "s": 24362, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24473, "s": 24390, "text": "In this article, we will discuss how to build a row from the dictionary in PySpark" }, { "code": null, "e": 24538, "s": 24473, "text": "For doing this, we will pass the dictionary to the Row() method." }, { "code": null, "e": 24546, "s": 24538, "text": "Syntax:" }, { "code": null, "e": 24564, "s": 24546, "text": "Syntax: Row(dict)" }, { "code": null, "e": 24634, "s": 24564, "text": "Example 1: Build a row with key-value pair (Dictionary) as arguments." }, { "code": null, "e": 24686, "s": 24634, "text": "Here, we are going to pass the Row with Dictionary " }, { "code": null, "e": 24744, "s": 24686, "text": "Syntax: Row({‘Key’:”value”, ‘Key’:”value”,’Key’:”value”})" }, { "code": null, "e": 24752, "s": 24744, "text": "Python3" }, { "code": "# import Rowfrom pyspark.sql import Row # dictdic = {'First_name':\"Sravan\", 'Last_name':\"Kumar\", 'address':\"hyderabad\"} # create a row with three values# as dictionary.row = Row(dic) # display rowprint(row)", "e": 24975, "s": 24752, "text": null }, { "code": null, "e": 24983, "s": 24975, "text": "Output:" }, { "code": null, "e": 25061, "s": 24983, "text": "<Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})>" }, { "code": null, "e": 25122, "s": 25061, "text": "Example 2: Python program to build two Rows with dictionary." }, { "code": null, "e": 25146, "s": 25122, "text": "Syntax: Row(dict, dict)" }, { "code": null, "e": 25152, "s": 25146, "text": "Code:" }, { "code": null, "e": 25160, "s": 25152, "text": "Python3" }, { "code": "# import Rowfrom pyspark.sql import Row dic_1 = {'First_name':\"Sravan\", 'Last_name':\"Kumar\", 'address':\"hyderabad\"} dic_2 = {'First_name':\"Bobby\", 'Last_name':\"Gottumukkala\", 'address':\"Ponnur\"} # create two rows with# three values as dictionary.row = [Row(dic_1), Row(dic_2)]# display rowprint(row)", "e": 25502, "s": 25160, "text": null }, { "code": null, "e": 25510, "s": 25502, "text": "Output:" }, { "code": null, "e": 25590, "s": 25510, "text": "[<Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})>," }, { "code": null, "e": 25673, "s": 25590, "text": " <Row({‘First_name’: ‘Bobby’, ‘Last_name’: ‘Gottumukkala’, ‘address’: ‘Ponnur’})>]" }, { "code": null, "e": 25680, "s": 25673, "text": "Picked" }, { "code": null, "e": 25695, "s": 25680, "text": "Python-Pyspark" }, { "code": null, "e": 25702, "s": 25695, "text": "Python" }, { "code": null, "e": 25800, "s": 25702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25832, "s": 25800, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25874, "s": 25832, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25916, "s": 25874, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25972, "s": 25916, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25994, "s": 25972, "text": "Defaultdict in Python" }, { "code": null, "e": 26021, "s": 25994, "text": "Python Classes and Objects" }, { "code": null, "e": 26050, "s": 26021, "text": "Create a directory in Python" }, { "code": null, "e": 26081, "s": 26050, "text": "Python | os.path.join() method" }, { "code": null, "e": 26117, "s": 26081, "text": "Python | Pandas dataframe.groupby()" } ]
Predefined Identifier __func__ in C - GeeksforGeeks
24 Sep, 2021 Before we start discussing about __func__, let us write some code snippet and anticipate the output: C #include <stdio.h> int main(){ printf("%s",__func__); return 0;} Will it compile error due to not defining variable __func__ ? Well, as you would have guessed so far, it won’t give any compile error and it’d print main! C language standard (i.e. C99 and C11) defines a predefined identifier as follows in clause 6.4.2.2: “The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = “function-name”;appeared, where function-name is the name of the lexically-enclosing function.“ It means that C compiler implicitly adds __func__ in every function so that it can be used in that function to get the function name. To understand it better, let us write this code: C #include <stdio.h>void foo(void){ printf("%s",__func__);}void bar(void){ printf("%s",__func__);} int main(){ foo(); bar(); return 0;} And it’ll give output as foobar. A use case of this predefined identifier could be logging the output of a big program where a programmer can use __func__ to get the current function instead of mentioning the complete function name explicitly. Now what happens if we define one more variable of name __func__ C #include <stdio.h> int __func__ = 10;int main(){ printf("%d",__func__); return 0;} Since C standard says compiler implicitly defines __func__ for each function as the function-name, we should not defined __func__ at the first place. You might get error but C standard says “undefined behavior” if someone explicitly defines __func__ . Just to finish the discussion on Predefined Identifier __func__, let us mention Predefined Macros as well (such as __FILE__ and __LINE__ etc.) Basically, C standard clause 6.10.8 mentions several predefined macros out of which __FILE__ and __LINE__ are of relevance here. It’s worthwhile to see the output of the following code snippet: C #include <stdio.h> int main(){ printf("In file:%s, function:%s() and line:%d",__FILE__,__func__,__LINE__); return 0;} Instead of explaining the output, we will leave this to you to guess and understand the role of __FILE__ and __LINE__!Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn avsadityavardhan chhabradhanvi C-Library Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Service-Oriented Architecture Const keyword in C++ Amazon’s most frequently asked interview questions | Set 2 What's the difference between Scripting and Programming Languages? Advantages and Disadvantages of Linked List Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 26049, "s": 26021, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26151, "s": 26049, "text": "Before we start discussing about __func__, let us write some code snippet and anticipate the output: " }, { "code": null, "e": 26153, "s": 26151, "text": "C" }, { "code": "#include <stdio.h> int main(){ printf(\"%s\",__func__); return 0;}", "e": 26222, "s": 26153, "text": null }, { "code": null, "e": 26378, "s": 26222, "text": "Will it compile error due to not defining variable __func__ ? Well, as you would have guessed so far, it won’t give any compile error and it’d print main! " }, { "code": null, "e": 26479, "s": 26378, "text": "C language standard (i.e. C99 and C11) defines a predefined identifier as follows in clause 6.4.2.2:" }, { "code": null, "e": 26769, "s": 26479, "text": "“The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = “function-name”;appeared, where function-name is the name of the lexically-enclosing function.“" }, { "code": null, "e": 26953, "s": 26769, "text": "It means that C compiler implicitly adds __func__ in every function so that it can be used in that function to get the function name. To understand it better, let us write this code: " }, { "code": null, "e": 26955, "s": 26953, "text": "C" }, { "code": "#include <stdio.h>void foo(void){ printf(\"%s\",__func__);}void bar(void){ printf(\"%s\",__func__);} int main(){ foo(); bar(); return 0;}", "e": 27099, "s": 26955, "text": null }, { "code": null, "e": 27409, "s": 27099, "text": "And it’ll give output as foobar. A use case of this predefined identifier could be logging the output of a big program where a programmer can use __func__ to get the current function instead of mentioning the complete function name explicitly. Now what happens if we define one more variable of name __func__ " }, { "code": null, "e": 27411, "s": 27409, "text": "C" }, { "code": "#include <stdio.h> int __func__ = 10;int main(){ printf(\"%d\",__func__); return 0;}", "e": 27499, "s": 27411, "text": null }, { "code": null, "e": 27751, "s": 27499, "text": "Since C standard says compiler implicitly defines __func__ for each function as the function-name, we should not defined __func__ at the first place. You might get error but C standard says “undefined behavior” if someone explicitly defines __func__ ." }, { "code": null, "e": 28024, "s": 27751, "text": "Just to finish the discussion on Predefined Identifier __func__, let us mention Predefined Macros as well (such as __FILE__ and __LINE__ etc.) Basically, C standard clause 6.10.8 mentions several predefined macros out of which __FILE__ and __LINE__ are of relevance here. " }, { "code": null, "e": 28090, "s": 28024, "text": "It’s worthwhile to see the output of the following code snippet: " }, { "code": null, "e": 28092, "s": 28090, "text": "C" }, { "code": "#include <stdio.h> int main(){ printf(\"In file:%s, function:%s() and line:%d\",__FILE__,__func__,__LINE__); return 0;}", "e": 28215, "s": 28092, "text": null }, { "code": null, "e": 28490, "s": 28215, "text": "Instead of explaining the output, we will leave this to you to guess and understand the role of __FILE__ and __LINE__!Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn " }, { "code": null, "e": 28507, "s": 28490, "text": "avsadityavardhan" }, { "code": null, "e": 28521, "s": 28507, "text": "chhabradhanvi" }, { "code": null, "e": 28531, "s": 28521, "text": "C-Library" }, { "code": null, "e": 28540, "s": 28531, "text": "Articles" }, { "code": null, "e": 28551, "s": 28540, "text": "C Language" }, { "code": null, "e": 28649, "s": 28551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28679, "s": 28649, "text": "Service-Oriented Architecture" }, { "code": null, "e": 28700, "s": 28679, "text": "Const keyword in C++" }, { "code": null, "e": 28759, "s": 28700, "text": "Amazon’s most frequently asked interview questions | Set 2" }, { "code": null, "e": 28826, "s": 28759, "text": "What's the difference between Scripting and Programming Languages?" }, { "code": null, "e": 28870, "s": 28826, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 28886, "s": 28870, "text": "Arrays in C/C++" }, { "code": null, "e": 28964, "s": 28886, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 28987, "s": 28964, "text": "std::sort() in C++ STL" }, { "code": null, "e": 29014, "s": 28987, "text": "Bitwise Operators in C/C++" } ]
Program for longest common directory path in Python
In this tutorial, we are going to write a program that finds the longest common path from the given list of paths. Let's see an example to understand the problem statement more clearly. paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django'] /home/tutorialspoint/ We can solve the problem using os module very easily. Let's see the steps to solve the Import the os module. Initialize the list of paths to find the longest common path. Find the common prefix of all paths using os.path.commonprefix(paths) and store it in variable. And extract the directory from the common prefix using os.path.dirname(common_prefix). Live Demo # importing the os module import os # initializing the paths paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials point/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django'] # finding the common prefix common_prefix = os.path.commonprefix(paths) # extracting the directory from the common prefix longest_common_directory = os.path.dirname(common_prefix) # printing the long common path print(longest_common_directory) If you run the above code, then you will get the following result. home/tutorialspoint If you have any queries regarding the tutorial, mention them in the comment section.
[ { "code": null, "e": 1248, "s": 1062, "text": "In this tutorial, we are going to write a program that finds the longest common path from the given list of paths. Let's see an example to understand the problem statement more clearly." }, { "code": null, "e": 1405, "s": 1248, "text": "paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript',\n'home/tutorialspoint/react', 'home/tutorialspoint/django']" }, { "code": null, "e": 1427, "s": 1405, "text": "/home/tutorialspoint/" }, { "code": null, "e": 1514, "s": 1427, "text": "We can solve the problem using os module very easily. Let's see the steps to solve the" }, { "code": null, "e": 1536, "s": 1514, "text": "Import the os module." }, { "code": null, "e": 1598, "s": 1536, "text": "Initialize the list of paths to find the longest common path." }, { "code": null, "e": 1694, "s": 1598, "text": "Find the common prefix of all paths using os.path.commonprefix(paths) and store it in variable." }, { "code": null, "e": 1781, "s": 1694, "text": "And extract the directory from the common prefix using os.path.dirname(common_prefix)." }, { "code": null, "e": 1792, "s": 1781, "text": " Live Demo" }, { "code": null, "e": 2255, "s": 1792, "text": "# importing the os module\nimport os\n# initializing the paths\npaths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials\npoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']\n# finding the common prefix\ncommon_prefix = os.path.commonprefix(paths)\n# extracting the directory from the common prefix\nlongest_common_directory = os.path.dirname(common_prefix)\n# printing the long common path\nprint(longest_common_directory)" }, { "code": null, "e": 2322, "s": 2255, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2342, "s": 2322, "text": "home/tutorialspoint" }, { "code": null, "e": 2427, "s": 2342, "text": "If you have any queries regarding the tutorial, mention them in the comment section." } ]
Double-Tap on a View in Android - GeeksforGeeks
18 Feb, 2021 Detecting a double tap i.e. whenever the user double taps on any view how it is detected and according to the view a response can be added corresponding to it. Here an example is shown in which the double tap on the view is detected and corresponding to it a response is added in the form of toast. Step 1: Create an Empty activity in Android Studio. To create one, follow this article- https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Check if the primary language selected is Kotlin. Step 2: No change is done in activity_main.xml. Since already a textview is present so the response for the double tap is added with it. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tvView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: In this step add the abstract class for the double tap and set the onClickListener which will use the abstract class. Below is the code for the MainActivity.kt class. Kotlin package org.geeksforgeeks.viewdoubletap import android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // In our case, we tap on Text View val view = findViewById<TextView>(R.id.tvView) // Double Click Listener implemented on the Text View view.setOnClickListener(object : DoubleClickListener() { override fun onDoubleClick(v: View?) { Toast.makeText(applicationContext,"Double Click",Toast.LENGTH_SHORT).show() } }) } // Abstract class defining methods to check Double Click where Time Delay // between the two clicks is set to 300 ms abstract class DoubleClickListener : View.OnClickListener { var lastClickTime: Long = 0 override fun onClick(v: View?) { val clickTime = System.currentTimeMillis() if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) { onDoubleClick(v) } lastClickTime = clickTime } abstract fun onDoubleClick(v: View?) companion object { private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds } }} android Android-View Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 25110, "s": 25082, "text": "\n18 Feb, 2021" }, { "code": null, "e": 25409, "s": 25110, "text": "Detecting a double tap i.e. whenever the user double taps on any view how it is detected and according to the view a response can be added corresponding to it. Here an example is shown in which the double tap on the view is detected and corresponding to it a response is added in the form of toast." }, { "code": null, "e": 25639, "s": 25409, "text": "Step 1: Create an Empty activity in Android Studio. To create one, follow this article- https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Check if the primary language selected is Kotlin." }, { "code": null, "e": 25776, "s": 25639, "text": "Step 2: No change is done in activity_main.xml. Since already a textview is present so the response for the double tap is added with it." }, { "code": null, "e": 25780, "s": 25776, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/tvView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World!\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 26580, "s": 25780, "text": null }, { "code": null, "e": 26755, "s": 26580, "text": "Step 3: In this step add the abstract class for the double tap and set the onClickListener which will use the abstract class. Below is the code for the MainActivity.kt class." }, { "code": null, "e": 26762, "s": 26755, "text": "Kotlin" }, { "code": "package org.geeksforgeeks.viewdoubletap import android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // In our case, we tap on Text View val view = findViewById<TextView>(R.id.tvView) // Double Click Listener implemented on the Text View view.setOnClickListener(object : DoubleClickListener() { override fun onDoubleClick(v: View?) { Toast.makeText(applicationContext,\"Double Click\",Toast.LENGTH_SHORT).show() } }) } // Abstract class defining methods to check Double Click where Time Delay // between the two clicks is set to 300 ms abstract class DoubleClickListener : View.OnClickListener { var lastClickTime: Long = 0 override fun onClick(v: View?) { val clickTime = System.currentTimeMillis() if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) { onDoubleClick(v) } lastClickTime = clickTime } abstract fun onDoubleClick(v: View?) companion object { private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds } }}", "e": 28197, "s": 26762, "text": null }, { "code": null, "e": 28205, "s": 28197, "text": "android" }, { "code": null, "e": 28218, "s": 28205, "text": "Android-View" }, { "code": null, "e": 28226, "s": 28218, "text": "Android" }, { "code": null, "e": 28233, "s": 28226, "text": "Kotlin" }, { "code": null, "e": 28241, "s": 28233, "text": "Android" }, { "code": null, "e": 28339, "s": 28241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28382, "s": 28339, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28440, "s": 28382, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 28473, "s": 28440, "text": "Services in Android with Example" }, { "code": null, "e": 28515, "s": 28473, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28546, "s": 28515, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 28589, "s": 28546, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28622, "s": 28589, "text": "Services in Android with Example" }, { "code": null, "e": 28664, "s": 28622, "text": "Content Providers in Android with Example" } ]
Add packages to Anaconda environment in Python
There are multiple ways by which we can add packages to our existing anaconda environment. Method 1 − One common approach is to use the “Anaconda Navigator” to add packages to our anaconda environment. Once “Ananconda Navigator” is opened, home page will look something like − Go to Environments tab just below the Home tab and from there we can check what all packages are installed and what is not. It is very easy to install any package through anaconda navigator, simply search the required package, select package and click on apply to install it. Let's suppose tensorflow packages are not installed in your computer, I can simply search the required package(like tensorflow), select it and click on apply to install it. Method 2 − Another way of installing packages is by the use of terminal or an Anaconda Prompt − conda install opencv Above command will install OpenCV package into your current environment. To install specific a specific version of a opencv package − conda install opencv-3.4.2 We can install multiple packages at once, such as OpenCV and tensorflow − conda install opencv tensorflow Note − It is recommended to install all required packages at once so that all of the dependencies are installed at once. To install a specific package such as opencv into your existing environment “myenv”(in case you have a virtual environment to install project specific packages). conda install –name myenv opencv Method 3 − If the package is not available in our conda environment or through anaconda navigator, we can find and install the package with another package manager like pip. We can install pip in our existing conda environment by simply giving the command − conda install pip And your screen will be shown an output something like − Now if you want to install any particular package, through pip in conda environment, we can do it like − Above we have installed opencv package through pip in conda environment. We can use the anaconda prompt, to list all of the packages in the active environment − conda list
[ { "code": null, "e": 1153, "s": 1062, "text": "There are multiple ways by which we can add packages to our existing anaconda environment." }, { "code": null, "e": 1339, "s": 1153, "text": "Method 1 − One common approach is to use the “Anaconda Navigator” to add packages to our anaconda environment. Once “Ananconda Navigator” is opened, home page will look something like −" }, { "code": null, "e": 1463, "s": 1339, "text": "Go to Environments tab just below the Home tab and from there we can check what all packages are installed and what is not." }, { "code": null, "e": 1788, "s": 1463, "text": "It is very easy to install any package through anaconda navigator, simply search the required package, select package and click on apply to install it. Let's suppose tensorflow packages are not installed in your computer, I can simply search the required package(like tensorflow), select it and click on apply to install it." }, { "code": null, "e": 1884, "s": 1788, "text": "Method 2 − Another way of installing packages is by the use of terminal or an Anaconda Prompt −" }, { "code": null, "e": 1905, "s": 1884, "text": "conda install opencv" }, { "code": null, "e": 1978, "s": 1905, "text": "Above command will install OpenCV package into your current environment." }, { "code": null, "e": 2039, "s": 1978, "text": "To install specific a specific version of a opencv package −" }, { "code": null, "e": 2066, "s": 2039, "text": "conda install opencv-3.4.2" }, { "code": null, "e": 2140, "s": 2066, "text": "We can install multiple packages at once, such as OpenCV and tensorflow −" }, { "code": null, "e": 2172, "s": 2140, "text": "conda install opencv tensorflow" }, { "code": null, "e": 2293, "s": 2172, "text": "Note − It is recommended to install all required packages at once so that all of the dependencies are installed at once." }, { "code": null, "e": 2455, "s": 2293, "text": "To install a specific package such as opencv into your existing environment “myenv”(in case you have a virtual environment to install project specific packages)." }, { "code": null, "e": 2488, "s": 2455, "text": "conda install –name myenv opencv" }, { "code": null, "e": 2662, "s": 2488, "text": "Method 3 − If the package is not available in our conda environment or through anaconda navigator, we can find and install the package with another package manager like pip." }, { "code": null, "e": 2746, "s": 2662, "text": "We can install pip in our existing conda environment by simply giving the command −" }, { "code": null, "e": 2764, "s": 2746, "text": "conda install pip" }, { "code": null, "e": 2821, "s": 2764, "text": "And your screen will be shown an output something like −" }, { "code": null, "e": 2926, "s": 2821, "text": "Now if you want to install any particular package, through pip in conda environment, we can do it like −" }, { "code": null, "e": 2999, "s": 2926, "text": "Above we have installed opencv package through pip in conda environment." }, { "code": null, "e": 3087, "s": 2999, "text": "We can use the anaconda prompt, to list all of the packages in the active environment −" }, { "code": null, "e": 3098, "s": 3087, "text": "conda list" } ]
Uri.EscapeDataString(String) Method in C#
The Uri.EscapeDataString() method in C# converts a string to its escaped representation. Following is the syntax − public static string EscapeDataString (string str); Above, the string str is the string to escape. Let us now see an example to implement the Uri.EscapeDataString() method − using System; public class Demo { public static void Main(){ string URI1 = "https://www.tutorialspoint.com/index.htm"; Console.WriteLine("URI = "+URI1); string URI2 = "https://www.tutorialspoint.com/"; Console.WriteLine("URI = "+URI2); Console.WriteLine("\nEscaped string (URI1) = "+Uri.EscapeDataString(URI1)); Console.WriteLine("Escaped string (URI2) = "+Uri.EscapeDataString(URI2)); } } This will produce the following output − URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/ Escaped string (URI1) = https%3A%2F%2Fwww.tutorialspoint.com%2Findex.htm Escaped string (URI2) = https%3A%2F%2Fwww.tutorialspoint.com%2F
[ { "code": null, "e": 1151, "s": 1062, "text": "The Uri.EscapeDataString() method in C# converts a string to its escaped representation." }, { "code": null, "e": 1177, "s": 1151, "text": "Following is the syntax −" }, { "code": null, "e": 1229, "s": 1177, "text": "public static string EscapeDataString (string str);" }, { "code": null, "e": 1276, "s": 1229, "text": "Above, the string str is the string to escape." }, { "code": null, "e": 1351, "s": 1276, "text": "Let us now see an example to implement the Uri.EscapeDataString() method −" }, { "code": null, "e": 1783, "s": 1351, "text": "using System;\npublic class Demo {\n public static void Main(){\n string URI1 = \"https://www.tutorialspoint.com/index.htm\";\n Console.WriteLine(\"URI = \"+URI1);\n string URI2 = \"https://www.tutorialspoint.com/\";\n Console.WriteLine(\"URI = \"+URI2);\n Console.WriteLine(\"\\nEscaped string (URI1) = \"+Uri.EscapeDataString(URI1));\n Console.WriteLine(\"Escaped string (URI2) = \"+Uri.EscapeDataString(URI2));\n }\n}" }, { "code": null, "e": 1824, "s": 1783, "text": "This will produce the following output −" }, { "code": null, "e": 2046, "s": 1824, "text": "URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/\nEscaped string (URI1) = https%3A%2F%2Fwww.tutorialspoint.com%2Findex.htm\nEscaped string (URI2) = https%3A%2F%2Fwww.tutorialspoint.com%2F" } ]
How to append data into a CSV file using PowerShell?
To append the data into CSV file you need to use –Append parameter while exporting to the CSV file. In the below example, we have created a CSV file $outfile = "C:\temp\Outfile.csv" $newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile $csvfile = Import-Csv $outfile $csvfile.Emp_Name = "Charles" $csvfile.EMP_ID = "2000" $csvfile.CITY = "New York" $csvfile | Export-CSV $outfile Import-Csv $outfile Now we need to append the below data to the existing file. So first we will import the csv file into a variable called $csvfile $csvfile = Import-Csv $outfile $csvfile.Emp_Name = "James" $csvfile.EMP_ID = "2500" $csvfile.CITY = "Scotland" Once data is inserted into a variable, we will append data with –Append parameter. $csvfile | Export-CSV $outfile –Append Check the output: Import-Csv $outfile EMP_Name EMP_ID CITY -------- ------ ---- Charles 2000 New York James 2500 Scotland
[ { "code": null, "e": 1162, "s": 1062, "text": "To append the data into CSV file you need to use –Append parameter while exporting to the CSV file." }, { "code": null, "e": 1211, "s": 1162, "text": "In the below example, we have created a CSV file" }, { "code": null, "e": 1479, "s": 1211, "text": "$outfile = \"C:\\temp\\Outfile.csv\"\n$newcsv = {} | Select \"EMP_Name\",\"EMP_ID\",\"CITY\" | Export-Csv $outfile\n$csvfile = Import-Csv $outfile\n$csvfile.Emp_Name = \"Charles\"\n$csvfile.EMP_ID = \"2000\"\n$csvfile.CITY = \"New York\"\n$csvfile | Export-CSV\n$outfile Import-Csv $outfile" }, { "code": null, "e": 1607, "s": 1479, "text": "Now we need to append the below data to the existing file. So first we will import the csv file into a variable called $csvfile" }, { "code": null, "e": 1718, "s": 1607, "text": "$csvfile = Import-Csv $outfile\n$csvfile.Emp_Name = \"James\"\n$csvfile.EMP_ID = \"2500\"\n$csvfile.CITY = \"Scotland\"" }, { "code": null, "e": 1801, "s": 1718, "text": "Once data is inserted into a variable, we will append data with –Append parameter." }, { "code": null, "e": 1840, "s": 1801, "text": "$csvfile | Export-CSV $outfile –Append" }, { "code": null, "e": 1858, "s": 1840, "text": "Check the output:" }, { "code": null, "e": 1878, "s": 1858, "text": "Import-Csv $outfile" }, { "code": null, "e": 1998, "s": 1878, "text": "EMP_Name EMP_ID CITY\n-------- ------ ----\nCharles 2000 New York\nJames 2500 Scotland" } ]
How to install c c compiler and development tools in ubuntu
Many of the Linux engineers are required to do some general programming languages to automate their normal tasks This article explains how to install C and C++ compilers and it’s development tools (build-essential) and related packages such as make,libc-dev,dpkg-dev, etc in Linux. Before getting into installation part, It is better if we can know about compiler. “A compiler is a software program that processes statements written in a particular programming language and creates a binary file which the machine’s CPU can easily understand and executes them” If Build-Essential Tools are not installed in your system then, use the following command- $ sudo apt-get install build-essential The output should be like this – Reading state information... Done The following packages were automatically installed and are no longer required: gcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386 libasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386 libavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl libcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl libcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl libdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386 libdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386 libffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386 libgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386 libgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386 libglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386 libgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386 libgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386 libgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386 libhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386 libhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386 libjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386 libk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386 libkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386 libltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl libogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386 libp11-kit-gnome-keyring:i386 libp11-kit0:i386 libpciaccess0:i386 ........................ We should delete old cache files to speed up compilation. To install cache management tool, use the following commands- $ sudo apt-get install aptitude The output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: gcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386 libasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386 libavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl libcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl libcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl libdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386 libdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386 libffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386 libgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386 libgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386 libglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386 libgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386 libgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386 libgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386 libhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386 libhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386 libjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386 libk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386 libkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386 libltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl libogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386 libp11-kit-gnome-keyring:i386 libp11-kit0:i386 libpciaccess0:i386 libpulse0:i386 libroken18-heimdal:i386 libsamplerate0:i386 libsane:i386 libsasl2-2:i386 libsasl2-modules:i386 libsasl2-modules-db:i386 libsm6:i386 libsndfile1:i386 libspeexdsp1:i386 libsqlite3-0:i386 libssl1.0.0:i386 libstdc++6:i386 libtasn1-6:i386 libtiff5:i386 libtxc-dxtn-s2tc0:i386 libusb-1.0-0:i386 libv4l-0:i386 libv4lconvert0:i386 libvorbis0a:i386 ................................... Now install ccache tool using aptitude as shown below – $ sudo aptitude install ccache The sample output should be like this – The following NEW packages will be installed: ccache The following packages will be REMOVED: gcc-4.8-base:i386{u} libasn1-8-heimdal:i386{u} libasound2:i386{u} libasound2-plugins:i386{u} libasyncns0:i386{u} libavahi-client3:i386{u} libavahi-common-data:i386{u} libavahi-common3:i386{u} libbit-vector-perl{u} libcapi20-3:i386{u} libcarp-clan-perl{u} libclass-method-modifiers-perl{u} libcups2:i386{u} libdata-random-perl{u} libdate-calc-perl{u} libdate-calc-xs-perl{u} libdrm-amdgpu1:i386{u} libdrm-intel1:i386{u} libdrm-nouveau2:i386{u} libdrm-radeon1:i386{u} libedit2:i386{u} libelf1:i386{u} libexif12:i386{u} libexpat1:i386{u} libffi6:i386{u} libflac8:i386{u} libfontconfig1:i386{u} libfreetype6:i386{u} libgcrypt11:i386{u} libgd-perl{u} libgd3:i386{u} libgif4:i386{u} libgl1-mesa-dri-lts-wily:i386{u} libgl1-mesa-glx-lts-wily:i386{u} libglapi-mesa-lts-wily:i386{u} libglib2.0-0:i386{u} libglu1-mesa:i386{u} libgnome2-gconf-perl{u} libgnutls26:i386{u} libgpg-error0:i386{u} libgphoto2-6:i386{u} libgphoto2-port10:i386{u} libgssapi-krb5-2:i386{u} libgssapi3-heimdal:i386{u} libgstreamer-plugins-base0.10-0:i386{u} ......................................... For instance, to test a C program, create a file called sum.c and add the following command- #include int main() { int a, b, c; printf("Enter two numbers to add: "); scanf("%d%d",&a,&b); c = a + b; printf("The sum of two numbers equals %d\n",c); return 0; } The above command gives the result of a sum of two numbers. To compile the above code into an executable named sum in the current working directory use the -o switch with gcc– $ gcc sum.c -o sum To use ccache command, use the following command- $ ccache gcc sum.c -o sum To run binary command, use the following command – $ ./sum The sample output should be like this – $ ./sum Enter two numbers to add: 24 54 The sum of equals 78 Congratulations! Now, you know “How to Install C, C++ Compiler and Development Tools in Ubuntu”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1344, "s": 1062, "text": "Many of the Linux engineers are required to do some general programming languages to automate their normal tasks This article explains how to install C and C++ compilers and it’s development tools (build-essential) and related packages such as make,libc-dev,dpkg-dev, etc in Linux." }, { "code": null, "e": 1427, "s": 1344, "text": "Before getting into installation part, It is better if we can know about compiler." }, { "code": null, "e": 1623, "s": 1427, "text": "“A compiler is a software program that processes statements written in a particular programming language and creates a binary file which the machine’s CPU can easily understand and executes them”" }, { "code": null, "e": 1714, "s": 1623, "text": "If Build-Essential Tools are not installed in your system then, use the following command-" }, { "code": null, "e": 1753, "s": 1714, "text": "$ sudo apt-get install build-essential" }, { "code": null, "e": 1786, "s": 1753, "text": "The output should be like this –" }, { "code": null, "e": 3383, "s": 1786, "text": "Reading state information... Done\nThe following packages were automatically installed and are no longer required:\ngcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386\nlibasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386\nlibavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl\nlibcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl\nlibcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl\nlibdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386\nlibdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386\nlibffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386\nlibgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386\nlibgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386\nlibglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386\nlibgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386\nlibgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386\nlibgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386\nlibhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386\nlibhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386\nlibjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386\nlibk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386\nlibkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386\nlibltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl\nlibogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386\nlibp11-kit-gnome-keyring:i386 libp11-kit0:i386 libpciaccess0:i386\n........................" }, { "code": null, "e": 3503, "s": 3383, "text": "We should delete old cache files to speed up compilation. To install cache management tool, use the following commands-" }, { "code": null, "e": 3535, "s": 3503, "text": "$ sudo apt-get install aptitude" }, { "code": null, "e": 3568, "s": 3535, "text": "The output should be like this –" }, { "code": null, "e": 5586, "s": 3568, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\ngcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386\nlibasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386\nlibavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl\nlibcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl\nlibcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl\nlibdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386\nlibdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386\nlibffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386\nlibgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386\nlibgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386\nlibglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386\nlibgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386\nlibgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386\nlibgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386\nlibhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386\nlibhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386\nlibjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386\nlibk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386\nlibkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386\nlibltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl\nlibogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386\nlibp11-kit-gnome-keyring:i386 libp11-kit0:i386 libpciaccess0:i386\nlibpulse0:i386 libroken18-heimdal:i386 libsamplerate0:i386 libsane:i386\nlibsasl2-2:i386 libsasl2-modules:i386 libsasl2-modules-db:i386 libsm6:i386\nlibsndfile1:i386 libspeexdsp1:i386 libsqlite3-0:i386 libssl1.0.0:i386\nlibstdc++6:i386 libtasn1-6:i386 libtiff5:i386 libtxc-dxtn-s2tc0:i386\nlibusb-1.0-0:i386 libv4l-0:i386 libv4lconvert0:i386 libvorbis0a:i386\n..................................." }, { "code": null, "e": 5642, "s": 5586, "text": "Now install ccache tool using aptitude as shown below –" }, { "code": null, "e": 5673, "s": 5642, "text": "$ sudo aptitude install ccache" }, { "code": null, "e": 5713, "s": 5673, "text": "The sample output should be like this –" }, { "code": null, "e": 6869, "s": 5713, "text": "The following NEW packages will be installed:\nccache\nThe following packages will be REMOVED:\ngcc-4.8-base:i386{u} libasn1-8-heimdal:i386{u} libasound2:i386{u}\nlibasound2-plugins:i386{u} libasyncns0:i386{u} libavahi-client3:i386{u}\nlibavahi-common-data:i386{u} libavahi-common3:i386{u}\nlibbit-vector-perl{u} libcapi20-3:i386{u} libcarp-clan-perl{u}\nlibclass-method-modifiers-perl{u} libcups2:i386{u} libdata-random-perl{u}\nlibdate-calc-perl{u} libdate-calc-xs-perl{u} libdrm-amdgpu1:i386{u}\nlibdrm-intel1:i386{u} libdrm-nouveau2:i386{u} libdrm-radeon1:i386{u}\nlibedit2:i386{u} libelf1:i386{u} libexif12:i386{u} libexpat1:i386{u}\nlibffi6:i386{u} libflac8:i386{u} libfontconfig1:i386{u}\nlibfreetype6:i386{u} libgcrypt11:i386{u} libgd-perl{u} libgd3:i386{u}\nlibgif4:i386{u} libgl1-mesa-dri-lts-wily:i386{u}\nlibgl1-mesa-glx-lts-wily:i386{u} libglapi-mesa-lts-wily:i386{u}\nlibglib2.0-0:i386{u} libglu1-mesa:i386{u} libgnome2-gconf-perl{u}\nlibgnutls26:i386{u} libgpg-error0:i386{u} libgphoto2-6:i386{u}\nlibgphoto2-port10:i386{u} libgssapi-krb5-2:i386{u}\nlibgssapi3-heimdal:i386{u} libgstreamer-plugins-base0.10-0:i386{u}\n........................................." }, { "code": null, "e": 6962, "s": 6869, "text": "For instance, to test a C program, create a file called sum.c and add the following command-" }, { "code": null, "e": 7145, "s": 6962, "text": "#include\nint main()\n{\n int a, b, c;\n printf(\"Enter two numbers to add: \");\n scanf(\"%d%d\",&a,&b);\n c = a + b;\n printf(\"The sum of two numbers equals %d\\n\",c);\n return 0;\n}" }, { "code": null, "e": 7321, "s": 7145, "text": "The above command gives the result of a sum of two numbers. To compile the above code into an executable named sum in the current working directory use the -o switch with gcc–" }, { "code": null, "e": 7340, "s": 7321, "text": "$ gcc sum.c -o sum" }, { "code": null, "e": 7390, "s": 7340, "text": "To use ccache command, use the following command-" }, { "code": null, "e": 7416, "s": 7390, "text": "$ ccache gcc sum.c -o sum" }, { "code": null, "e": 7467, "s": 7416, "text": "To run binary command, use the following command –" }, { "code": null, "e": 7475, "s": 7467, "text": "$ ./sum" }, { "code": null, "e": 7515, "s": 7475, "text": "The sample output should be like this –" }, { "code": null, "e": 7576, "s": 7515, "text": "$ ./sum\nEnter two numbers to add: 24 54\nThe sum of equals 78" }, { "code": null, "e": 7758, "s": 7576, "text": "Congratulations! Now, you know “How to Install C, C++ Compiler and Development Tools in Ubuntu”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Minimum time to finish tasks without skipping two consecutive - GeeksforGeeks
01 Feb, 2022 Given time taken by n tasks. Find the minimum time needed to finish the tasks such that skipping of tasks is allowed, but can not skip two consecutive tasks.Examples : Input : arr[] = {10, 5, 7, 10} Output : 12 We can skip first and last task and finish these task in 12 min. Input : arr[] = {10} Output : 0 There is only one task and we can skip it. Input : arr[] = {10, 30} Output : 10 Input : arr[] = {10, 5, 2, 4, 8, 6, 7, 10} Output : 22 Expected Time Complexity is O(n) and extra space is O(1). The given problem has the following recursive property.Let minTime(i) be minimum time to finish till i’th task. It can be written as minimum of two values. Minimum time if i’th task is included in list, let this time be incl(i)Minimum time if i’th task is excluded from result, let this time be excl(i) Minimum time if i’th task is included in list, let this time be incl(i) Minimum time if i’th task is excluded from result, let this time be excl(i) minTime(i) = min(excl(i), incl(i)) Result is minTime(n-1) if there are n tasks and indexes start from 0.incl(i) can be written as below. // There are two possibilities // (a) Previous task is also included // (b) Previous task is not included incl(i) = min(incl(i-1), excl(i-1)) + arr[i] // Since this is inclusive // arr[i] must be included excl(i) can be written as below. // There is only one possibility (Previous task must be // included as we can't skip consecutive tasks. excl(i) = incl(i-1) A simple solution is to make two tables incl[] and excl[] to store times for tasks. Finally return minimum of incl[n-1] and excl[n-1]. This solution requires O(n) time and O(n) space.If we take a closer look, we can notice that we only need incl and excl of previous job. So we can save space and solve the problem in O(n) time and O(1) space. Below is C++ implementation of the idea. C++ Java Python3 C# PHP Javascript // C++ program to find minimum time to finish tasks// such that no two consecutive tasks are skipped.#include <bits/stdc++.h>using namespace std; // arr[] represents time taken by n given tasksint minTime(int arr[], int n){ // Corner Cases if (n <= 0) return 0; // Initialize value for the case when there // is only one task in task list. int incl = arr[0]; // First task is included int excl = 0; // First task is excluded // Process remaining n-1 tasks for (int i=1; i<n; i++) { // Time taken if current task is included // There are two possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + min(excl, incl); // Time taken when current task is not // included. There is only one possibility // that previous task is also included. int excl_new = incl; // Update incl and excl for next iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for last task return min(incl, excl);} // Driver codeint main(){ int arr1[] = {10, 5, 2, 7, 10}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << minTime(arr1, n1) << endl; int arr2[] = {10, 5, 7, 10}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << minTime(arr2, n2) << endl; int arr3[] = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout << minTime(arr3, n3) << endl; return 0;} // Java program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped.import java.io.*; class GFG { // arr[] represents time taken by n // given tasks static int minTime(int arr[], int n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included int incl = arr[0]; // First task is excluded int excl = 0; // Process remaining n-1 tasks for (int i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + Math.min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. int excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.min(incl, excl); } // Driver code public static void main(String[] args) { int arr1[] = {10, 5, 2, 7, 10}; int n1 = arr1.length; System.out.println(minTime(arr1, n1)); int arr2[] = {10, 5, 7, 10}; int n2 = arr2.length; System.out.println(minTime(arr2, n2)); int arr3[] = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = arr3.length; System.out.println(minTime(arr3, n3)); }}// This code is contributed by Prerna Saini # Python3 program to find minimum# time to finish tasks such that no# two consecutive tasks are skipped. # arr[] represents time# taken by n given tasksdef minTime(arr, n): # Corner Cases if (n <= 0): return 0 # Initialize value for the # case when there is only # one task in task list. incl = arr[0] # First task is included excl = 0 # First task is excluded # Process remaining n-1 tasks for i in range(1, n): # Time taken if current task is included # There are two possibilities # (a) Previous task is also included # (b) Previous task is not included incl_new = arr[i] + min(excl, incl) # Time taken when current task is not # included. There is only one possibility # that previous task is also included. excl_new = incl # Update incl and excl for next iteration incl = incl_new excl = excl_new # Return minimum of two values for last task return min(incl, excl) # Driver codearr1 = [10, 5, 2, 7, 10]n1 = len(arr1)print(minTime(arr1, n1)) arr2 = [10, 5, 7, 10]n2 = len(arr2)print(minTime(arr2, n2)) arr3 = [10, 5, 2, 4, 8, 6, 7, 10]n3 = len(arr3)print(minTime(arr3, n3)) # This code is contributed by Anant Agarwal. // C# program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped.using System; class GFG { // arr[] represents time taken by n // given tasks static int minTime(int []arr, int n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included int incl = arr[0]; // First task is excluded int excl = 0; // Process remaining n-1 tasks for (int i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + Math.Min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. int excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.Min(incl, excl); } // Driver code public static void Main() { int []arr1 = {10, 5, 2, 7, 10}; int n1 = arr1.Length; Console.WriteLine(minTime(arr1, n1)); int []arr2 = {10, 5, 7, 10}; int n2 = arr2.Length; Console.WriteLine(minTime(arr2, n2)); int []arr3 = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = arr3.Length; Console.WriteLine(minTime(arr3, n3)); }}// This code is contributed by Anant Agarwal. <?php// PHP program to find minimum time// to finish tasks such that no two// consecutive tasks are skipped. // arr[] represents time// taken by n given tasksfunction minTime($arr, $n){ // Corner Cases if ($n <= 0) return 0; // Initialize value for the // case when there is only // one task in task list. // First task is included $incl = $arr[0]; // First task is excluded $excl = 0; // Process remaining n-1 tasks for ($i = 1; $i < $n; $i++) { // Time taken if current task is // included There are two possibilities // (a) Previous task is also included // (b) Previous task is not included $incl_new = $arr[$i] + min($excl, $incl); // Time taken when current task // is not included. There is only // one possibility that previous // task is also included. $excl_new = $incl; // Update incl and excl // for next iteration $incl = $incl_new; $excl = $excl_new; } // Return minimum of two // values for last task return min($incl, $excl);} // Driver code $arr1 = array(10, 5, 2, 7, 10);$n1 = sizeof($arr1);echo minTime($arr1, $n1),"\n" ; $arr2 = array(10, 5, 7, 10);$n2 = sizeof($arr2);echo minTime($arr2, $n2),"\n" ; $arr3 = array(10, 5, 2, 4, 8, 6, 7, 10);$n3 = sizeof($arr3);echo minTime($arr3, $n3); // This code is contributed// by nitin mittal.?> <script> // Javascript program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped. // arr[] represents time taken by n // given tasks function minTime(arr, n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included let incl = arr[0]; // First task is excluded let excl = 0; // Process remaining n-1 tasks for (let i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included let incl_new = arr[i] + Math.min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. let excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.min(incl, excl); } // Driver Code let arr1 = [10, 5, 2, 7, 10]; let n1 = arr1.length; document.write(minTime(arr1, n1) + "<br/>"); let arr2 = [10, 5, 7, 10]; let n2 = arr2.length; document.write(minTime(arr2, n2) + "<br/>"); let arr3 = [10, 5, 2, 4, 8, 6, 7, 10]; let n3 = arr3.length; document.write(minTime(arr3, n3) + "<br/>"); </script> Output : 12 12 22 Related Problems: Find minimum time to finish all jobs with given constraints Maximum sum such that no two elements are adjacent.This article is contributed by Arnab Dutta. 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 nitin mittal souravghosh0416 hrithik2108 sumitgumber28 Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Subset Sum Problem | DP-25 Coin Change | DP-7 Sieve of Eratosthenes Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Efficient program to print all prime factors of a given number
[ { "code": null, "e": 25020, "s": 24992, "text": "\n01 Feb, 2022" }, { "code": null, "e": 25189, "s": 25020, "text": "Given time taken by n tasks. Find the minimum time needed to finish the tasks such that skipping of tasks is allowed, but can not skip two consecutive tasks.Examples : " }, { "code": null, "e": 25467, "s": 25189, "text": "Input : arr[] = {10, 5, 7, 10}\nOutput : 12\nWe can skip first and last task and\nfinish these task in 12 min.\n\nInput : arr[] = {10}\nOutput : 0\nThere is only one task and we can\nskip it.\n\nInput : arr[] = {10, 30}\nOutput : 10\n\nInput : arr[] = {10, 5, 2, 4, 8, 6, 7, 10}\nOutput : 22" }, { "code": null, "e": 25526, "s": 25467, "text": "Expected Time Complexity is O(n) and extra space is O(1). " }, { "code": null, "e": 25683, "s": 25526, "text": "The given problem has the following recursive property.Let minTime(i) be minimum time to finish till i’th task. It can be written as minimum of two values. " }, { "code": null, "e": 25830, "s": 25683, "text": "Minimum time if i’th task is included in list, let this time be incl(i)Minimum time if i’th task is excluded from result, let this time be excl(i)" }, { "code": null, "e": 25902, "s": 25830, "text": "Minimum time if i’th task is included in list, let this time be incl(i)" }, { "code": null, "e": 25978, "s": 25902, "text": "Minimum time if i’th task is excluded from result, let this time be excl(i)" }, { "code": null, "e": 26016, "s": 25980, "text": "minTime(i) = min(excl(i), incl(i)) " }, { "code": null, "e": 26119, "s": 26016, "text": "Result is minTime(n-1) if there are n tasks and indexes start from 0.incl(i) can be written as below. " }, { "code": null, "e": 26361, "s": 26119, "text": "// There are two possibilities\n// (a) Previous task is also included\n// (b) Previous task is not included\nincl(i) = min(incl(i-1), excl(i-1)) +\n arr[i] // Since this is inclusive \n // arr[i] must be included " }, { "code": null, "e": 26395, "s": 26361, "text": "excl(i) can be written as below. " }, { "code": null, "e": 26521, "s": 26395, "text": "// There is only one possibility (Previous task must be\n// included as we can't skip consecutive tasks.\nexcl(i) = incl(i-1) " }, { "code": null, "e": 26908, "s": 26521, "text": "A simple solution is to make two tables incl[] and excl[] to store times for tasks. Finally return minimum of incl[n-1] and excl[n-1]. This solution requires O(n) time and O(n) space.If we take a closer look, we can notice that we only need incl and excl of previous job. So we can save space and solve the problem in O(n) time and O(1) space. Below is C++ implementation of the idea. " }, { "code": null, "e": 26912, "s": 26908, "text": "C++" }, { "code": null, "e": 26917, "s": 26912, "text": "Java" }, { "code": null, "e": 26925, "s": 26917, "text": "Python3" }, { "code": null, "e": 26928, "s": 26925, "text": "C#" }, { "code": null, "e": 26932, "s": 26928, "text": "PHP" }, { "code": null, "e": 26943, "s": 26932, "text": "Javascript" }, { "code": "// C++ program to find minimum time to finish tasks// such that no two consecutive tasks are skipped.#include <bits/stdc++.h>using namespace std; // arr[] represents time taken by n given tasksint minTime(int arr[], int n){ // Corner Cases if (n <= 0) return 0; // Initialize value for the case when there // is only one task in task list. int incl = arr[0]; // First task is included int excl = 0; // First task is excluded // Process remaining n-1 tasks for (int i=1; i<n; i++) { // Time taken if current task is included // There are two possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + min(excl, incl); // Time taken when current task is not // included. There is only one possibility // that previous task is also included. int excl_new = incl; // Update incl and excl for next iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for last task return min(incl, excl);} // Driver codeint main(){ int arr1[] = {10, 5, 2, 7, 10}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << minTime(arr1, n1) << endl; int arr2[] = {10, 5, 7, 10}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << minTime(arr2, n2) << endl; int arr3[] = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout << minTime(arr3, n3) << endl; return 0;}", "e": 28429, "s": 26943, "text": null }, { "code": "// Java program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped.import java.io.*; class GFG { // arr[] represents time taken by n // given tasks static int minTime(int arr[], int n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included int incl = arr[0]; // First task is excluded int excl = 0; // Process remaining n-1 tasks for (int i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + Math.min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. int excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.min(incl, excl); } // Driver code public static void main(String[] args) { int arr1[] = {10, 5, 2, 7, 10}; int n1 = arr1.length; System.out.println(minTime(arr1, n1)); int arr2[] = {10, 5, 7, 10}; int n2 = arr2.length; System.out.println(minTime(arr2, n2)); int arr3[] = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = arr3.length; System.out.println(minTime(arr3, n3)); }}// This code is contributed by Prerna Saini", "e": 30190, "s": 28429, "text": null }, { "code": "# Python3 program to find minimum# time to finish tasks such that no# two consecutive tasks are skipped. # arr[] represents time# taken by n given tasksdef minTime(arr, n): # Corner Cases if (n <= 0): return 0 # Initialize value for the # case when there is only # one task in task list. incl = arr[0] # First task is included excl = 0 # First task is excluded # Process remaining n-1 tasks for i in range(1, n): # Time taken if current task is included # There are two possibilities # (a) Previous task is also included # (b) Previous task is not included incl_new = arr[i] + min(excl, incl) # Time taken when current task is not # included. There is only one possibility # that previous task is also included. excl_new = incl # Update incl and excl for next iteration incl = incl_new excl = excl_new # Return minimum of two values for last task return min(incl, excl) # Driver codearr1 = [10, 5, 2, 7, 10]n1 = len(arr1)print(minTime(arr1, n1)) arr2 = [10, 5, 7, 10]n2 = len(arr2)print(minTime(arr2, n2)) arr3 = [10, 5, 2, 4, 8, 6, 7, 10]n3 = len(arr3)print(minTime(arr3, n3)) # This code is contributed by Anant Agarwal.", "e": 31451, "s": 30190, "text": null }, { "code": "// C# program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped.using System; class GFG { // arr[] represents time taken by n // given tasks static int minTime(int []arr, int n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included int incl = arr[0]; // First task is excluded int excl = 0; // Process remaining n-1 tasks for (int i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included int incl_new = arr[i] + Math.Min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. int excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.Min(incl, excl); } // Driver code public static void Main() { int []arr1 = {10, 5, 2, 7, 10}; int n1 = arr1.Length; Console.WriteLine(minTime(arr1, n1)); int []arr2 = {10, 5, 7, 10}; int n2 = arr2.Length; Console.WriteLine(minTime(arr2, n2)); int []arr3 = {10, 5, 2, 4, 8, 6, 7, 10}; int n3 = arr3.Length; Console.WriteLine(minTime(arr3, n3)); }}// This code is contributed by Anant Agarwal.", "e": 33203, "s": 31451, "text": null }, { "code": "<?php// PHP program to find minimum time// to finish tasks such that no two// consecutive tasks are skipped. // arr[] represents time// taken by n given tasksfunction minTime($arr, $n){ // Corner Cases if ($n <= 0) return 0; // Initialize value for the // case when there is only // one task in task list. // First task is included $incl = $arr[0]; // First task is excluded $excl = 0; // Process remaining n-1 tasks for ($i = 1; $i < $n; $i++) { // Time taken if current task is // included There are two possibilities // (a) Previous task is also included // (b) Previous task is not included $incl_new = $arr[$i] + min($excl, $incl); // Time taken when current task // is not included. There is only // one possibility that previous // task is also included. $excl_new = $incl; // Update incl and excl // for next iteration $incl = $incl_new; $excl = $excl_new; } // Return minimum of two // values for last task return min($incl, $excl);} // Driver code $arr1 = array(10, 5, 2, 7, 10);$n1 = sizeof($arr1);echo minTime($arr1, $n1),\"\\n\" ; $arr2 = array(10, 5, 7, 10);$n2 = sizeof($arr2);echo minTime($arr2, $n2),\"\\n\" ; $arr3 = array(10, 5, 2, 4, 8, 6, 7, 10);$n3 = sizeof($arr3);echo minTime($arr3, $n3); // This code is contributed// by nitin mittal.?>", "e": 34587, "s": 33203, "text": null }, { "code": "<script> // Javascript program to find minimum time to// finish tasks such that no two// consecutive tasks are skipped. // arr[] represents time taken by n // given tasks function minTime(arr, n) { // Corner Cases if (n <= 0) return 0; // Initialize value for the case // when there is only one task in // task list. // First task is included let incl = arr[0]; // First task is excluded let excl = 0; // Process remaining n-1 tasks for (let i = 1; i < n; i++) { // Time taken if current task is // included. There are two // possibilities // (a) Previous task is also included // (b) Previous task is not included let incl_new = arr[i] + Math.min(excl, incl); // Time taken when current task is not // included. There is only one // possibility that previous task is // also included. let excl_new = incl; // Update incl and excl for next // iteration incl = incl_new; excl = excl_new; } // Return minimum of two values for // last task return Math.min(incl, excl); } // Driver Code let arr1 = [10, 5, 2, 7, 10]; let n1 = arr1.length; document.write(minTime(arr1, n1) + \"<br/>\"); let arr2 = [10, 5, 7, 10]; let n2 = arr2.length; document.write(minTime(arr2, n2) + \"<br/>\"); let arr3 = [10, 5, 2, 4, 8, 6, 7, 10]; let n3 = arr3.length; document.write(minTime(arr3, n3) + \"<br/>\"); </script>", "e": 36288, "s": 34587, "text": null }, { "code": null, "e": 36298, "s": 36288, "text": "Output : " }, { "code": null, "e": 36307, "s": 36298, "text": "12\n12\n22" }, { "code": null, "e": 36826, "s": 36307, "text": "Related Problems: Find minimum time to finish all jobs with given constraints Maximum sum such that no two elements are adjacent.This article is contributed by Arnab Dutta. 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": 36839, "s": 36826, "text": "nitin mittal" }, { "code": null, "e": 36855, "s": 36839, "text": "souravghosh0416" }, { "code": null, "e": 36867, "s": 36855, "text": "hrithik2108" }, { "code": null, "e": 36881, "s": 36867, "text": "sumitgumber28" }, { "code": null, "e": 36901, "s": 36881, "text": "Dynamic Programming" }, { "code": null, "e": 36921, "s": 36901, "text": "Dynamic Programming" }, { "code": null, "e": 37019, "s": 36921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37050, "s": 37019, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 37083, "s": 37050, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 37118, "s": 37083, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 37186, "s": 37118, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 37213, "s": 37186, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 37232, "s": 37213, "text": "Coin Change | DP-7" }, { "code": null, "e": 37254, "s": 37232, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 37275, "s": 37254, "text": "Edit Distance | DP-5" }, { "code": null, "e": 37338, "s": 37275, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
Types of CSS (Cascading Style Sheet) - GeeksforGeeks
30 Jul, 2021 Cascading Style Sheet(CSS) is used to set the style in web pages that contain HTML elements. It sets the background color, font-size, font-family, color, ... etc property of elements on a web page. There are three types of CSS which are given below: Inline CSS Internal or Embedded CSS External CSS Inline CSS: Inline CSS contains the CSS property in the body section attached with element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. Example: html <!DOCTYPE html><html> <head> <title>Inline CSS</title> </head> <body> <p style = "color:#009900; font-size:50px; font-style:italic; text-align:center;"> GeeksForGeeks </p> </body></html> Output: Internal or Embedded CSS: This can be used when a single HTML document must be styled uniquely. The CSS rule set should be within the HTML file in the head section i.e the CSS is embedded within the HTML file. Example: html <!DOCTYPE html><html> <head> <title>Internal CSS</title> <style> .main { text-align:center; } .GFG { color:#009900; font-size:50px; font-weight:bold; } .geeks { font-style:bold; font-size:20px; } </style> </head> <body> <div class = "main"> <div class ="GFG">GeeksForGeeks</div> <div class ="geeks"> A computer science portal for geeks </div> </div> </body></html> Output: External CSS: External CSS contains separate CSS file which contains only style property with the help of tag attributes (For example class, id, heading, ... etc). CSS property written in a separate file with .css extension and should be linked to the HTML document using link tag. This means that for each element, style can be set only once and that will be applied across web pages.Example: The file given below contains CSS property. This file save with .css extension. For Ex: geeks.css body { background-color:powderblue; } .main { text-align:center; } .GFG { color:#009900; font-size:50px; font-weight:bold; } #geeks { font-style:bold; font-size:20px; } Below is the HTML file that is making use of the created external style sheet link tag is used to link the external style sheet with the html webpage. href attribute is used to specify the location of the external style sheet file. html <!DOCTYPE html><html> <head> <link rel="stylesheet" href="geeks.css"/> </head> <body> <div class = "main"> <div class ="GFG">GeeksForGeeks</div> <div id ="geeks"> A computer science portal for geeks </div> </div> </body></html> Output: Properties of CSS: Inline CSS has the highest priority, then comes Internal/Embedded followed by External CSS which has the least priority. Multiple style sheets can be defined on one page. If for an HTML tag, styles are defined in multiple style sheets then the below order will be followed. As Inline has the highest priority, any styles that are defined in the internal and external style sheets are overridden by Inline styles. Internal or Embedded stands second in the priority list and overrides the styles in the external style sheet. External style sheets have the least priority. If there are no styles defined either in inline or internal style sheet then external style sheet rules are applied for the HTML tags. Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. GAURAVKESHARI ysachin2314 CSS-Basics Picked CSS HTML Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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? CSS to put icon inside an input element in a form 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 set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 23172, "s": 23144, "text": "\n30 Jul, 2021" }, { "code": null, "e": 23424, "s": 23172, "text": "Cascading Style Sheet(CSS) is used to set the style in web pages that contain HTML elements. It sets the background color, font-size, font-family, color, ... etc property of elements on a web page. There are three types of CSS which are given below: " }, { "code": null, "e": 23435, "s": 23424, "text": "Inline CSS" }, { "code": null, "e": 23460, "s": 23435, "text": "Internal or Embedded CSS" }, { "code": null, "e": 23473, "s": 23460, "text": "External CSS" }, { "code": null, "e": 23677, "s": 23473, "text": "Inline CSS: Inline CSS contains the CSS property in the body section attached with element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. Example: " }, { "code": null, "e": 23682, "s": 23677, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Inline CSS</title> </head> <body> <p style = \"color:#009900; font-size:50px; font-style:italic; text-align:center;\"> GeeksForGeeks </p> </body></html> ", "e": 23945, "s": 23682, "text": null }, { "code": null, "e": 23955, "s": 23945, "text": "Output: " }, { "code": null, "e": 24176, "s": 23955, "text": "Internal or Embedded CSS: This can be used when a single HTML document must be styled uniquely. The CSS rule set should be within the HTML file in the head section i.e the CSS is embedded within the HTML file. Example: " }, { "code": null, "e": 24181, "s": 24176, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Internal CSS</title> <style> .main { text-align:center; } .GFG { color:#009900; font-size:50px; font-weight:bold; } .geeks { font-style:bold; font-size:20px; } </style> </head> <body> <div class = \"main\"> <div class =\"GFG\">GeeksForGeeks</div> <div class =\"geeks\"> A computer science portal for geeks </div> </div> </body></html> ", "e": 24826, "s": 24181, "text": null }, { "code": null, "e": 24836, "s": 24826, "text": "Output: " }, { "code": null, "e": 25330, "s": 24836, "text": "External CSS: External CSS contains separate CSS file which contains only style property with the help of tag attributes (For example class, id, heading, ... etc). CSS property written in a separate file with .css extension and should be linked to the HTML document using link tag. This means that for each element, style can be set only once and that will be applied across web pages.Example: The file given below contains CSS property. This file save with .css extension. For Ex: geeks.css " }, { "code": null, "e": 25530, "s": 25330, "text": "body {\n background-color:powderblue;\n}\n.main {\n text-align:center; \n}\n.GFG {\n color:#009900;\n font-size:50px;\n font-weight:bold;\n}\n#geeks {\n font-style:bold;\n font-size:20px;\n}" }, { "code": null, "e": 25610, "s": 25530, "text": "Below is the HTML file that is making use of the created external style sheet " }, { "code": null, "e": 25683, "s": 25610, "text": "link tag is used to link the external style sheet with the html webpage." }, { "code": null, "e": 25764, "s": 25683, "text": "href attribute is used to specify the location of the external style sheet file." }, { "code": null, "e": 25769, "s": 25764, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"geeks.css\"/> </head> <body> <div class = \"main\"> <div class =\"GFG\">GeeksForGeeks</div> <div id =\"geeks\"> A computer science portal for geeks </div> </div> </body></html>", "e": 26080, "s": 25769, "text": null }, { "code": null, "e": 26090, "s": 26080, "text": "Output: " }, { "code": null, "e": 26384, "s": 26090, "text": "Properties of CSS: Inline CSS has the highest priority, then comes Internal/Embedded followed by External CSS which has the least priority. Multiple style sheets can be defined on one page. If for an HTML tag, styles are defined in multiple style sheets then the below order will be followed. " }, { "code": null, "e": 26523, "s": 26384, "text": "As Inline has the highest priority, any styles that are defined in the internal and external style sheets are overridden by Inline styles." }, { "code": null, "e": 26633, "s": 26523, "text": "Internal or Embedded stands second in the priority list and overrides the styles in the external style sheet." }, { "code": null, "e": 26815, "s": 26633, "text": "External style sheets have the least priority. If there are no styles defined either in inline or internal style sheet then external style sheet rules are applied for the HTML tags." }, { "code": null, "e": 26834, "s": 26815, "text": "Supported Browser:" }, { "code": null, "e": 26848, "s": 26834, "text": "Google Chrome" }, { "code": null, "e": 26866, "s": 26848, "text": "Internet Explorer" }, { "code": null, "e": 26874, "s": 26866, "text": "Firefox" }, { "code": null, "e": 26880, "s": 26874, "text": "Opera" }, { "code": null, "e": 26887, "s": 26880, "text": "Safari" }, { "code": null, "e": 27081, "s": 26887, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 27267, "s": 27081, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 27404, "s": 27267, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27418, "s": 27404, "text": "GAURAVKESHARI" }, { "code": null, "e": 27430, "s": 27418, "text": "ysachin2314" }, { "code": null, "e": 27441, "s": 27430, "text": "CSS-Basics" }, { "code": null, "e": 27448, "s": 27441, "text": "Picked" }, { "code": null, "e": 27452, "s": 27448, "text": "CSS" }, { "code": null, "e": 27457, "s": 27452, "text": "HTML" }, { "code": null, "e": 27484, "s": 27457, "text": "Web technologies Questions" }, { "code": null, "e": 27489, "s": 27484, "text": "HTML" }, { "code": null, "e": 27587, "s": 27489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27596, "s": 27587, "text": "Comments" }, { "code": null, "e": 27609, "s": 27596, "text": "Old Comments" }, { "code": null, "e": 27671, "s": 27609, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27721, "s": 27671, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27769, "s": 27721, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27827, "s": 27769, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27877, "s": 27827, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27939, "s": 27877, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27989, "s": 27939, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28037, "s": 27989, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28097, "s": 28037, "text": "How to set the default value for an HTML <select> element ?" } ]
Express.js – app.use() Method
The app.use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path. app.use([path], callback, [callback]) path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these. path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these. callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route). callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route). Create a file with the name "appUse.js" and copy the following code snippet. After creating the file, use the command "node appUse.js" to run this code. // app.use() Method Demo Example // Importing the express module const express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // This method will call the next() middleware app.use('/api', function (req, res, next) { console.log('Time for main function: %d', Date.now()) next(); }) // Will be called after the middleware app.get('/api', function (req, res) { console.log('Time for middleware function: %d', Date.now()) res.send('Welcome to Tutorials Point') }) // App listening on the below port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); }); Now, hit the following Endpoint with a GET request http://localhost:3000/api C:\home\node>> node appUse.js Server listening on PORT 3000 Time for main function: 1627490133904 Time for middleware function: 1627490133905 Let’s take a look at one more example. // app.use() Method Demo Example // Importing the express module const express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // This method will call the next() middleware app.use('/', function (req, res, next) { console.log('Middleware will not be called') }) // Will be called after the middleware app.get('/api', function (req, res) { console.log('Time for middleware function: %d', Date.now()) res.send('Welcome to Tutorials Point') }) // App listening on the below port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); }); Now, hit the following Endpoint with a GET request http://localhost:3000/api C:\home\node>> node appUse.js Server listening on PORT 3000 Middleware will not be called
[ { "code": null, "e": 1265, "s": 1062, "text": "The app.use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path." }, { "code": null, "e": 1303, "s": 1265, "text": "app.use([path], callback, [callback])" }, { "code": null, "e": 1458, "s": 1303, "text": "path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these." }, { "code": null, "e": 1613, "s": 1458, "text": "path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these." }, { "code": null, "e": 1776, "s": 1613, "text": "callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route)." }, { "code": null, "e": 1939, "s": 1776, "text": "callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route)." }, { "code": null, "e": 2092, "s": 1939, "text": "Create a file with the name \"appUse.js\" and copy the following code snippet. After creating the file, use the command \"node appUse.js\" to run this code." }, { "code": null, "e": 2850, "s": 2092, "text": "// app.use() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// This method will call the next() middleware\napp.use('/api', function (req, res, next) {\n console.log('Time for main function: %d', Date.now())\n next();\n})\n\n// Will be called after the middleware\napp.get('/api', function (req, res) {\n console.log('Time for middleware function: %d', Date.now())\n res.send('Welcome to Tutorials Point')\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});" }, { "code": null, "e": 2901, "s": 2850, "text": "Now, hit the following Endpoint with a GET request" }, { "code": null, "e": 2928, "s": 2901, "text": "http://localhost:3000/api\n" }, { "code": null, "e": 3070, "s": 2928, "text": "C:\\home\\node>> node appUse.js\nServer listening on PORT 3000\nTime for main function: 1627490133904\nTime for middleware function: 1627490133905" }, { "code": null, "e": 3109, "s": 3070, "text": "Let’s take a look at one more example." }, { "code": null, "e": 3844, "s": 3109, "text": "// app.use() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// This method will call the next() middleware\napp.use('/', function (req, res, next) {\n console.log('Middleware will not be called')\n})\n\n// Will be called after the middleware\napp.get('/api', function (req, res) {\n console.log('Time for middleware function: %d', Date.now())\n res.send('Welcome to Tutorials Point')\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});" }, { "code": null, "e": 3895, "s": 3844, "text": "Now, hit the following Endpoint with a GET request" }, { "code": null, "e": 3922, "s": 3895, "text": "http://localhost:3000/api\n" }, { "code": null, "e": 4012, "s": 3922, "text": "C:\\home\\node>> node appUse.js\nServer listening on PORT 3000\nMiddleware will not be called" } ]
Implementation of sleep (system call) in OS - GeeksforGeeks
15 Dec, 2021 In this article, we are going to learn about sleep (system call) in operating systems. In the computer science field, a system call is a mechanism that provides the interface between a process and the operating system. In simple terms, it is basically a method in which a computer program requests a service from the kernel of the operating system. What is sleep in the operating system?Sleep is a computer program and when you call this method, then it sets the process to wait until the specified amount of time proceeds, then goes and finds some other process to run. The sleep system call is used to take a time value as a parameter, specifying the minimum amount of time that the process is to sleep before resuming execution. Syntax – sleep(time); Methods used : sleep() – This method is used to sleep a thread for a specified amount of time. start() – This method is used to create a separate call stack for the thread. run() – This method is used if the thread was constructed using a separate Runnable object. Otherwise this method does nothing and returns. Example 1 – Java class TestSleep extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{Thread.sleep(300);}catch(InterruptedException e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ TestSleep t1=new TestSleep(); TestSleep t2=new TestSleep(); t1.start(); t2.start(); } } Output – Note - In the above example you can notice that at a time only one thread has been executed and if you sleep a thread for thespecified time,the thread shedular picks up another thread and so on. Points to remember while using the Tread.sleep() : Whenever you use this method, it will pause the current thread execution. Interrupted Exception will be thrown when any other thread interrupts when the thread is sleeping. anikaseth98 surindertarika1234 Picked Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Management in Operating System File Allocation Methods Logical and Physical Address in Operating System Difference between Internal and External fragmentation Process Table and Process Control Block (PCB) File Access Methods in Operating System Memory Hierarchy Design and its Characteristics File Systems in Operating System States of a Process in Operating Systems Introduction of Process Management
[ { "code": null, "e": 25737, "s": 25709, "text": "\n15 Dec, 2021" }, { "code": null, "e": 26086, "s": 25737, "text": "In this article, we are going to learn about sleep (system call) in operating systems. In the computer science field, a system call is a mechanism that provides the interface between a process and the operating system. In simple terms, it is basically a method in which a computer program requests a service from the kernel of the operating system." }, { "code": null, "e": 26469, "s": 26086, "text": "What is sleep in the operating system?Sleep is a computer program and when you call this method, then it sets the process to wait until the specified amount of time proceeds, then goes and finds some other process to run. The sleep system call is used to take a time value as a parameter, specifying the minimum amount of time that the process is to sleep before resuming execution." }, { "code": null, "e": 26478, "s": 26469, "text": "Syntax –" }, { "code": null, "e": 26492, "s": 26478, "text": " sleep(time);" }, { "code": null, "e": 26508, "s": 26492, "text": "Methods used : " }, { "code": null, "e": 26589, "s": 26508, "text": "sleep() – This method is used to sleep a thread for a specified amount of time." }, { "code": null, "e": 26667, "s": 26589, "text": "start() – This method is used to create a separate call stack for the thread." }, { "code": null, "e": 26807, "s": 26667, "text": "run() – This method is used if the thread was constructed using a separate Runnable object. Otherwise this method does nothing and returns." }, { "code": null, "e": 26820, "s": 26807, "text": "Example 1 – " }, { "code": null, "e": 26825, "s": 26820, "text": "Java" }, { "code": "class TestSleep extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{Thread.sleep(300);}catch(InterruptedException e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ TestSleep t1=new TestSleep(); TestSleep t2=new TestSleep(); t1.start(); t2.start(); } } ", "e": 27161, "s": 26825, "text": null }, { "code": null, "e": 27170, "s": 27161, "text": "Output –" }, { "code": null, "e": 27381, "s": 27170, "text": "Note - In the above example you can notice that at a time only one thread has been executed and if \n you sleep a thread for thespecified time,the thread shedular picks up another thread and \n so on." }, { "code": null, "e": 27432, "s": 27381, "text": "Points to remember while using the Tread.sleep() :" }, { "code": null, "e": 27506, "s": 27432, "text": "Whenever you use this method, it will pause the current thread execution." }, { "code": null, "e": 27605, "s": 27506, "text": "Interrupted Exception will be thrown when any other thread interrupts when the thread is sleeping." }, { "code": null, "e": 27617, "s": 27605, "text": "anikaseth98" }, { "code": null, "e": 27636, "s": 27617, "text": "surindertarika1234" }, { "code": null, "e": 27643, "s": 27636, "text": "Picked" }, { "code": null, "e": 27661, "s": 27643, "text": "Operating Systems" }, { "code": null, "e": 27679, "s": 27661, "text": "Operating Systems" }, { "code": null, "e": 27777, "s": 27679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27815, "s": 27777, "text": "Memory Management in Operating System" }, { "code": null, "e": 27839, "s": 27815, "text": "File Allocation Methods" }, { "code": null, "e": 27888, "s": 27839, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27943, "s": 27888, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27989, "s": 27943, "text": "Process Table and Process Control Block (PCB)" }, { "code": null, "e": 28029, "s": 27989, "text": "File Access Methods in Operating System" }, { "code": null, "e": 28077, "s": 28029, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 28110, "s": 28077, "text": "File Systems in Operating System" }, { "code": null, "e": 28151, "s": 28110, "text": "States of a Process in Operating Systems" } ]
Matcher quoteReplacement(String) method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods. Syntax: public static String quoteReplacement(String string) Parameters: This method takes a parameter string which is the String to be replaced in the Matcher. Return Value: This method returns a String literal which is the replacement String for the matcher. Below examples illustrate the Matcher.quoteReplacement() method: Example 1: // Java code to illustrate quoteReplacement() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geek"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks Geeks for For Geeks Geek"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "Geeks"; // Get the String literal // using quoteReplacement() method System.out.println( matcher .quoteReplacement(stringToBeReplaced)); }} Geeks Example 2: // Java code to illustrate quoteReplacement() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "FGF"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "GFG"; // Get the String literal // using quoteReplacement() method System.out.println( matcher .quoteReplacement(stringToBeReplaced)); System.out.println( matcher .replaceAll( matcher .quoteReplacement( stringToBeReplaced))); }} GFG GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG Reference: Oracle Doc Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Interfaces in Java Stream In Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Multithreading in Java
[ { "code": null, "e": 25565, "s": 25537, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25854, "s": 25565, "text": "The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods." }, { "code": null, "e": 25862, "s": 25854, "text": "Syntax:" }, { "code": null, "e": 25916, "s": 25862, "text": "public static String quoteReplacement(String string)\n" }, { "code": null, "e": 26016, "s": 25916, "text": "Parameters: This method takes a parameter string which is the String to be replaced in the Matcher." }, { "code": null, "e": 26116, "s": 26016, "text": "Return Value: This method returns a String literal which is the replacement String for the matcher." }, { "code": null, "e": 26181, "s": 26116, "text": "Below examples illustrate the Matcher.quoteReplacement() method:" }, { "code": null, "e": 26192, "s": 26181, "text": "Example 1:" }, { "code": "// Java code to illustrate quoteReplacement() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geek\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks Geeks for For Geeks Geek\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = \"Geeks\"; // Get the String literal // using quoteReplacement() method System.out.println( matcher .quoteReplacement(stringToBeReplaced)); }}", "e": 27047, "s": 26192, "text": null }, { "code": null, "e": 27054, "s": 27047, "text": "Geeks\n" }, { "code": null, "e": 27065, "s": 27054, "text": "Example 2:" }, { "code": "// Java code to illustrate quoteReplacement() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"FGF\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = \"GFG\"; // Get the String literal // using quoteReplacement() method System.out.println( matcher .quoteReplacement(stringToBeReplaced)); System.out.println( matcher .replaceAll( matcher .quoteReplacement( stringToBeReplaced))); }}", "e": 28102, "s": 27065, "text": null }, { "code": null, "e": 28143, "s": 28102, "text": "GFG\nGGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG\n" }, { "code": null, "e": 28165, "s": 28143, "text": "Reference: Oracle Doc" }, { "code": null, "e": 28185, "s": 28165, "text": "Java - util package" }, { "code": null, "e": 28200, "s": 28185, "text": "Java-Functions" }, { "code": null, "e": 28213, "s": 28200, "text": "Java-Matcher" }, { "code": null, "e": 28218, "s": 28213, "text": "Java" }, { "code": null, "e": 28223, "s": 28218, "text": "Java" }, { "code": null, "e": 28321, "s": 28223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28351, "s": 28321, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28370, "s": 28351, "text": "Interfaces in Java" }, { "code": null, "e": 28385, "s": 28370, "text": "Stream In Java" }, { "code": null, "e": 28403, "s": 28385, "text": "ArrayList in Java" }, { "code": null, "e": 28435, "s": 28403, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28455, "s": 28435, "text": "Stack Class in Java" }, { "code": null, "e": 28487, "s": 28455, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28511, "s": 28487, "text": "Singleton Class in Java" }, { "code": null, "e": 28523, "s": 28511, "text": "Set in Java" } ]
Calendar get() method in Java with Examples - GeeksforGeeks
14 Feb, 2019 The get(int field_value) method of Calendar class is used to return the value of the given calendar field in the parameter. Syntax: public int get(int field) Parameters: The method takes one parameter field_value of integer type and refers to the calendar whose value is needed to be returned. Return Value: The method returns the value of the passed field. Below programs illustrate the working of get() Method of Calendar class:Example 1: // Java Code to illustrate// get() Method import java.util.*; public class CalendarClassDemo extends GregorianCalendar { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Getting the value of all // the calendar date fields System.out.println("The given calendar's" + " year is: " + calndr.get(Calendar.YEAR)); System.out.println("The given calendar's" + " month is: " + calndr.get(Calendar.MONTH)); System.out.println("The given calendar's" + " day is: " + calndr.get(Calendar.DATE)); }} The given calendar's year is: 2019 The given calendar's month is: 1 The given calendar's day is: 13 Example 2: // Java Code to illustrate// get() Method import java.util.*; public class CalendarClassDemo extends GregorianCalendar { public static void main(String args[]) { // Creating a calendar object Calendar calndr = new GregorianCalendar(2018, 9, 2); // Getting the value of all // the calendar date fields System.out.println("The given calendar's" + " year is: " + calndr.get(Calendar.YEAR)); System.out.println("The given calendar's" + " month is: " + calndr.get(Calendar.MONTH)); System.out.println("The given calendar's" + " day is: " + calndr.get(Calendar.DATE)); }} The given calendar's year is: 2019 The given calendar's month is: 9 The given calendar's day is: 2 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#get(int) Java-Calendar Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25729, "s": 25701, "text": "\n14 Feb, 2019" }, { "code": null, "e": 25853, "s": 25729, "text": "The get(int field_value) method of Calendar class is used to return the value of the given calendar field in the parameter." }, { "code": null, "e": 25861, "s": 25853, "text": "Syntax:" }, { "code": null, "e": 25887, "s": 25861, "text": "public int get(int field)" }, { "code": null, "e": 26023, "s": 25887, "text": "Parameters: The method takes one parameter field_value of integer type and refers to the calendar whose value is needed to be returned." }, { "code": null, "e": 26087, "s": 26023, "text": "Return Value: The method returns the value of the passed field." }, { "code": null, "e": 26170, "s": 26087, "text": "Below programs illustrate the working of get() Method of Calendar class:Example 1:" }, { "code": "// Java Code to illustrate// get() Method import java.util.*; public class CalendarClassDemo extends GregorianCalendar { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Getting the value of all // the calendar date fields System.out.println(\"The given calendar's\" + \" year is: \" + calndr.get(Calendar.YEAR)); System.out.println(\"The given calendar's\" + \" month is: \" + calndr.get(Calendar.MONTH)); System.out.println(\"The given calendar's\" + \" day is: \" + calndr.get(Calendar.DATE)); }}", "e": 26861, "s": 26170, "text": null }, { "code": null, "e": 26962, "s": 26861, "text": "The given calendar's year is: 2019\nThe given calendar's month is: 1\nThe given calendar's day is: 13\n" }, { "code": null, "e": 26973, "s": 26962, "text": "Example 2:" }, { "code": "// Java Code to illustrate// get() Method import java.util.*; public class CalendarClassDemo extends GregorianCalendar { public static void main(String args[]) { // Creating a calendar object Calendar calndr = new GregorianCalendar(2018, 9, 2); // Getting the value of all // the calendar date fields System.out.println(\"The given calendar's\" + \" year is: \" + calndr.get(Calendar.YEAR)); System.out.println(\"The given calendar's\" + \" month is: \" + calndr.get(Calendar.MONTH)); System.out.println(\"The given calendar's\" + \" day is: \" + calndr.get(Calendar.DATE)); }}", "e": 27682, "s": 26973, "text": null }, { "code": null, "e": 27782, "s": 27682, "text": "The given calendar's year is: 2019\nThe given calendar's month is: 9\nThe given calendar's day is: 2\n" }, { "code": null, "e": 27868, "s": 27782, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#get(int)" }, { "code": null, "e": 27882, "s": 27868, "text": "Java-Calendar" }, { "code": null, "e": 27897, "s": 27882, "text": "Java-Functions" }, { "code": null, "e": 27902, "s": 27897, "text": "Java" }, { "code": null, "e": 27907, "s": 27902, "text": "Java" }, { "code": null, "e": 28005, "s": 27907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28056, "s": 28005, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28086, "s": 28056, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28101, "s": 28086, "text": "Stream In Java" }, { "code": null, "e": 28120, "s": 28101, "text": "Interfaces in Java" }, { "code": null, "e": 28151, "s": 28120, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28169, "s": 28151, "text": "ArrayList in Java" }, { "code": null, "e": 28201, "s": 28169, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28221, "s": 28201, "text": "Stack Class in Java" }, { "code": null, "e": 28253, "s": 28221, "text": "Multidimensional Arrays in Java" } ]
HTTP headers | Pragma - GeeksforGeeks
28 Nov, 2019 The Pragma is a no-cache general-type CORS-safe listed response header field in an HTTP/1.0 header which is intended to use in the request-response chain. A pragma header meant to prevent the client from caching the response, pragma means the browsers to tell the server and any intermediate caches that it wants a fresh version of the resource and vice-versa is not true. Note: Pragma is not specified for HTTP responses that’s why it is not a reliable replacement for the general HTTP/1.1 Cache-Control header. It is used only for backwards compatibility with HTTP/1.0 clients. Difference between Pragma and Cache-control headers: The Pragma is only defined as applicable to the requests by the client, and the Cache-Control may be used by both the requests of the clients and the response of the servers. Syntax Pragma: no-cache Directives: It is same as Cache-Control: no-cache header. It forces the caches to submit the request to the origin server for validation before releasing a cached copy. Example: Pragma: no-cache To check the Pragma in action go to Inspect Element -> Network check the header for Pragma like below. Pragma header is highlighted. Browser Compatibility: The browsers compatible with Pragma header are listed below: Google chrome 6.0 and above Internet Explorer 9.0 and above Firefox 4.0 and above Opera 11.1 and above Safari 5.0 and above Samsung Internet HTTP-headers Picked Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method
[ { "code": null, "e": 25767, "s": 25739, "text": "\n28 Nov, 2019" }, { "code": null, "e": 26140, "s": 25767, "text": "The Pragma is a no-cache general-type CORS-safe listed response header field in an HTTP/1.0 header which is intended to use in the request-response chain. A pragma header meant to prevent the client from caching the response, pragma means the browsers to tell the server and any intermediate caches that it wants a fresh version of the resource and vice-versa is not true." }, { "code": null, "e": 26347, "s": 26140, "text": "Note: Pragma is not specified for HTTP responses that’s why it is not a reliable replacement for the general HTTP/1.1 Cache-Control header. It is used only for backwards compatibility with HTTP/1.0 clients." }, { "code": null, "e": 26575, "s": 26347, "text": "Difference between Pragma and Cache-control headers: The Pragma is only defined as applicable to the requests by the client, and the Cache-Control may be used by both the requests of the clients and the response of the servers." }, { "code": null, "e": 26582, "s": 26575, "text": "Syntax" }, { "code": null, "e": 26599, "s": 26582, "text": "Pragma: no-cache" }, { "code": null, "e": 26768, "s": 26599, "text": "Directives: It is same as Cache-Control: no-cache header. It forces the caches to submit the request to the origin server for validation before releasing a cached copy." }, { "code": null, "e": 26777, "s": 26768, "text": "Example:" }, { "code": null, "e": 26794, "s": 26777, "text": "Pragma: no-cache" }, { "code": null, "e": 26927, "s": 26794, "text": "To check the Pragma in action go to Inspect Element -> Network check the header for Pragma like below. Pragma header is highlighted." }, { "code": null, "e": 27011, "s": 26927, "text": "Browser Compatibility: The browsers compatible with Pragma header are listed below:" }, { "code": null, "e": 27039, "s": 27011, "text": "Google chrome 6.0 and above" }, { "code": null, "e": 27071, "s": 27039, "text": "Internet Explorer 9.0 and above" }, { "code": null, "e": 27093, "s": 27071, "text": "Firefox 4.0 and above" }, { "code": null, "e": 27114, "s": 27093, "text": "Opera 11.1 and above" }, { "code": null, "e": 27135, "s": 27114, "text": "Safari 5.0 and above" }, { "code": null, "e": 27152, "s": 27135, "text": "Samsung Internet" }, { "code": null, "e": 27165, "s": 27152, "text": "HTTP-headers" }, { "code": null, "e": 27172, "s": 27165, "text": "Picked" }, { "code": null, "e": 27191, "s": 27172, "text": "Technical Scripter" }, { "code": null, "e": 27208, "s": 27191, "text": "Web Technologies" }, { "code": null, "e": 27306, "s": 27208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27346, "s": 27306, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27379, "s": 27346, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27424, "s": 27379, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27467, "s": 27424, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27529, "s": 27467, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27579, "s": 27529, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27640, "s": 27579, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27698, "s": 27640, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27770, "s": 27698, "text": "Differences between Functional Components and Class Components in React" } ]
Matcher toMatchResult() method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The toMatchResult() method of Matcher Class is used to get the current result state of this Matcher. Syntax: public MatchResult toMatchResult() Parameters: This method do not takes any parameter. Return Value: This method returns a MatchResult with the current match result state of this Matcher. Below examples illustrate the Matcher.toMatchResult() method: Example 1: // Java code to illustrate toMatchResult() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using toMatchResult() method System.out.println("Result: " + matcher.toMatchResult()); }} Result: java.util.regex.Matcher[pattern=Geeks region=0, 13 lastmatch=] Example 2: // Java code to illustrate toMatchResult() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using toMatchResult() method System.out.println("Result: " + matcher.toMatchResult()); }} Result: java.util.regex.Matcher[pattern=GFG region=0, 19 lastmatch=] Reference: Oracle Doc Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25326, "s": 25225, "text": "The toMatchResult() method of Matcher Class is used to get the current result state of this Matcher." }, { "code": null, "e": 25334, "s": 25326, "text": "Syntax:" }, { "code": null, "e": 25370, "s": 25334, "text": "public MatchResult toMatchResult()\n" }, { "code": null, "e": 25422, "s": 25370, "text": "Parameters: This method do not takes any parameter." }, { "code": null, "e": 25523, "s": 25422, "text": "Return Value: This method returns a MatchResult with the current match result state of this Matcher." }, { "code": null, "e": 25585, "s": 25523, "text": "Below examples illustrate the Matcher.toMatchResult() method:" }, { "code": null, "e": 25596, "s": 25585, "text": "Example 1:" }, { "code": "// Java code to illustrate toMatchResult() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using toMatchResult() method System.out.println(\"Result: \" + matcher.toMatchResult()); }}", "e": 26323, "s": 25596, "text": null }, { "code": null, "e": 26394, "s": 26323, "text": "Result: java.util.regex.Matcher[pattern=Geeks region=0, 13 lastmatch=]" }, { "code": null, "e": 26405, "s": 26394, "text": "Example 2:" }, { "code": "// Java code to illustrate toMatchResult() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using toMatchResult() method System.out.println(\"Result: \" + matcher.toMatchResult()); }}", "e": 27136, "s": 26405, "text": null }, { "code": null, "e": 27205, "s": 27136, "text": "Result: java.util.regex.Matcher[pattern=GFG region=0, 19 lastmatch=]" }, { "code": null, "e": 27227, "s": 27205, "text": "Reference: Oracle Doc" }, { "code": null, "e": 27247, "s": 27227, "text": "Java - util package" }, { "code": null, "e": 27262, "s": 27247, "text": "Java-Functions" }, { "code": null, "e": 27275, "s": 27262, "text": "Java-Matcher" }, { "code": null, "e": 27280, "s": 27275, "text": "Java" }, { "code": null, "e": 27285, "s": 27280, "text": "Java" }, { "code": null, "e": 27383, "s": 27285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27398, "s": 27383, "text": "Stream In Java" }, { "code": null, "e": 27419, "s": 27398, "text": "Constructors in Java" }, { "code": null, "e": 27438, "s": 27419, "text": "Exceptions in Java" }, { "code": null, "e": 27468, "s": 27438, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27514, "s": 27468, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27531, "s": 27514, "text": "Generics in Java" }, { "code": null, "e": 27552, "s": 27531, "text": "Introduction to Java" }, { "code": null, "e": 27595, "s": 27552, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27631, "s": 27595, "text": "Internal Working of HashMap in Java" } ]
jQuery BlockUI Plugin - GeeksforGeeks
10 Jul, 2020 The BlockUI plugin is used to simulate synchronous AJAX behavior. When activated, it stops the user from interacting with the page until it is deactivated. The DOM (Document Object Model) is added with elements to give a nice user-interface look and feel along with behavior. Download Link: <script src="https://malsup.github.io/jquery.blockUI.js"></script> Syntax: For blocking the UI $.blockUI(); For unblocking the UI $.unblockUI(); When we call blockUI without parameters, it displays a “Please wait” message on the screen. We can change the messages by adding parameters to it. To block only an element and not the whole page, we have to make a slightly different call, block and unblock. To get a better understanding, let us see a basic example. Example: <!DOCTYPE html><html> <head> <title>BlockUI</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://malsup.github.io/jquery.blockUI.js"> </script> <style> .btn { background-color: white; color: black; padding: 14px 28px; font-size: 16px; cursor: pointer; margin-bottom: 3rem; } .success { border-color: #4CAF50; color: green; } .success:hover { background-color: #4CAF50; color: white; } </style></head> <body> <button class="btn success" id="blockd"> BlockUI default</button> <br> <button class="btn success" id="blockm"> BlockUI with custom message</button> <br> <button class="btn success" id="blocks"> BlockUI with custom style </button> <div id="blockel"> <button class="btn success" id="blocke"> BlockUI Element Blocking</button> </div> <div id="message" style="display: none;"> <h1>Loading ...</h1> </div> <script> $(document).ready(function () { $("#blockd").click(function () { // Default blockUI code $.blockUI(); setTimeout(function () { // Timer to unblock $.unblockUI(); }, 3000); }); $("#blockm").click(function () { // blockUI code with custom message $.blockUI({ message: $('#message') }); setTimeout(function () { $.unblockUI(); }, 3000); }); $("#blocks").click(function () { $.blockUI({ // blockUI code with custom // message and styling message: "<h3>GeeksForGeeks loading...<h3>", css: { color: 'green', borderColor: 'green' } }); setTimeout(function () { $.unblockUI(); }, 3000); }); $("#blocke").click(function () { $("#blockel").block({ // BlockUI code for element blocking message: "<h3>GeeksForGeeks loading...<h3>", css: { color: 'green', borderColor: 'green' } }); setTimeout(function () { $("#blockel").unblock(); }, 3000); }); }); </script></body> </html> Output: Before BlockUI activated: After BlockUI activated: Default BlockUI: BlockUI with custom message: BlockUI with custom styling: BlockUI Element Blocking: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-UI CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26896, "s": 26868, "text": "\n10 Jul, 2020" }, { "code": null, "e": 27172, "s": 26896, "text": "The BlockUI plugin is used to simulate synchronous AJAX behavior. When activated, it stops the user from interacting with the page until it is deactivated. The DOM (Document Object Model) is added with elements to give a nice user-interface look and feel along with behavior." }, { "code": null, "e": 27187, "s": 27172, "text": "Download Link:" }, { "code": null, "e": 27255, "s": 27187, "text": "<script src=\"https://malsup.github.io/jquery.blockUI.js\"></script>\n" }, { "code": null, "e": 27283, "s": 27255, "text": "Syntax: For blocking the UI" }, { "code": null, "e": 27298, "s": 27283, "text": "$.blockUI(); \n" }, { "code": null, "e": 27320, "s": 27298, "text": "For unblocking the UI" }, { "code": null, "e": 27337, "s": 27320, "text": "$.unblockUI(); \n" }, { "code": null, "e": 27654, "s": 27337, "text": "When we call blockUI without parameters, it displays a “Please wait” message on the screen. We can change the messages by adding parameters to it. To block only an element and not the whole page, we have to make a slightly different call, block and unblock. To get a better understanding, let us see a basic example." }, { "code": null, "e": 27663, "s": 27654, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>BlockUI</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://malsup.github.io/jquery.blockUI.js\"> </script> <style> .btn { background-color: white; color: black; padding: 14px 28px; font-size: 16px; cursor: pointer; margin-bottom: 3rem; } .success { border-color: #4CAF50; color: green; } .success:hover { background-color: #4CAF50; color: white; } </style></head> <body> <button class=\"btn success\" id=\"blockd\"> BlockUI default</button> <br> <button class=\"btn success\" id=\"blockm\"> BlockUI with custom message</button> <br> <button class=\"btn success\" id=\"blocks\"> BlockUI with custom style </button> <div id=\"blockel\"> <button class=\"btn success\" id=\"blocke\"> BlockUI Element Blocking</button> </div> <div id=\"message\" style=\"display: none;\"> <h1>Loading ...</h1> </div> <script> $(document).ready(function () { $(\"#blockd\").click(function () { // Default blockUI code $.blockUI(); setTimeout(function () { // Timer to unblock $.unblockUI(); }, 3000); }); $(\"#blockm\").click(function () { // blockUI code with custom message $.blockUI({ message: $('#message') }); setTimeout(function () { $.unblockUI(); }, 3000); }); $(\"#blocks\").click(function () { $.blockUI({ // blockUI code with custom // message and styling message: \"<h3>GeeksForGeeks loading...<h3>\", css: { color: 'green', borderColor: 'green' } }); setTimeout(function () { $.unblockUI(); }, 3000); }); $(\"#blocke\").click(function () { $(\"#blockel\").block({ // BlockUI code for element blocking message: \"<h3>GeeksForGeeks loading...<h3>\", css: { color: 'green', borderColor: 'green' } }); setTimeout(function () { $(\"#blockel\").unblock(); }, 3000); }); }); </script></body> </html>", "e": 30305, "s": 27663, "text": null }, { "code": null, "e": 30313, "s": 30305, "text": "Output:" }, { "code": null, "e": 30339, "s": 30313, "text": "Before BlockUI activated:" }, { "code": null, "e": 30364, "s": 30339, "text": "After BlockUI activated:" }, { "code": null, "e": 30381, "s": 30364, "text": "Default BlockUI:" }, { "code": null, "e": 30410, "s": 30381, "text": "BlockUI with custom message:" }, { "code": null, "e": 30439, "s": 30410, "text": "BlockUI with custom styling:" }, { "code": null, "e": 30465, "s": 30439, "text": "BlockUI Element Blocking:" }, { "code": null, "e": 30602, "s": 30465, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30612, "s": 30602, "text": "jQuery-UI" }, { "code": null, "e": 30616, "s": 30612, "text": "CSS" }, { "code": null, "e": 30621, "s": 30616, "text": "HTML" }, { "code": null, "e": 30628, "s": 30621, "text": "JQuery" }, { "code": null, "e": 30645, "s": 30628, "text": "Web Technologies" }, { "code": null, "e": 30650, "s": 30645, "text": "HTML" }, { "code": null, "e": 30748, "s": 30650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30785, "s": 30748, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30824, "s": 30785, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30853, "s": 30824, "text": "Form validation using jQuery" }, { "code": null, "e": 30895, "s": 30853, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 30930, "s": 30895, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30990, "s": 30930, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31043, "s": 30990, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31104, "s": 31043, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31128, "s": 31104, "text": "REST API (Introduction)" } ]
fullscreen_window driver method - Selenium Python - GeeksforGeeks
27 Apr, 2021 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around fullscreen_window driver method in Selenium. fullscreen_window method invokes the window manager-specific ‘full screen’ operation.Syntax – driver.fullscreen_window() Example – Now one can use fullscreen_window method as a driver method as below – driver.get("https://www.geeksforgeeks.org/") driver.fullscreen_window() To demonstrate, fullscreen_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.Program – Python3 # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get geeksforgeeks.orgdriver.get("https://www.practice.geeksforgeeks.org/") # full screen windowdriver.fullscreen_window() Output – Browser goes full screen as verified below – simmytarika5 Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Apr, 2021" }, { "code": null, "e": 26446, "s": 25537, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around fullscreen_window driver method in Selenium. fullscreen_window method invokes the window manager-specific ‘full screen’ operation.Syntax – " }, { "code": null, "e": 26473, "s": 26446, "text": "driver.fullscreen_window()" }, { "code": null, "e": 26556, "s": 26473, "text": "Example – Now one can use fullscreen_window method as a driver method as below – " }, { "code": null, "e": 26628, "s": 26556, "text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.fullscreen_window()" }, { "code": null, "e": 26789, "s": 26630, "text": "To demonstrate, fullscreen_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.Program – " }, { "code": null, "e": 26797, "s": 26789, "text": "Python3" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get geeksforgeeks.orgdriver.get(\"https://www.practice.geeksforgeeks.org/\") # full screen windowdriver.fullscreen_window()", "e": 27092, "s": 26797, "text": null }, { "code": null, "e": 27148, "s": 27092, "text": "Output – Browser goes full screen as verified below – " }, { "code": null, "e": 27163, "s": 27150, "text": "simmytarika5" }, { "code": null, "e": 27179, "s": 27163, "text": "Python-selenium" }, { "code": null, "e": 27188, "s": 27179, "text": "selenium" }, { "code": null, "e": 27195, "s": 27188, "text": "Python" }, { "code": null, "e": 27293, "s": 27195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27325, "s": 27293, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27367, "s": 27325, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27409, "s": 27367, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27465, "s": 27409, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27492, "s": 27465, "text": "Python Classes and Objects" }, { "code": null, "e": 27523, "s": 27492, "text": "Python | os.path.join() method" }, { "code": null, "e": 27562, "s": 27523, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27591, "s": 27562, "text": "Create a directory in Python" }, { "code": null, "e": 27613, "s": 27591, "text": "Defaultdict in Python" } ]
PostgreSQL - Drop Procedure - GeeksforGeeks
28 Aug, 2020 In PostgreSQL, the drop procedure statement removes a stored procedure. Syntax: drop procedure [if exists] procedure_name (argument_list) [cascade | restrict] Let’s analyze the above syntax: First, specify the name (procedure_name) of the stored procedure that you want to remove after the drop procedure keywords. Second, use the if exists option if you want PostgreSQL to issue a notice instead of an error if you drop a stored procedure that does not exist. Third, specify the argument list of the stored procedure if the stored procedure’s name is not unique in the database. Note that stored procedures that have different argument lists can share the same name. PostgreSQL needs the argument list to determine which stored procedure that you want to remove. Finally, use the cascade option to drop the stored procedures and its dependent objects and the objects that depend on those objects and so on. The default option is restricted that will reject the removal of the stored procedure in case it has any dependent objects. To drop multiple stored procedures, you specify a comma-list of stored procedure names after the drop procedure keyword like this: Syntax: drop procedure [if exists] name1, name2, ...; For the sake of example, we will create a stored procedure on the sample database ie, dvdrental. Let’s create a couple of stored procedures that manage actors so that you can learn how to drop them: The following insert_actor() stored procedure inserts a new row into the actor table. It accepts two arguments which are the first name and last name of the actor. create or replace procedure insert_actor( fname varchar, lname varchar) language plpgsql as $$ begin insert into actor(first_name, last_name) values('John', 'Doe'); end; $$; The following insert_actor stored procedure also inserts a row into the actor table. However, it accepts one argument which is the full name of the actor. The insert_actor() uses the split_part() function to split the full name into first name and last name before inserting them into the actor table. create or replace procedure insert_actor( full_name varchar ) language plpgsql as $$ declare fname varchar; lname varchar; begin -- split the fullname into first & last name select split_part(full_name, ' ', 1), split_part(full_name, ' ', 2) into fname, lname; -- insert first & last name into the actor table insert into actor(first_name, last_name) values('John', 'Doe'); end; $$; The following stored procedure deletes an actor by id: create or replace procedure delete_actor( p_actor_id int ) language plpgsql as $$ begin delete from actor where actor_id = p_actor_id; end; $$; And the following stored procedure updates the first name and last name of an actor: create or replace procedure update_actor( p_actor_id int, fname varchar, lname varchar ) language plpgsql as $$ begin update actor set first_name = fname, last_name = lname where actor_id = p_actor_id; end; $$; Example: First, attempt to drop the insert_actor stored procedure: drop procedure insert_actor; Output: Because there are two insert_actor stored procedures, you need to specify the argument list so that PostgreSQL can select the right stored procedure to drop. Second, drop the insert_actor(varchar) stored procedure that accepts one argument: drop procedure insert_actor(varchar); Since the insert_actor stored procedure is unique now, you can drop it without specifying the argument list: drop procedure insert_actor; It is the same as: drop procedure insert_actor(varchar, varchar); Third, drop two stored procedures using a single drop procedure statement: drop procedure delete_actor, update_actor; Use the drop procedure statement to remove a stored procedure. Specify a comma-separated list of stored procedure names after the drop procedure keywords to drop multiple stored procedures. If the stored procedure name is not unique, use the argument list to specify which stored procedure you want to drop. postgreSQL-stored-procedures PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - CREATE PROCEDURE PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - TIME Data Type PostgreSQL - REPLACE Function PostgreSQL - CREATE SCHEMA PostgreSQL - SELECT PostgreSQL - ROW_NUMBER Function PostgreSQL - Cursor PostgreSQL - LEFT JOIN
[ { "code": null, "e": 25367, "s": 25339, "text": "\n28 Aug, 2020" }, { "code": null, "e": 25439, "s": 25367, "text": "In PostgreSQL, the drop procedure statement removes a stored procedure." }, { "code": null, "e": 25527, "s": 25439, "text": "Syntax:\ndrop procedure [if exists] procedure_name (argument_list)\n[cascade | restrict]\n" }, { "code": null, "e": 25559, "s": 25527, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 25683, "s": 25559, "text": "First, specify the name (procedure_name) of the stored procedure that you want to remove after the drop procedure keywords." }, { "code": null, "e": 25829, "s": 25683, "text": "Second, use the if exists option if you want PostgreSQL to issue a notice instead of an error if you drop a stored procedure that does not exist." }, { "code": null, "e": 26132, "s": 25829, "text": "Third, specify the argument list of the stored procedure if the stored procedure’s name is not unique in the database. Note that stored procedures that have different argument lists can share the same name. PostgreSQL needs the argument list to determine which stored procedure that you want to remove." }, { "code": null, "e": 26400, "s": 26132, "text": "Finally, use the cascade option to drop the stored procedures and its dependent objects and the objects that depend on those objects and so on. The default option is restricted that will reject the removal of the stored procedure in case it has any dependent objects." }, { "code": null, "e": 26531, "s": 26400, "text": "To drop multiple stored procedures, you specify a comma-list of stored procedure names after the drop procedure keyword like this:" }, { "code": null, "e": 26586, "s": 26531, "text": "Syntax:\ndrop procedure [if exists] name1, name2, ...;\n" }, { "code": null, "e": 26683, "s": 26586, "text": "For the sake of example, we will create a stored procedure on the sample database ie, dvdrental." }, { "code": null, "e": 26785, "s": 26683, "text": "Let’s create a couple of stored procedures that manage actors so that you can learn how to drop them:" }, { "code": null, "e": 26949, "s": 26785, "text": "The following insert_actor() stored procedure inserts a new row into the actor table. It accepts two arguments which are the first name and last name of the actor." }, { "code": null, "e": 27145, "s": 26949, "text": "create or replace procedure insert_actor(\n fname varchar, \n lname varchar)\nlanguage plpgsql \nas $$\nbegin\n insert into actor(first_name, last_name)\n values('John', 'Doe');\nend;\n$$;\n" }, { "code": null, "e": 27447, "s": 27145, "text": "The following insert_actor stored procedure also inserts a row into the actor table. However, it accepts one argument which is the full name of the actor. The insert_actor() uses the split_part() function to split the full name into first name and last name before inserting them into the actor table." }, { "code": null, "e": 27902, "s": 27447, "text": "create or replace procedure insert_actor(\n full_name varchar\n)\nlanguage plpgsql \nas $$\ndeclare\n fname varchar;\n lname varchar;\nbegin\n -- split the fullname into first & last name\n select \n split_part(full_name, ' ', 1),\n split_part(full_name, ' ', 2)\n into fname,\n lname;\n \n -- insert first & last name into the actor table\n insert into actor(first_name, last_name)\n values('John', 'Doe');\nend;\n$$;\n" }, { "code": null, "e": 27957, "s": 27902, "text": "The following stored procedure deletes an actor by id:" }, { "code": null, "e": 28116, "s": 27957, "text": "create or replace procedure delete_actor(\n p_actor_id int\n)\nlanguage plpgsql\nas $$\nbegin\n delete from actor \n where actor_id = p_actor_id;\nend; \n$$;\n" }, { "code": null, "e": 28201, "s": 28116, "text": "And the following stored procedure updates the first name and last name of an actor:" }, { "code": null, "e": 28447, "s": 28201, "text": "create or replace procedure update_actor(\n p_actor_id int,\n fname varchar,\n lname varchar\n)\nlanguage plpgsql\nas $$\nbegin\n update actor \n set first_name = fname,\n last_name = lname\n where actor_id = p_actor_id;\nend; \n$$;\n" }, { "code": null, "e": 28456, "s": 28447, "text": "Example:" }, { "code": null, "e": 28514, "s": 28456, "text": "First, attempt to drop the insert_actor stored procedure:" }, { "code": null, "e": 28544, "s": 28514, "text": "drop procedure insert_actor;\n" }, { "code": null, "e": 28552, "s": 28544, "text": "Output:" }, { "code": null, "e": 28710, "s": 28552, "text": "Because there are two insert_actor stored procedures, you need to specify the argument list so that PostgreSQL can select the right stored procedure to drop." }, { "code": null, "e": 28793, "s": 28710, "text": "Second, drop the insert_actor(varchar) stored procedure that accepts one argument:" }, { "code": null, "e": 28832, "s": 28793, "text": "drop procedure insert_actor(varchar);\n" }, { "code": null, "e": 28941, "s": 28832, "text": "Since the insert_actor stored procedure is unique now, you can drop it without specifying the argument list:" }, { "code": null, "e": 28971, "s": 28941, "text": "drop procedure insert_actor;\n" }, { "code": null, "e": 28990, "s": 28971, "text": "It is the same as:" }, { "code": null, "e": 29038, "s": 28990, "text": "drop procedure insert_actor(varchar, varchar);\n" }, { "code": null, "e": 29113, "s": 29038, "text": "Third, drop two stored procedures using a single drop procedure statement:" }, { "code": null, "e": 29167, "s": 29113, "text": "drop procedure \n delete_actor, \n update_actor;\n" }, { "code": null, "e": 29230, "s": 29167, "text": "Use the drop procedure statement to remove a stored procedure." }, { "code": null, "e": 29357, "s": 29230, "text": "Specify a comma-separated list of stored procedure names after the drop procedure keywords to drop multiple stored procedures." }, { "code": null, "e": 29475, "s": 29357, "text": "If the stored procedure name is not unique, use the argument list to specify which stored procedure you want to drop." }, { "code": null, "e": 29504, "s": 29475, "text": "postgreSQL-stored-procedures" }, { "code": null, "e": 29515, "s": 29504, "text": "PostgreSQL" }, { "code": null, "e": 29613, "s": 29515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29643, "s": 29613, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 29672, "s": 29643, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 29696, "s": 29672, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 29724, "s": 29696, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 29754, "s": 29724, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 29781, "s": 29754, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 29801, "s": 29781, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 29834, "s": 29801, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 29854, "s": 29834, "text": "PostgreSQL - Cursor" } ]
How to close model from a button using vue.js ? - GeeksforGeeks
18 Jan, 2021 This article will tell us about how to close a modal from a button using vue.js. To close a modal using vue.js you can use the click event i.e. @click to trigger change in modal visibility. So, whenever the close button is pressed the @click method will trigger the function associated with the action ( here, hiding the modal ). Add @click=”$emit(‘close’)” property to the close button of the modal. <button type="button" class="close" @click="$emit('close')"> X </button> In the component where modal is used add close modal and open modal properties in data data () { return { isModalVisible: false, }; }, methods: { showModal() { this.isModalVisible = true; }, closeModal() { this.isModalVisible = false; } }, }; Javascript <!--Modal.vue--> <script> export default { name: 'modal', };</script><template> <transition name="modal-fade"> <div class="modal-backdrop"> <div class="modal" role="dialog" > <header class="modal-header" id="modalTitle" > <slot name="header"> Modal Header: GeeksforGeeks <button type="button" class="close" @click="$emit('close')" <!--Added the Click Event--> > X </button> </slot> </header> <section class="modal-body" id="modalDescription" > <slot name="body"> Closing modal using vue.js </slot> </section> </div> </div> </transition></template><style> .modal-backdrop { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(133, 226, 100, 0.427); display: flex; justify-content: center; align-items: center; } .modal { background: #eeeeee; width: 50%; height: 30%; box-shadow: 2px 2px 20px 1px; overflow-x: auto; display: flex; flex-direction: column; } .modal-header{ padding: 15px; display: flex; } .modal-header { border-bottom: 1px solid #eeeeee; font-size: 30px; color: #4AAE9B; justify-content: center; } .modal-body { position: relative; font-size: 30px; align-self: center; padding: 20px 10px; } .close { border: none; font-size: 30px; margin-left: 100px; cursor: pointer; font-weight: bold; color: #4AAE9B; background: transparent; }</style> Javascript <!--App.vue--> <script> import modal from './components/modal.vue'; export default { name: 'app', components: { modal, }, data () { return { isModalVisible: false, }; }, methods: { showModal() { this.isModalVisible = true; }, closeModal() { this.isModalVisible = false; } }, };</script> <template> <div id="app"> <button type="button" class="btn" @click="showModal" > Open Modal </button> <modal v-show="isModalVisible" @close="closeModal" /> </div></template> Picked Technical Scripter 2020 Vue.JS JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n18 Jan, 2021" }, { "code": null, "e": 26875, "s": 26545, "text": "This article will tell us about how to close a modal from a button using vue.js. To close a modal using vue.js you can use the click event i.e. @click to trigger change in modal visibility. So, whenever the close button is pressed the @click method will trigger the function associated with the action ( here, hiding the modal )." }, { "code": null, "e": 26946, "s": 26875, "text": "Add @click=”$emit(‘close’)” property to the close button of the modal." }, { "code": null, "e": 27025, "s": 26946, "text": "<button type=\"button\" class=\"close\" \n @click=\"$emit('close')\"> X \n</button>" }, { "code": null, "e": 27112, "s": 27025, "text": "In the component where modal is used add close modal and open modal properties in data" }, { "code": null, "e": 27329, "s": 27112, "text": "data () {\n return {\n isModalVisible: false,\n };\n },\n methods: {\n showModal() {\n this.isModalVisible = true;\n },\n closeModal() {\n this.isModalVisible = false;\n }\n },\n };" }, { "code": null, "e": 27340, "s": 27329, "text": "Javascript" }, { "code": "<!--Modal.vue--> <script> export default { name: 'modal', };</script><template> <transition name=\"modal-fade\"> <div class=\"modal-backdrop\"> <div class=\"modal\" role=\"dialog\" > <header class=\"modal-header\" id=\"modalTitle\" > <slot name=\"header\"> Modal Header: GeeksforGeeks <button type=\"button\" class=\"close\" @click=\"$emit('close')\" <!--Added the Click Event--> > X </button> </slot> </header> <section class=\"modal-body\" id=\"modalDescription\" > <slot name=\"body\"> Closing modal using vue.js </slot> </section> </div> </div> </transition></template><style> .modal-backdrop { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(133, 226, 100, 0.427); display: flex; justify-content: center; align-items: center; } .modal { background: #eeeeee; width: 50%; height: 30%; box-shadow: 2px 2px 20px 1px; overflow-x: auto; display: flex; flex-direction: column; } .modal-header{ padding: 15px; display: flex; } .modal-header { border-bottom: 1px solid #eeeeee; font-size: 30px; color: #4AAE9B; justify-content: center; } .modal-body { position: relative; font-size: 30px; align-self: center; padding: 20px 10px; } .close { border: none; font-size: 30px; margin-left: 100px; cursor: pointer; font-weight: bold; color: #4AAE9B; background: transparent; }</style>", "e": 29004, "s": 27340, "text": null }, { "code": null, "e": 29015, "s": 29004, "text": "Javascript" }, { "code": "<!--App.vue--> <script> import modal from './components/modal.vue'; export default { name: 'app', components: { modal, }, data () { return { isModalVisible: false, }; }, methods: { showModal() { this.isModalVisible = true; }, closeModal() { this.isModalVisible = false; } }, };</script> <template> <div id=\"app\"> <button type=\"button\" class=\"btn\" @click=\"showModal\" > Open Modal </button> <modal v-show=\"isModalVisible\" @close=\"closeModal\" /> </div></template>", "e": 29609, "s": 29015, "text": null }, { "code": null, "e": 29616, "s": 29609, "text": "Picked" }, { "code": null, "e": 29640, "s": 29616, "text": "Technical Scripter 2020" }, { "code": null, "e": 29647, "s": 29640, "text": "Vue.JS" }, { "code": null, "e": 29658, "s": 29647, "text": "JavaScript" }, { "code": null, "e": 29677, "s": 29658, "text": "Technical Scripter" }, { "code": null, "e": 29694, "s": 29677, "text": "Web Technologies" }, { "code": null, "e": 29792, "s": 29694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29832, "s": 29792, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29893, "s": 29832, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29934, "s": 29893, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29956, "s": 29934, "text": "JavaScript | Promises" }, { "code": null, "e": 30010, "s": 29956, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30050, "s": 30010, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30083, "s": 30050, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30126, "s": 30083, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30176, "s": 30126, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create a TilePane using JavaFX?
Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package. In this layout, the nodes are arranged as a grid of uniformly sized tiles. You can create a tile pane in your application by instantiating the javafx.scene.layout.TilePane class. On instantiating the TilePane class, by default, a horizontal tile pane will be created, you can change its orientation using the setOrientation() method. On instantiating the TilePane class, by default, a horizontal tile pane will be created, you can change its orientation using the setOrientation() method. You can set the maximum with of the pane using the setMaxWidth() method. You can set the maximum with of the pane using the setMaxWidth() method. To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as − getChildren().addAll(); import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Orientation; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.TilePane; import javafx.stage.Stage; public class TilePaneExample extends Application { @Override public void start(Stage stage) { //Creating buttons Button one = new Button("one"); one.setPrefSize(200, 100); Button two = new Button("Two"); two.setPrefSize(200, 100); Button three = new Button("Three"); three.setPrefSize(200, 100); Button four = new Button("Four"); four.setPrefSize(200, 100); Button five = new Button("Five"); five.setPrefSize(200, 100); Button six = new Button("six"); six.setPrefSize(200, 100); Button seven = new Button("seven"); seven.setPrefSize(200, 100); Button eight = new Button("eight"); eight.setPrefSize(200, 100); Button nine = new Button("nine"); nine.setPrefSize(200, 100); //Creating the tile pane TilePane tilePane = new TilePane(); //Setting the orientation for the Tile Pane tilePane.setOrientation(Orientation.HORIZONTAL); //Setting the alignment for the Tile Pane tilePane.setTileAlignment(Pos.CENTER_LEFT); //Setting the preferred columns for the Tile Pane tilePane.setPrefRows(3); //Retrieving the observable list of the Tile Pane ObservableList list = tilePane.getChildren(); //Adding the array of buttons to the pane list.addAll(one, two, three, four, five, six, seven, eight, nine); //Setting the Scene Scene scene = new Scene(tilePane, 600, 300); stage.setTitle("Tile Pane"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1314, "s": 1062, "text": "Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package." }, { "code": null, "e": 1493, "s": 1314, "text": "In this layout, the nodes are arranged as a grid of uniformly sized tiles. You can create a tile pane in your application by instantiating the javafx.scene.layout.TilePane class." }, { "code": null, "e": 1648, "s": 1493, "text": "On instantiating the TilePane class, by default, a horizontal tile pane will be created, you can change its orientation using the setOrientation() method." }, { "code": null, "e": 1803, "s": 1648, "text": "On instantiating the TilePane class, by default, a horizontal tile pane will be created, you can change its orientation using the setOrientation() method." }, { "code": null, "e": 1876, "s": 1803, "text": "You can set the maximum with of the pane using the setMaxWidth() method." }, { "code": null, "e": 1949, "s": 1876, "text": "You can set the maximum with of the pane using the setMaxWidth() method." }, { "code": null, "e": 2085, "s": 1949, "text": "To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −" }, { "code": null, "e": 2109, "s": 2085, "text": "getChildren().addAll();" }, { "code": null, "e": 4000, "s": 2109, "text": "import javafx.application.Application;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Orientation;\nimport javafx.geometry.Pos;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.layout.TilePane;\nimport javafx.stage.Stage;\npublic class TilePaneExample extends Application {\n @Override\n public void start(Stage stage) {\n //Creating buttons\n Button one = new Button(\"one\");\n one.setPrefSize(200, 100);\n Button two = new Button(\"Two\");\n two.setPrefSize(200, 100);\n Button three = new Button(\"Three\");\n three.setPrefSize(200, 100);\n Button four = new Button(\"Four\");\n four.setPrefSize(200, 100);\n Button five = new Button(\"Five\");\n five.setPrefSize(200, 100);\n Button six = new Button(\"six\");\n six.setPrefSize(200, 100);\n Button seven = new Button(\"seven\");\n seven.setPrefSize(200, 100);\n Button eight = new Button(\"eight\");\n eight.setPrefSize(200, 100);\n Button nine = new Button(\"nine\");\n nine.setPrefSize(200, 100);\n //Creating the tile pane\n TilePane tilePane = new TilePane();\n //Setting the orientation for the Tile Pane\n tilePane.setOrientation(Orientation.HORIZONTAL);\n //Setting the alignment for the Tile Pane\n tilePane.setTileAlignment(Pos.CENTER_LEFT);\n //Setting the preferred columns for the Tile Pane\n tilePane.setPrefRows(3);\n //Retrieving the observable list of the Tile Pane\n ObservableList list = tilePane.getChildren();\n //Adding the array of buttons to the pane\n list.addAll(one, two, three, four, five, six, seven, eight, nine);\n //Setting the Scene\n Scene scene = new Scene(tilePane, 600, 300);\n stage.setTitle(\"Tile Pane\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Assembly - STOS Instruction
The STOS instruction copies the data item from AL (for bytes - STOSB), AX (for words - STOSW) or EAX (for doublewords - STOSD) to the destination string, pointed to by ES:DI in memory. The following example demonstrates use of the LODS and STOS instruction to convert an upper case string to its lower case value − section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov ecx, len mov esi, s1 mov edi, s2 loop_here: lodsb or al, 20h stosb loop loop_here cld rep movsb mov edx,20 ;message length mov ecx,s2 ;message to write mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel section .data s1 db 'HELLO, WORLD', 0 ;source len equ $-s1 section .bss s2 resb 20 ;destination When the above code is compiled and executed, it produces the following result − hello, world 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2270, "s": 2085, "text": "The STOS instruction copies the data item from AL (for bytes - STOSB), AX (for words - STOSW) or EAX (for doublewords - STOSD) to the destination string, pointed to by ES:DI in memory." }, { "code": null, "e": 2400, "s": 2270, "text": "The following example demonstrates use of the LODS and STOS instruction to convert an upper case string to its lower case value −" }, { "code": null, "e": 3080, "s": 2400, "text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start:\t ;tell linker entry point\n mov ecx, len\n mov esi, s1\n mov edi, s2\n\t\nloop_here:\n lodsb\n or al, 20h\n stosb\n loop loop_here\t\n cld\n rep\tmovsb\n\t\n mov\tedx,20\t ;message length\n mov\tecx,s2\t ;message to write\n mov\tebx,1\t ;file descriptor (stdout)\n mov\teax,4\t ;system call number (sys_write)\n int\t0x80\t ;call kernel\n\t\n mov\teax,1\t ;system call number (sys_exit)\n int\t0x80\t ;call kernel\n\t\nsection\t.data\ns1 db 'HELLO, WORLD', 0 ;source\nlen equ $-s1\n\nsection\t.bss\ns2 resb 20 ;destination" }, { "code": null, "e": 3161, "s": 3080, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3175, "s": 3161, "text": "hello, world\n" }, { "code": null, "e": 3208, "s": 3175, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 3225, "s": 3208, "text": " Frahaan Hussain" }, { "code": null, "e": 3259, "s": 3225, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 3267, "s": 3259, "text": " Uplatz" }, { "code": null, "e": 3274, "s": 3267, "text": " Print" }, { "code": null, "e": 3285, "s": 3274, "text": " Add Notes" } ]
Nested-if statement in Python - GeeksforGeeks
26 Mar, 2020 There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. This is done with the help of decision-making statements in Python. Example: # Python program to demonstrate# decision making i = 20; if (i < 15): print ("i is smaller than 15") print ("i'm in if Block") else: print ("i is greater than 15") print ("i'm in else Block") print ("i'm not in if and not in else Block") Output: i is greater than 15 i'm in else Block i'm not in if and not in else Block We can have an if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can. Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here FlowChart Example 1: # Python program to demonstrate# nested if statement num = 15if num >= 0: if num == 0: print("Zero") else: print("Positive number")else: print("Negative number") Output: Positive number Example 2: # Python program to demonstrate# nested if statement i = 13 if (i == 13): # First if statement if (i < 15): print ("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print ("i is smaller than 12 too") else: print ("i is greater than 12 and smaller than 15") Output: i is smaller than 15 i is greater than 12 and smaller than 15 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24317, "s": 24289, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24671, "s": 24317, "text": "There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. This is done with the help of decision-making statements in Python." }, { "code": null, "e": 24680, "s": 24671, "text": "Example:" }, { "code": "# Python program to demonstrate# decision making i = 20; if (i < 15): print (\"i is smaller than 15\") print (\"i'm in if Block\") else: print (\"i is greater than 15\") print (\"i'm in else Block\") print (\"i'm not in if and not in else Block\") ", "e": 24936, "s": 24680, "text": null }, { "code": null, "e": 24944, "s": 24936, "text": "Output:" }, { "code": null, "e": 25019, "s": 24944, "text": "i is greater than 15\ni'm in else Block\ni'm not in if and not in else Block" }, { "code": null, "e": 25338, "s": 25019, "text": "We can have an if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can." }, { "code": null, "e": 25346, "s": 25338, "text": "Syntax:" }, { "code": null, "e": 25512, "s": 25346, "text": "if (condition1):\n # Executes when condition1 is true\n if (condition2): \n # Executes when condition2 is true\n # if Block is end here\n# if Block is end here" }, { "code": null, "e": 25522, "s": 25512, "text": "FlowChart" }, { "code": null, "e": 25533, "s": 25522, "text": "Example 1:" }, { "code": "# Python program to demonstrate# nested if statement num = 15if num >= 0: if num == 0: print(\"Zero\") else: print(\"Positive number\")else: print(\"Negative number\")", "e": 25722, "s": 25533, "text": null }, { "code": null, "e": 25730, "s": 25722, "text": "Output:" }, { "code": null, "e": 25747, "s": 25730, "text": "Positive number\n" }, { "code": null, "e": 25758, "s": 25747, "text": "Example 2:" }, { "code": "# Python program to demonstrate# nested if statement i = 13 if (i == 13): # First if statement if (i < 15): print (\"i is smaller than 15\") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print (\"i is smaller than 12 too\") else: print (\"i is greater than 12 and smaller than 15\")", "e": 26149, "s": 25758, "text": null }, { "code": null, "e": 26157, "s": 26149, "text": "Output:" }, { "code": null, "e": 26220, "s": 26157, "text": "i is smaller than 15\ni is greater than 12 and smaller than 15\n" }, { "code": null, "e": 26234, "s": 26220, "text": "python-basics" }, { "code": null, "e": 26241, "s": 26234, "text": "Python" }, { "code": null, "e": 26339, "s": 26241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26371, "s": 26339, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26413, "s": 26371, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26469, "s": 26413, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26511, "s": 26469, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26542, "s": 26511, "text": "Python | os.path.join() method" }, { "code": null, "e": 26597, "s": 26542, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26619, "s": 26597, "text": "Defaultdict in Python" }, { "code": null, "e": 26658, "s": 26619, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26687, "s": 26658, "text": "Create a directory in Python" } ]
Program to find list of all possible combinations of letters of a given string s in Python
Suppose we have a string s. We have to find all possible combinations of letters of s. If there are two strings with same set of characters, then show the lexicographically smallest of them. And one constraint is each character in s are unique. So, if the input is like s = "pqr", then the output will be ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p'] To solve this, we will follow these steps − st_arr := a new list for i in range size of s - 1 to 0, decrease by 1, dofor j in range 0 to size of st_arr - 1, doinsert (s[i] concatenate st_arr[j]) at the end of st_arrinsert s[i] at the end of st_arr for j in range 0 to size of st_arr - 1, doinsert (s[i] concatenate st_arr[j]) at the end of st_arr insert (s[i] concatenate st_arr[j]) at the end of st_arr insert s[i] at the end of st_arr return st_arr Let us see the following implementation to get better understanding − def solve(s): st_arr = [] for i in range(len(s)-1,-1,-1): for j in range(len(st_arr)): st_arr.append(s[i]+st_arr[j]) st_arr.append(s[i]) return st_arr s = "pqr" print(solve(s)) "pqr" ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']
[ { "code": null, "e": 1307, "s": 1062, "text": "Suppose we have a string s. We have to find all possible combinations of letters of s. If there are two strings with same set of characters, then show the lexicographically smallest of them. And one constraint is each character in s are unique." }, { "code": null, "e": 1408, "s": 1307, "text": "So, if the input is like s = \"pqr\", then the output will be ['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']" }, { "code": null, "e": 1452, "s": 1408, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1473, "s": 1452, "text": "st_arr := a new list" }, { "code": null, "e": 1656, "s": 1473, "text": "for i in range size of s - 1 to 0, decrease by 1, dofor j in range 0 to size of st_arr - 1, doinsert (s[i] concatenate st_arr[j]) at the end of st_arrinsert s[i] at the end of st_arr" }, { "code": null, "e": 1755, "s": 1656, "text": "for j in range 0 to size of st_arr - 1, doinsert (s[i] concatenate st_arr[j]) at the end of st_arr" }, { "code": null, "e": 1812, "s": 1755, "text": "insert (s[i] concatenate st_arr[j]) at the end of st_arr" }, { "code": null, "e": 1845, "s": 1812, "text": "insert s[i] at the end of st_arr" }, { "code": null, "e": 1859, "s": 1845, "text": "return st_arr" }, { "code": null, "e": 1929, "s": 1859, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2138, "s": 1929, "text": "def solve(s):\n st_arr = []\n\n for i in range(len(s)-1,-1,-1):\n for j in range(len(st_arr)):\n st_arr.append(s[i]+st_arr[j])\n st_arr.append(s[i])\n return st_arr\n\ns = \"pqr\"\nprint(solve(s))" }, { "code": null, "e": 2145, "s": 2138, "text": "\"pqr\"\n" }, { "code": null, "e": 2186, "s": 2145, "text": "['r', 'qr', 'q', 'pr', 'pqr', 'pq', 'p']" } ]
Elo Rating Algorithm - GeeksforGeeks
20 Mar, 2018 Elo Rating Algorithm is widely used rating algorithm that is used to rank players in many competitive games.Players with higher ELO rating have a higher probability of winning a game than a player with lower ELO rating. After each game, ELO rating of players is updated. If a player with higher ELO rating wins, only a few points are transferred from the lower rated player. However if lower rated player wins, then transferred points from a higher rated player are far greater. Approach:P1: Probability of winning of player with rating2P2: Probability of winning of player with rating1. P1 = (1.0 / (1.0 + pow(10, ((rating1 – rating2) / 400))));P2 = (1.0 / (1.0 + pow(10, ((rating2 – rating1) / 400))));Obviously, P1 + P2 = 1. The rating of player is updated using the formula given below :- rating1 = rating1 + K*(Actual Score – Expected score); In most of the games, “Actual Score” is either 0 or 1 means player either wins or loose. K is a constant. If K is of a lower value, then the rating is changed by a small fraction but if K is of a higher value, then the changes in the rating are significant. Different organizations set a different value of K. Example: Suppose there is a live match on chess.com between two playersrating1 = 1200, rating2 = 1000;P1 = (1.0 / (1.0 + pow(10, ((1000-1200) / 400)))) = 0.76P2 = (1.0 / (1.0 + pow(10, ((1200-1000) / 400)))) = 0.24 And Assume constant K=30; CASE-1 : Suppose Player 1 wins:rating1 = rating1 + k*(actual – expected) = 1200+30(1 – 0.76) = 1207.2;rating2 = rating2 + k*(actual – expected) = 1000+30(0 – 0.24) = 992.8; Case-2 : Suppose Player 2 wins:rating1 = rating1 + k*(actual – expected) = 1200+30(0 – 0.76) = 1177.2;rating2 = rating2 + k*(actual – expected) = 1000+30(1 – 0.24) = 1022.8; CPP Java Python3 C# // CPP program for Elo Rating#include <bits/stdc++.h>using namespace std; // Function to calculate the Probabilityfloat Probability(int rating1, int rating2){ return 1.0 * 1.0 / (1 + 1.0 * pow(10, 1.0 * (rating1 - rating2) / 400));} // Function to calculate Elo rating// K is a constant.// d determines whether Player A wins or Player B. void EloRating(float Ra, float Rb, int K, bool d){ // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == 1) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } cout << "Updated Ratings:-\n"; cout << "Ra = " << Ra << " Rb = " << Rb;} int main(){ // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; bool d = 1; EloRating(Ra, Rb, K, d); return 0;} // Java program to count rotationally // equivalent rectangles with n unit // squaresclass GFG { // Function to calculate the Probability static float Probability(float rating1, float rating2) { return 1.0f * 1.0f / (1 + 1.0f * (float)(Math.pow(10, 1.0f * (rating1 - rating2) / 400))); } // Function to calculate Elo rating // K is a constant. // d determines whether Player A wins // or Player B. static void EloRating(float Ra, float Rb, int K, boolean d) { // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == true) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } System.out.print("Updated Ratings:-\n"); System.out.print("Ra = " + (Math.round( Ra * 1000000.0) / 1000000.0) + " Rb = " + Math.round(Rb * 1000000.0) / 1000000.0); } //driver code public static void main (String[] args) { // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; boolean d = true; EloRating(Ra, Rb, K, d); }} // This code is contributed by Anant Agarwal. # Python 3 program for Elo Ratingimport math # Function to calculate the Probabilitydef Probability(rating1, rating2): return 1.0 * 1.0 / (1 + 1.0 * math.pow(10, 1.0 * (rating1 - rating2) / 400)) # Function to calculate Elo rating# K is a constant.# d determines whether# Player A wins or Player B. def EloRating(Ra, Rb, K, d): # To calculate the Winning # Probability of Player B Pb = Probability(Ra, Rb) # To calculate the Winning # Probability of Player A Pa = Probability(Rb, Ra) # Case -1 When Player A wins # Updating the Elo Ratings if (d == 1) : Ra = Ra + K * (1 - Pa) Rb = Rb + K * (0 - Pb) # Case -2 When Player B wins # Updating the Elo Ratings else : Ra = Ra + K * (0 - Pa) Rb = Rb + K * (1 - Pb) print("Updated Ratings:-") print("Ra =", round(Ra, 6)," Rb =", round(Rb, 6)) # Driver code # Ra and Rb are current ELO ratingsRa = 1200Rb = 1000K = 30d = 1EloRating(Ra, Rb, K, d) # This code is contributed by# Smitha Dinesh Semwal // C# program to count rotationally equivalent// rectangles with n unit squaresusing System; class GFG { // Function to calculate the Probability static float Probability(float rating1, float rating2) { return 1.0f * 1.0f / (1 + 1.0f * (float)(Math.Pow(10, 1.0f * (rating1 - rating2) / 400))); } // Function to calculate Elo rating // K is a constant. // d determines whether Player A wins or // Player B. static void EloRating(float Ra, float Rb, int K, bool d) { // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == true) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } Console.Write("Updated Ratings:-\n"); Console.Write("Ra = " + (Math.Round(Ra * 1000000.0) / 1000000.0) + " Rb = " + Math.Round(Rb * 1000000.0) / 1000000.0); } //driver code public static void Main() { // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; bool d = true; EloRating(Ra, Rb, K, d); }} // This code is contributed by Anant Agarwal. Updated Ratings:- Ra = 1207.207642 Rb = 992.792419 Time ComplexityTime complexity of algorithm depends mostly on the complexity of pow function whosecomplexity is dependent on Computer Architecture.On x86, this is constant time operation:-O(1) Referenceshttp://www.gautamnarula.com/rating/ Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Implementation of LinkedList in Javascript Difference between Min Heap and Max Heap Difference between Class and Object Deploy Python Flask App on Heroku SQL | Functions (Aggregate and Scalar Functions) How compare() method works in Java
[ { "code": null, "e": 24396, "s": 24368, "text": "\n20 Mar, 2018" }, { "code": null, "e": 24875, "s": 24396, "text": "Elo Rating Algorithm is widely used rating algorithm that is used to rank players in many competitive games.Players with higher ELO rating have a higher probability of winning a game than a player with lower ELO rating. After each game, ELO rating of players is updated. If a player with higher ELO rating wins, only a few points are transferred from the lower rated player. However if lower rated player wins, then transferred points from a higher rated player are far greater." }, { "code": null, "e": 24984, "s": 24875, "text": "Approach:P1: Probability of winning of player with rating2P2: Probability of winning of player with rating1." }, { "code": null, "e": 25124, "s": 24984, "text": "P1 = (1.0 / (1.0 + pow(10, ((rating1 – rating2) / 400))));P2 = (1.0 / (1.0 + pow(10, ((rating2 – rating1) / 400))));Obviously, P1 + P2 = 1." }, { "code": null, "e": 25189, "s": 25124, "text": "The rating of player is updated using the formula given below :-" }, { "code": null, "e": 25244, "s": 25189, "text": "rating1 = rating1 + K*(Actual Score – Expected score);" }, { "code": null, "e": 25554, "s": 25244, "text": "In most of the games, “Actual Score” is either 0 or 1 means player either wins or loose. K is a constant. If K is of a lower value, then the rating is changed by a small fraction but if K is of a higher value, then the changes in the rating are significant. Different organizations set a different value of K." }, { "code": null, "e": 25563, "s": 25554, "text": "Example:" }, { "code": null, "e": 25769, "s": 25563, "text": "Suppose there is a live match on chess.com between two playersrating1 = 1200, rating2 = 1000;P1 = (1.0 / (1.0 + pow(10, ((1000-1200) / 400)))) = 0.76P2 = (1.0 / (1.0 + pow(10, ((1200-1000) / 400)))) = 0.24" }, { "code": null, "e": 25795, "s": 25769, "text": "And Assume constant K=30;" }, { "code": null, "e": 25968, "s": 25795, "text": "CASE-1 : Suppose Player 1 wins:rating1 = rating1 + k*(actual – expected) = 1200+30(1 – 0.76) = 1207.2;rating2 = rating2 + k*(actual – expected) = 1000+30(0 – 0.24) = 992.8;" }, { "code": null, "e": 26142, "s": 25968, "text": "Case-2 : Suppose Player 2 wins:rating1 = rating1 + k*(actual – expected) = 1200+30(0 – 0.76) = 1177.2;rating2 = rating2 + k*(actual – expected) = 1000+30(1 – 0.24) = 1022.8;" }, { "code": null, "e": 26146, "s": 26142, "text": "CPP" }, { "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": "// CPP program for Elo Rating#include <bits/stdc++.h>using namespace std; // Function to calculate the Probabilityfloat Probability(int rating1, int rating2){ return 1.0 * 1.0 / (1 + 1.0 * pow(10, 1.0 * (rating1 - rating2) / 400));} // Function to calculate Elo rating// K is a constant.// d determines whether Player A wins or Player B. void EloRating(float Ra, float Rb, int K, bool d){ // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == 1) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } cout << \"Updated Ratings:-\\n\"; cout << \"Ra = \" << Ra << \" Rb = \" << Rb;} int main(){ // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; bool d = 1; EloRating(Ra, Rb, K, d); return 0;}", "e": 27303, "s": 26162, "text": null }, { "code": "// Java program to count rotationally // equivalent rectangles with n unit // squaresclass GFG { // Function to calculate the Probability static float Probability(float rating1, float rating2) { return 1.0f * 1.0f / (1 + 1.0f * (float)(Math.pow(10, 1.0f * (rating1 - rating2) / 400))); } // Function to calculate Elo rating // K is a constant. // d determines whether Player A wins // or Player B. static void EloRating(float Ra, float Rb, int K, boolean d) { // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == true) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } System.out.print(\"Updated Ratings:-\\n\"); System.out.print(\"Ra = \" + (Math.round( Ra * 1000000.0) / 1000000.0) + \" Rb = \" + Math.round(Rb * 1000000.0) / 1000000.0); } //driver code public static void main (String[] args) { // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; boolean d = true; EloRating(Ra, Rb, K, d); }} // This code is contributed by Anant Agarwal.", "e": 29047, "s": 27303, "text": null }, { "code": "# Python 3 program for Elo Ratingimport math # Function to calculate the Probabilitydef Probability(rating1, rating2): return 1.0 * 1.0 / (1 + 1.0 * math.pow(10, 1.0 * (rating1 - rating2) / 400)) # Function to calculate Elo rating# K is a constant.# d determines whether# Player A wins or Player B. def EloRating(Ra, Rb, K, d): # To calculate the Winning # Probability of Player B Pb = Probability(Ra, Rb) # To calculate the Winning # Probability of Player A Pa = Probability(Rb, Ra) # Case -1 When Player A wins # Updating the Elo Ratings if (d == 1) : Ra = Ra + K * (1 - Pa) Rb = Rb + K * (0 - Pb) # Case -2 When Player B wins # Updating the Elo Ratings else : Ra = Ra + K * (0 - Pa) Rb = Rb + K * (1 - Pb) print(\"Updated Ratings:-\") print(\"Ra =\", round(Ra, 6),\" Rb =\", round(Rb, 6)) # Driver code # Ra and Rb are current ELO ratingsRa = 1200Rb = 1000K = 30d = 1EloRating(Ra, Rb, K, d) # This code is contributed by# Smitha Dinesh Semwal", "e": 30094, "s": 29047, "text": null }, { "code": "// C# program to count rotationally equivalent// rectangles with n unit squaresusing System; class GFG { // Function to calculate the Probability static float Probability(float rating1, float rating2) { return 1.0f * 1.0f / (1 + 1.0f * (float)(Math.Pow(10, 1.0f * (rating1 - rating2) / 400))); } // Function to calculate Elo rating // K is a constant. // d determines whether Player A wins or // Player B. static void EloRating(float Ra, float Rb, int K, bool d) { // To calculate the Winning // Probability of Player B float Pb = Probability(Ra, Rb); // To calculate the Winning // Probability of Player A float Pa = Probability(Rb, Ra); // Case -1 When Player A wins // Updating the Elo Ratings if (d == true) { Ra = Ra + K * (1 - Pa); Rb = Rb + K * (0 - Pb); } // Case -2 When Player B wins // Updating the Elo Ratings else { Ra = Ra + K * (0 - Pa); Rb = Rb + K * (1 - Pb); } Console.Write(\"Updated Ratings:-\\n\"); Console.Write(\"Ra = \" + (Math.Round(Ra * 1000000.0) / 1000000.0) + \" Rb = \" + Math.Round(Rb * 1000000.0) / 1000000.0); } //driver code public static void Main() { // Ra and Rb are current ELO ratings float Ra = 1200, Rb = 1000; int K = 30; bool d = true; EloRating(Ra, Rb, K, d); }} // This code is contributed by Anant Agarwal.", "e": 31829, "s": 30094, "text": null }, { "code": null, "e": 31882, "s": 31829, "text": "\nUpdated Ratings:-\nRa = 1207.207642 Rb = 992.792419\n" }, { "code": null, "e": 32075, "s": 31882, "text": "Time ComplexityTime complexity of algorithm depends mostly on the complexity of pow function whosecomplexity is dependent on Computer Architecture.On x86, this is constant time operation:-O(1)" }, { "code": null, "e": 32121, "s": 32075, "text": "Referenceshttp://www.gautamnarula.com/rating/" }, { "code": null, "e": 32130, "s": 32121, "text": "Articles" }, { "code": null, "e": 32228, "s": 32130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32237, "s": 32228, "text": "Comments" }, { "code": null, "e": 32250, "s": 32237, "text": "Old Comments" }, { "code": null, "e": 32287, "s": 32250, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 32313, "s": 32287, "text": "Docker - COPY Instruction" }, { "code": null, "e": 32360, "s": 32313, "text": "Time complexities of different data structures" }, { "code": null, "e": 32381, "s": 32360, "text": "SQL | Date functions" }, { "code": null, "e": 32424, "s": 32381, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 32465, "s": 32424, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 32501, "s": 32465, "text": "Difference between Class and Object" }, { "code": null, "e": 32535, "s": 32501, "text": "Deploy Python Flask App on Heroku" }, { "code": null, "e": 32584, "s": 32535, "text": "SQL | Functions (Aggregate and Scalar Functions)" } ]
Convert birth date to age in Pandas - GeeksforGeeks
02 Feb, 2021 In this article, we are going to convert birthdate into the age in pandas dataframe. We will be using Pandas and datetime package to convert birth date into age. To convert the date of birth to age first we convert the given date to the right format by using strptime() function and then subtract current year with birthdate year and check if the birth month and birth date are greater than a current month and current date if it is true we subtract one else zero is subtracted. Approach: First, we use strptime function to identify the given date format into the date, month, and year. Then we use today function to get today’s date. To get age we subtract the birth year from the current year. This gives age in years but, to calculate accurate age further we check if the birth month and birth date is greater than current month and the current date and if this condition is true we subtract 1 from the final result as even if the current year is passed but yet his birth month or birth date is still yet to arrive. Example 1: In this example, we will convert a single given date to age. Python3 from datetime import datetime, date born='26/01/2000'print("Born :",born) #Identify given date as date month and yearborn = datetime.strptime(born, "%d/%m/%Y").date() #Get today's datetoday = date.today() print("Age :", today.year - born.year - ((today.month, today.day) < (born.month, born.day))) Output: Born : 26/01/2000 Age : 21 Explanation: In the above code, we used datetime package and imported datetime and time. We used strptime function to identify date stored in the born variable i.e. we identified 26/01/2000 as date/month/year. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come. Example 2: Now we will use a dataframe having a column of date of birth and convert it to age and add that column to that dataframe. Python3 import pandas as pdfrom datetime import datetime, date # Creating a list of date of birthdob = {'DOB': ['13/05/1986', '12/12/2018', '23/04/2006']} # Creating dataframedf = pd.DataFrame(data = dob) # This function converts given date to agedef age(born): born = datetime.strptime(born, "%d/%m/%Y").date() today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) df['Age'] = df['DOB'].apply(age) display(df) Output: Explanation: In above code used pandas and datetime package. We created a dataframe of DOB having three rows of different dates. To calculate age we created an age function that uses strptime function to identify the date in date/month/year format. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come. We return age in this function which gets added as a new row inside column ‘Age’. Later we display the data frame. Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas 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 ? Selecting rows in pandas DataFrame based on conditions 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 | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Feb, 2021" }, { "code": null, "e": 24771, "s": 24292, "text": "In this article, we are going to convert birthdate into the age in pandas dataframe. We will be using Pandas and datetime package to convert birth date into age. To convert the date of birth to age first we convert the given date to the right format by using strptime() function and then subtract current year with birthdate year and check if the birth month and birth date are greater than a current month and current date if it is true we subtract one else zero is subtracted." }, { "code": null, "e": 24781, "s": 24771, "text": "Approach:" }, { "code": null, "e": 24879, "s": 24781, "text": "First, we use strptime function to identify the given date format into the date, month, and year." }, { "code": null, "e": 24927, "s": 24879, "text": "Then we use today function to get today’s date." }, { "code": null, "e": 25311, "s": 24927, "text": "To get age we subtract the birth year from the current year. This gives age in years but, to calculate accurate age further we check if the birth month and birth date is greater than current month and the current date and if this condition is true we subtract 1 from the final result as even if the current year is passed but yet his birth month or birth date is still yet to arrive." }, { "code": null, "e": 25383, "s": 25311, "text": "Example 1: In this example, we will convert a single given date to age." }, { "code": null, "e": 25391, "s": 25383, "text": "Python3" }, { "code": "from datetime import datetime, date born='26/01/2000'print(\"Born :\",born) #Identify given date as date month and yearborn = datetime.strptime(born, \"%d/%m/%Y\").date() #Get today's datetoday = date.today() print(\"Age :\", today.year - born.year - ((today.month, today.day) < (born.month, born.day)))", "e": 25794, "s": 25391, "text": null }, { "code": null, "e": 25802, "s": 25794, "text": "Output:" }, { "code": null, "e": 25829, "s": 25802, "text": "Born : 26/01/2000\nAge : 21" }, { "code": null, "e": 26389, "s": 25829, "text": "Explanation: In the above code, we used datetime package and imported datetime and time. We used strptime function to identify date stored in the born variable i.e. we identified 26/01/2000 as date/month/year. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come." }, { "code": null, "e": 26522, "s": 26389, "text": "Example 2: Now we will use a dataframe having a column of date of birth and convert it to age and add that column to that dataframe." }, { "code": null, "e": 26530, "s": 26522, "text": "Python3" }, { "code": "import pandas as pdfrom datetime import datetime, date # Creating a list of date of birthdob = {'DOB': ['13/05/1986', '12/12/2018', '23/04/2006']} # Creating dataframedf = pd.DataFrame(data = dob) # This function converts given date to agedef age(born): born = datetime.strptime(born, \"%d/%m/%Y\").date() today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) df['Age'] = df['DOB'].apply(age) display(df)", "e": 27088, "s": 26530, "text": null }, { "code": null, "e": 27096, "s": 27088, "text": "Output:" }, { "code": null, "e": 27810, "s": 27096, "text": "Explanation: In above code used pandas and datetime package. We created a dataframe of DOB having three rows of different dates. To calculate age we created an age function that uses strptime function to identify the date in date/month/year format. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come. We return age in this function which gets added as a new row inside column ‘Age’. Later we display the data frame." }, { "code": null, "e": 27817, "s": 27810, "text": "Picked" }, { "code": null, "e": 27841, "s": 27817, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27864, "s": 27841, "text": "Python Pandas-exercise" }, { "code": null, "e": 27878, "s": 27864, "text": "Python-pandas" }, { "code": null, "e": 27885, "s": 27878, "text": "Python" }, { "code": null, "e": 27983, "s": 27885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27992, "s": 27983, "text": "Comments" }, { "code": null, "e": 28005, "s": 27992, "text": "Old Comments" }, { "code": null, "e": 28037, "s": 28005, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28092, "s": 28037, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28148, "s": 28092, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28190, "s": 28148, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28232, "s": 28190, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28271, "s": 28232, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28293, "s": 28271, "text": "Defaultdict in Python" }, { "code": null, "e": 28314, "s": 28293, "text": "Python OOPs Concepts" }, { "code": null, "e": 28345, "s": 28314, "text": "Python | os.path.join() method" } ]
Stop Waiting! Start using Async and Await! | by Simon Hawe | Towards Data Science
The most important ingredient for us data scientists is data. How do we get the data we need into our programs? We do that through some I/O-operations like querying a database, loading files from our disk, or downloading data from the web through HTTP requests. These I/O-operations can take quite some time where we just hang around waiting for the data to be accessible. This gets even worse when we have to load multiple files, do multiple database queries, or perform multiple HTTP requests. Most often, we perform these operations sequentially, which leads to executing 100 I/O-operations in total taking 100 times longer than executing a single operation. Now waiting is not only annoying but becomes a real pain. But wait, not too long :), does it make sense to wait for the response to a request before we fire up another completely independent request? Or as a daily life example, when you write an email to two persons, would you wait to send the email to the second person until you’ve received a response from the first one? I guess not. In this article, I want to show you how to significantly reduce waiting time for IO-bound problems using the Asynchronous IO, short AsyncIO, programming paradigm in Python. I will not dive too much into technical details, but rather keep it fairly basic and show you a small code example, which hopefully facilitates your understanding. Assume we want to download three different files from a server. If we do that sequentially, most of the time our CPU is idle waiting for the server to respond. If the response time dominates, the total execution time is given as the sum over the individual response times. Schematically, this looks like shown in Picture 1. I think an idle CPU sounds suboptimal. Wouldn’t it be better to send the requests sequentially, be idle until all those requests have finished and combine all the responses? In that scenario, again assuming the response time to dominate, the total execution time is roughly given as the maximum response time out of all requests. Schematically this is shown in Picture 2. Note that the blue bar just visualizes the time between a request being sent and the response is available. Instead of just having an idle CPU in that timeframe, we should make use of it and perform some work. That’s exactly what we are doing here. When a response from one request arrives we already process it while still waiting for the other responses to arrive. That sounds great, doesn’t it? So how can we write code that makes use of that? As already spoiled in the introduction, we can use AsyncIO to that end. Asynchronous is a higher-level programming paradigm, where you start a task, and while you don’t have the result of that task, you do some other work. With this, AsyncIO gives a feeling of concurrency despite using a single thread in a single process. The magic ingredients to make that work are an event loop, coroutines, and awaitable objects which are coroutine-objects, Tasks, and Futures. Just very briefly An event loop orchestrates the execution and communication of awaitable objects. Without an event loop, we cannot use awaitables, hence, every AsyncIO program has at least one event loop. A native coroutine is a python function defined with async def. You can think of it as a pausible function that can hold state and resume execution from the paused state. You pause a coroutine by calling await on an awaitable. By pausing, it releases the flow of control back to the event loop, which enables other work to be done. When the result of the awaitable is ready, the event loop gives back the flow of control to the coroutine. Calling a coroutine returns a coroutine-object, that must be awaited to get the actual result. Finally, it’s important to remember that you can call await only inside a coroutine. Your root coroutine needs to be scheduled on the event loop by a blocking call. Below you find some very basic code that hopefully facilitates your understanding import asyncioasync def sample_coroutine(): return 1212async def main_coroutine(): coroutine_object = sample_coroutine() # With await, we stop execution, give control back to the # eventloop, and come back when the result of the # coroutine_object is available. result = await coroutine_object assert result == 1212# Blocking call to get the event loop, schedule a task, and close# the event loopasyncio.run(main_coroutine()) If you are interested in more comprehensive introductions, I refer you to this, this, and that. Enough theory, let’s try it out. Prerequisite to use native coroutines is Python 3.5+, however, asyncio is evolving rapidly so I would suggest using the most recent Python version which was 3.7+ at the time of writing. As an example, I download a couple of dog images. For comparison, I do the same operations in both synchronous, and asynchronous fashion. To execute HTTP requests, I use Requests for the synchronous part and AIOHTTP for the async part. I have intentionally left out any kind of error checking to avoid convoluting the code. So let’s first install the necessary modules pip install aiohttp requests Next, I import the modules and add a small helper function import asyncioimport timefrom typing import Any, Iterable, List, Tuple, Callableimport osimport aiohttpimport requestsdef image_name_from_url(url: str) -> str: return url.split("/")[-1] Now, given a bunch of image URLs, we can sequentially download and store them as a List of pairs (image-name, byte array) by def download_all(urls: Iterable[str]) -> List[Tuple[str, bytes]]: def download(url: str) -> Tuple[str, bytes]: print(f"Start downloading {url}") with requests.Session() as s: resp = s.get(url) out= image_name_from_url(url), resp.content print(f"Done downloading {url}") return outreturn [download(url) for url in urls] I have added a few print statements such that you see what happens when executing the function. So far so good, nothing new up until now, but here comes the async version async def donwload_aio(urls:Iterable[str])->List[Tuple[str, bytes]]: async def download(url: str) -> Tuple[str, bytes]: print(f"Start downloading {url}") async with aiohttp.ClientSession() as s: resp = await s.get(url) out = image_name_from_url(url), await resp.read() print(f"Done downloading {url}") return out return await asyncio.gather(*[download(url) for url in urls]) Ah ha, this looks almost identical, apart from all those async and await keywords. Let me explain to you what’s happening here. download_aio is a coroutine as it is defined with async def. It has to be a coroutine because we call other coroutines within it. In the download coroutine, we create a Session object using an async context manager (async with) and await the result of the get request. At this point, we perform the potentially long-lasting HTTP request. Through await we pause execution and give other tasks the chance to work. asyncio.gather is probably the most important part here. It executes a sequence of awaitable objects and returns a list of the gathered results. With this function, you can achieve a feeling of concurrency as shown in Picture 2. You cannot schedule too many coroutines with gather, it’s in the order of a few hundreds. When you run into issues with that, you can still partition the calls into smaller sized chunks that you pass to gather one by one. Like calling a coroutine returning an awaitable, calling gather also returns an awaitable that you have to await to get the results. Let’s put that together, run it, and compare how long it takes to download the doggys. Below you find the code to perform both the synchronous and asynchronous Http calls. if __name__ == "__main__": # Get list of images from dogs API URL = "https://dog.ceo/api/breed/hound/images" images = requests.get(URL).json()["message"]# Take only 200 images to not run into issues with gather reduced = images[:200] st = time.time() images_s = download_all(reduced) print(f"Synchronous exec took {time.time() - st} seconds")st = time.time() images_a = asyncio.run(donwload_aio(reduced)) print(f"Asynchronous exec took {time.time() - st} seconds") In a bit simplified version, the synchronous version prints out Start 1, End 1, Start 2, End 2, ... , Start 200, End 200 which reflects the flow shown in Picture 1. The async counterpart prints out something like Start 1, Start 2, ..., Start 200, End 3, End 1, ..., End 199 which reflects what is shown in Picture 2. Awesome, that is what I have promised you. But I think that alone is not very convincing. So, save the best for last and let’s look at the execution times. To download 200 images on my machine, the synchronous call took 52.7 seconds, while the async one took 6.5 seconds which is about 8 times faster. I like that! The speedup varies based on the maximum download time of an individual item, which depends on the item’s size and the load the server can handle without slowing down. Use AsnycIO for IO-bound problems that you want to accelerate. There are tones of modules for IO-bound operations like Aioredis, Aiokafka, or Aiomysql just to mention a few. For a comprehensive list of higher-level async APIs visit awesome-asyncio. You can only await a coroutine inside a coroutine. You need to schedule your async program or the “root” coroutine by calling asyncio.run in python 3.7+ or asyncio.get_event_loop().run_until_complete in python 3.5–3.6. Last but most important: Don’t wait, await! Hopefully, you’ve learned something new and can reduce waiting time. Thank you for following along and feel free to contact me for questions, comments, or suggestions.
[ { "code": null, "e": 1559, "s": 172, "text": "The most important ingredient for us data scientists is data. How do we get the data we need into our programs? We do that through some I/O-operations like querying a database, loading files from our disk, or downloading data from the web through HTTP requests. These I/O-operations can take quite some time where we just hang around waiting for the data to be accessible. This gets even worse when we have to load multiple files, do multiple database queries, or perform multiple HTTP requests. Most often, we perform these operations sequentially, which leads to executing 100 I/O-operations in total taking 100 times longer than executing a single operation. Now waiting is not only annoying but becomes a real pain. But wait, not too long :), does it make sense to wait for the response to a request before we fire up another completely independent request? Or as a daily life example, when you write an email to two persons, would you wait to send the email to the second person until you’ve received a response from the first one? I guess not. In this article, I want to show you how to significantly reduce waiting time for IO-bound problems using the Asynchronous IO, short AsyncIO, programming paradigm in Python. I will not dive too much into technical details, but rather keep it fairly basic and show you a small code example, which hopefully facilitates your understanding." }, { "code": null, "e": 1883, "s": 1559, "text": "Assume we want to download three different files from a server. If we do that sequentially, most of the time our CPU is idle waiting for the server to respond. If the response time dominates, the total execution time is given as the sum over the individual response times. Schematically, this looks like shown in Picture 1." }, { "code": null, "e": 2255, "s": 1883, "text": "I think an idle CPU sounds suboptimal. Wouldn’t it be better to send the requests sequentially, be idle until all those requests have finished and combine all the responses? In that scenario, again assuming the response time to dominate, the total execution time is roughly given as the maximum response time out of all requests. Schematically this is shown in Picture 2." }, { "code": null, "e": 2774, "s": 2255, "text": "Note that the blue bar just visualizes the time between a request being sent and the response is available. Instead of just having an idle CPU in that timeframe, we should make use of it and perform some work. That’s exactly what we are doing here. When a response from one request arrives we already process it while still waiting for the other responses to arrive. That sounds great, doesn’t it? So how can we write code that makes use of that? As already spoiled in the introduction, we can use AsyncIO to that end." }, { "code": null, "e": 3186, "s": 2774, "text": "Asynchronous is a higher-level programming paradigm, where you start a task, and while you don’t have the result of that task, you do some other work. With this, AsyncIO gives a feeling of concurrency despite using a single thread in a single process. The magic ingredients to make that work are an event loop, coroutines, and awaitable objects which are coroutine-objects, Tasks, and Futures. Just very briefly" }, { "code": null, "e": 3374, "s": 3186, "text": "An event loop orchestrates the execution and communication of awaitable objects. Without an event loop, we cannot use awaitables, hence, every AsyncIO program has at least one event loop." }, { "code": null, "e": 4073, "s": 3374, "text": "A native coroutine is a python function defined with async def. You can think of it as a pausible function that can hold state and resume execution from the paused state. You pause a coroutine by calling await on an awaitable. By pausing, it releases the flow of control back to the event loop, which enables other work to be done. When the result of the awaitable is ready, the event loop gives back the flow of control to the coroutine. Calling a coroutine returns a coroutine-object, that must be awaited to get the actual result. Finally, it’s important to remember that you can call await only inside a coroutine. Your root coroutine needs to be scheduled on the event loop by a blocking call." }, { "code": null, "e": 4155, "s": 4073, "text": "Below you find some very basic code that hopefully facilitates your understanding" }, { "code": null, "e": 4604, "s": 4155, "text": "import asyncioasync def sample_coroutine(): return 1212async def main_coroutine(): coroutine_object = sample_coroutine() # With await, we stop execution, give control back to the # eventloop, and come back when the result of the # coroutine_object is available. result = await coroutine_object assert result == 1212# Blocking call to get the event loop, schedule a task, and close# the event loopasyncio.run(main_coroutine())" }, { "code": null, "e": 4700, "s": 4604, "text": "If you are interested in more comprehensive introductions, I refer you to this, this, and that." }, { "code": null, "e": 5243, "s": 4700, "text": "Enough theory, let’s try it out. Prerequisite to use native coroutines is Python 3.5+, however, asyncio is evolving rapidly so I would suggest using the most recent Python version which was 3.7+ at the time of writing. As an example, I download a couple of dog images. For comparison, I do the same operations in both synchronous, and asynchronous fashion. To execute HTTP requests, I use Requests for the synchronous part and AIOHTTP for the async part. I have intentionally left out any kind of error checking to avoid convoluting the code." }, { "code": null, "e": 5288, "s": 5243, "text": "So let’s first install the necessary modules" }, { "code": null, "e": 5317, "s": 5288, "text": "pip install aiohttp requests" }, { "code": null, "e": 5376, "s": 5317, "text": "Next, I import the modules and add a small helper function" }, { "code": null, "e": 5565, "s": 5376, "text": "import asyncioimport timefrom typing import Any, Iterable, List, Tuple, Callableimport osimport aiohttpimport requestsdef image_name_from_url(url: str) -> str: return url.split(\"/\")[-1]" }, { "code": null, "e": 5690, "s": 5565, "text": "Now, given a bunch of image URLs, we can sequentially download and store them as a List of pairs (image-name, byte array) by" }, { "code": null, "e": 6062, "s": 5690, "text": "def download_all(urls: Iterable[str]) -> List[Tuple[str, bytes]]: def download(url: str) -> Tuple[str, bytes]: print(f\"Start downloading {url}\") with requests.Session() as s: resp = s.get(url) out= image_name_from_url(url), resp.content print(f\"Done downloading {url}\") return outreturn [download(url) for url in urls]" }, { "code": null, "e": 6233, "s": 6062, "text": "I have added a few print statements such that you see what happens when executing the function. So far so good, nothing new up until now, but here comes the async version" }, { "code": null, "e": 6672, "s": 6233, "text": "async def donwload_aio(urls:Iterable[str])->List[Tuple[str, bytes]]: async def download(url: str) -> Tuple[str, bytes]: print(f\"Start downloading {url}\") async with aiohttp.ClientSession() as s: resp = await s.get(url) out = image_name_from_url(url), await resp.read() print(f\"Done downloading {url}\") return out return await asyncio.gather(*[download(url) for url in urls])" }, { "code": null, "e": 6800, "s": 6672, "text": "Ah ha, this looks almost identical, apart from all those async and await keywords. Let me explain to you what’s happening here." }, { "code": null, "e": 6930, "s": 6800, "text": "download_aio is a coroutine as it is defined with async def. It has to be a coroutine because we call other coroutines within it." }, { "code": null, "e": 7212, "s": 6930, "text": "In the download coroutine, we create a Session object using an async context manager (async with) and await the result of the get request. At this point, we perform the potentially long-lasting HTTP request. Through await we pause execution and give other tasks the chance to work." }, { "code": null, "e": 7796, "s": 7212, "text": "asyncio.gather is probably the most important part here. It executes a sequence of awaitable objects and returns a list of the gathered results. With this function, you can achieve a feeling of concurrency as shown in Picture 2. You cannot schedule too many coroutines with gather, it’s in the order of a few hundreds. When you run into issues with that, you can still partition the calls into smaller sized chunks that you pass to gather one by one. Like calling a coroutine returning an awaitable, calling gather also returns an awaitable that you have to await to get the results." }, { "code": null, "e": 7883, "s": 7796, "text": "Let’s put that together, run it, and compare how long it takes to download the doggys." }, { "code": null, "e": 7968, "s": 7883, "text": "Below you find the code to perform both the synchronous and asynchronous Http calls." }, { "code": null, "e": 8465, "s": 7968, "text": "if __name__ == \"__main__\": # Get list of images from dogs API URL = \"https://dog.ceo/api/breed/hound/images\" images = requests.get(URL).json()[\"message\"]# Take only 200 images to not run into issues with gather reduced = images[:200] st = time.time() images_s = download_all(reduced) print(f\"Synchronous exec took {time.time() - st} seconds\")st = time.time() images_a = asyncio.run(donwload_aio(reduced)) print(f\"Asynchronous exec took {time.time() - st} seconds\")" }, { "code": null, "e": 8529, "s": 8465, "text": "In a bit simplified version, the synchronous version prints out" }, { "code": null, "e": 8586, "s": 8529, "text": "Start 1, End 1, Start 2, End 2, ... , Start 200, End 200" }, { "code": null, "e": 8678, "s": 8586, "text": "which reflects the flow shown in Picture 1. The async counterpart prints out something like" }, { "code": null, "e": 8739, "s": 8678, "text": "Start 1, Start 2, ..., Start 200, End 3, End 1, ..., End 199" }, { "code": null, "e": 9264, "s": 8739, "text": "which reflects what is shown in Picture 2. Awesome, that is what I have promised you. But I think that alone is not very convincing. So, save the best for last and let’s look at the execution times. To download 200 images on my machine, the synchronous call took 52.7 seconds, while the async one took 6.5 seconds which is about 8 times faster. I like that! The speedup varies based on the maximum download time of an individual item, which depends on the item’s size and the load the server can handle without slowing down." }, { "code": null, "e": 9513, "s": 9264, "text": "Use AsnycIO for IO-bound problems that you want to accelerate. There are tones of modules for IO-bound operations like Aioredis, Aiokafka, or Aiomysql just to mention a few. For a comprehensive list of higher-level async APIs visit awesome-asyncio." }, { "code": null, "e": 9564, "s": 9513, "text": "You can only await a coroutine inside a coroutine." }, { "code": null, "e": 9732, "s": 9564, "text": "You need to schedule your async program or the “root” coroutine by calling asyncio.run in python 3.7+ or asyncio.get_event_loop().run_until_complete in python 3.5–3.6." }, { "code": null, "e": 9776, "s": 9732, "text": "Last but most important: Don’t wait, await!" } ]
Python 3 - Membership Operators Example
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below − #!/usr/bin/python3 a = 10 b = 20 list = [1, 2, 3, 4, 5 ] if ( a in list ): print ("Line 1 - a is available in the given list") else: print ("Line 1 - a is not available in the given list") if ( b not in list ): print ("Line 2 - b is not available in the given list") else: print ("Line 2 - b is available in the given list") c = b/a if ( c in list ): print ("Line 3 - a is available in the given list") else: print ("Line 3 - a is not available in the given list") When you execute the above program it produces the following result − Line 1 - a is not available in the given list Line 2 - b is not available in the given list Line 3 - a is available in the given list 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2496, "s": 2340, "text": "Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below −" }, { "code": null, "e": 2984, "s": 2496, "text": "#!/usr/bin/python3\n\na = 10\nb = 20\nlist = [1, 2, 3, 4, 5 ]\n\nif ( a in list ):\n print (\"Line 1 - a is available in the given list\")\nelse:\n print (\"Line 1 - a is not available in the given list\")\n\nif ( b not in list ):\n print (\"Line 2 - b is not available in the given list\")\nelse:\n print (\"Line 2 - b is available in the given list\")\n\nc = b/a\nif ( c in list ):\n print (\"Line 3 - a is available in the given list\")\nelse:\n print (\"Line 3 - a is not available in the given list\")\n" }, { "code": null, "e": 3054, "s": 2984, "text": "When you execute the above program it produces the following result −" }, { "code": null, "e": 3189, "s": 3054, "text": "Line 1 - a is not available in the given list\nLine 2 - b is not available in the given list\nLine 3 - a is available in the given list\n" }, { "code": null, "e": 3226, "s": 3189, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3242, "s": 3226, "text": " Malhar Lathkar" }, { "code": null, "e": 3275, "s": 3242, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3294, "s": 3275, "text": " Arnab Chakraborty" }, { "code": null, "e": 3329, "s": 3294, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3351, "s": 3329, "text": " In28Minutes Official" }, { "code": null, "e": 3385, "s": 3351, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3413, "s": 3385, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3448, "s": 3413, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3462, "s": 3448, "text": " Lets Kode It" }, { "code": null, "e": 3495, "s": 3462, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3512, "s": 3495, "text": " Abhilash Nelson" }, { "code": null, "e": 3519, "s": 3512, "text": " Print" }, { "code": null, "e": 3530, "s": 3519, "text": " Add Notes" } ]
Count array elements whose perfect squares are present in the given array - GeeksforGeeks
13 Jan, 2022 Given an array arr[], the task is to find the count of array elements whose squares are already present in the array. Examples: Input: arr[] = {2, 4, 5, 20, 16}Output: 2Explanation:{2, 4} has their squares {4, 16} present in the array. Input: arr[] = {1, 30, 3, 8, 64}Output: 2Explanation:{1, 8} has their squares {1, 64} present in the array. Naive Approach: Follow the steps below to solve the problem: Initialize a variable, say, count, to store the required count. Traverse the array and for each and every array element, perform the following operations:Traverse the array and search if the square of the current element is present in the array.If the square found increment the count. Traverse the array and search if the square of the current element is present in the array. If the square found increment the count. Print count as the answer. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of elements whose// squares are already present int the arrayvoid countSquares(int arr[], int N){ // Stores the required count int count = 0; // Traverse the array for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for (int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count cout << count;} // Driver Codeint main(){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); countSquares(arr, N); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the count of elements whose// squares are already present int the arraystatic void countSquares(int arr[], int N){ // Stores the required count int count = 0; // Traverse the array for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for (int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count System.out.print(count);} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.length; countSquares(arr, N);}} // This code is contributed by shikhasingrajput # Python program for the above approach # Function to find the count of elements whose# squares are already present the arraydef countSquares(arr, N): # Stores the required count count = 0; # Traverse the array for i in range(N): # Square of the element square = arr[i] * arr[i]; # Traverse the array for j in range(N): # Check whether the value # is equal to square if (arr[j] == square): # Increment count count = count + 1; # Print count print(count); # Driver Codeif __name__ == '__main__': # Given array arr = [2, 4, 5, 20, 16]; # Size of the array N = len(arr); countSquares(arr, N); # This code is contributed by shikhasingrajput // C# program of the above approachusing System; class GFG{ // Function to find the count of elements whose// squares are already present int the arraystatic void countSquares(int[] arr, int N){ // Stores the required count int count = 0; // Traverse the array for(int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for(int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count Console.WriteLine(count);} // Driver code static void Main(){ // Given array int[] arr = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.Length; countSquares(arr, N);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function to find the count of elements whose// squares are already present int the arrayfunction countSquares(arr, N){ // Stores the required count var count = 0; // Traverse the array for (var i = 0; i < N; i++) { // Square of the element var square = arr[i] * arr[i]; // Traverse the array for (var j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count document.write( count);} // Driver Code// Given arrayvar arr = [2, 4, 5, 20, 16];// Size of the arrayvar N = arr.length;countSquares(arr, N); </script> 2 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: The optimal idea is to use unordered_map to keep the count of visited elements and update the variable count accordingly. Below are the steps: Initialize a Map to store the frequency of array elements and initialize a variable, say, count. Traverse the array and for each element, increment its count in the Map. Again traverse the array and for each element check for the frequency of the square of the element in the map and add it to the variable count. Print count as the number of elements whose square is already present in the array. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of elements whose// squares is already present int the arrayint countSquares(int arr[], int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements unordered_map<int, int> m; // Traverse the array for (int i = 0; i < N; i++) { m[arr[i]] = m[arr[i]] + 1; } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += m[square]; } // Print the count cout << count;} // Driver Codeint main(){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function Call countSquares(arr, N); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the count of elements whose// squares is already present int the arraystatic void countSquares(int arr[], int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse the array for (int i = 0; i < N; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += mp.containsKey(square)?mp.get(square):0; } // Print the count System.out.print(count);} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.length; // Function Call countSquares(arr, N);}} // This code is contributed by 29AjayKumar # Python 3 program for the above approachfrom collections import defaultdict # Function to find the count of elements whose# squares is already present int the arraydef countSquares( arr, N): # Stores the count of array elements count = 0; # Stores frequency of visited elements m = defaultdict(int); # Traverse the array for i in range(N): m[arr[i]] = m[arr[i]] + 1 for i in range( N ): # Square of the element square = arr[i] * arr[i] # Update the count count += m[square] # Print the count print(count) # Driver Codeif __name__ == "__main__": # Given array arr = [ 2, 4, 5, 20, 16 ] # Size of the array N = len(arr) # Function Call countSquares(arr, N); # This code is contributed by chitranayal. // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the count of elements whose// squares is already present int the arraystatic void countSquares(int []arr, int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse the array for (int i = 0; i < N; i++) { if(mp.ContainsKey(arr[i])) { mp.Add(arr[i], mp[arr[i]] + 1); } else { mp.Add(arr[i], 1); } } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += mp.ContainsKey(square)?mp[square]:0; } // Print the count Console.Write(count);} // Driver Codepublic static void Main(){ // Given array int []arr = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.Length; // Function Call countSquares(arr, N);}} // This code is contributed by Samim Hossain Mondal <script> // Javascript program for the above approach // Function to find the count of elements whose// squares is already present int the arrayfunction countSquares(arr, N){ // Stores the count of array elements var count = 0; // Stores frequency of visited elements var m = new Map(); // Traverse the array for (var i = 0; i < N; i++) { if(m.has(arr[i])) m.set(arr[i], m.get(arr[i])+1) else m.set(arr[i], 1); } for (var i = 0; i < N; i++) { // Square of the element var square = arr[i] * arr[i]; // Update the count if(m.has(square)) count += m.get(square); } // Print the count document.write( count);} // Driver Code// Given arrayvar arr = [2, 4, 5, 20, 16];// Size of the arrayvar N = arr.length;// Function CallcountSquares(arr, N); </script> 2 Time Complexity: O(N)Auxiliary Space: O(N) divyeshrabadiya07 shikhasingrajput 29AjayKumar ukasp itsok famously samim2000 khushboogoyal499 Algorithms-Analysis of Algorithms Arrays cpp-unordered_map Competitive Programming Arrays 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) Graph implementation using STL for competitive programming | Set 2 (Weighted graph) Most important type of Algorithms 5 Best Languages for Competitive Programming 5 Best Books for Competitive Programming Check whether two strings contain same characters in same order
[ { "code": null, "e": 25048, "s": 25020, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25166, "s": 25048, "text": "Given an array arr[], the task is to find the count of array elements whose squares are already present in the array." }, { "code": null, "e": 25176, "s": 25166, "text": "Examples:" }, { "code": null, "e": 25284, "s": 25176, "text": "Input: arr[] = {2, 4, 5, 20, 16}Output: 2Explanation:{2, 4} has their squares {4, 16} present in the array." }, { "code": null, "e": 25392, "s": 25284, "text": "Input: arr[] = {1, 30, 3, 8, 64}Output: 2Explanation:{1, 8} has their squares {1, 64} present in the array." }, { "code": null, "e": 25453, "s": 25392, "text": "Naive Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 25517, "s": 25453, "text": "Initialize a variable, say, count, to store the required count." }, { "code": null, "e": 25739, "s": 25517, "text": "Traverse the array and for each and every array element, perform the following operations:Traverse the array and search if the square of the current element is present in the array.If the square found increment the count." }, { "code": null, "e": 25831, "s": 25739, "text": "Traverse the array and search if the square of the current element is present in the array." }, { "code": null, "e": 25872, "s": 25831, "text": "If the square found increment the count." }, { "code": null, "e": 25899, "s": 25872, "text": "Print count as the answer." }, { "code": null, "e": 25950, "s": 25899, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25956, "s": 25950, "text": "C++14" }, { "code": null, "e": 25961, "s": 25956, "text": "Java" }, { "code": null, "e": 25969, "s": 25961, "text": "Python3" }, { "code": null, "e": 25972, "s": 25969, "text": "C#" }, { "code": null, "e": 25983, "s": 25972, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of elements whose// squares are already present int the arrayvoid countSquares(int arr[], int N){ // Stores the required count int count = 0; // Traverse the array for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for (int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count cout << count;} // Driver Codeint main(){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); countSquares(arr, N); return 0;}", "e": 26872, "s": 25983, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the count of elements whose// squares are already present int the arraystatic void countSquares(int arr[], int N){ // Stores the required count int count = 0; // Traverse the array for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for (int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count System.out.print(count);} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.length; countSquares(arr, N);}} // This code is contributed by shikhasingrajput", "e": 27834, "s": 26872, "text": null }, { "code": "# Python program for the above approach # Function to find the count of elements whose# squares are already present the arraydef countSquares(arr, N): # Stores the required count count = 0; # Traverse the array for i in range(N): # Square of the element square = arr[i] * arr[i]; # Traverse the array for j in range(N): # Check whether the value # is equal to square if (arr[j] == square): # Increment count count = count + 1; # Print count print(count); # Driver Codeif __name__ == '__main__': # Given array arr = [2, 4, 5, 20, 16]; # Size of the array N = len(arr); countSquares(arr, N); # This code is contributed by shikhasingrajput", "e": 28622, "s": 27834, "text": null }, { "code": "// C# program of the above approachusing System; class GFG{ // Function to find the count of elements whose// squares are already present int the arraystatic void countSquares(int[] arr, int N){ // Stores the required count int count = 0; // Traverse the array for(int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Traverse the array for(int j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count Console.WriteLine(count);} // Driver code static void Main(){ // Given array int[] arr = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.Length; countSquares(arr, N);}} // This code is contributed by divyeshrabadiya07", "e": 29625, "s": 28622, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the count of elements whose// squares are already present int the arrayfunction countSquares(arr, N){ // Stores the required count var count = 0; // Traverse the array for (var i = 0; i < N; i++) { // Square of the element var square = arr[i] * arr[i]; // Traverse the array for (var j = 0; j < N; j++) { // Check whether the value // is equal to square if (arr[j] == square) { // Increment count count = count + 1; } } } // Print the count document.write( count);} // Driver Code// Given arrayvar arr = [2, 4, 5, 20, 16];// Size of the arrayvar N = arr.length;countSquares(arr, N); </script>", "e": 30428, "s": 29625, "text": null }, { "code": null, "e": 30430, "s": 30428, "text": "2" }, { "code": null, "e": 30476, "s": 30432, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 30639, "s": 30476, "text": "Efficient Approach: The optimal idea is to use unordered_map to keep the count of visited elements and update the variable count accordingly. Below are the steps:" }, { "code": null, "e": 30736, "s": 30639, "text": "Initialize a Map to store the frequency of array elements and initialize a variable, say, count." }, { "code": null, "e": 30809, "s": 30736, "text": "Traverse the array and for each element, increment its count in the Map." }, { "code": null, "e": 30953, "s": 30809, "text": "Again traverse the array and for each element check for the frequency of the square of the element in the map and add it to the variable count." }, { "code": null, "e": 31037, "s": 30953, "text": "Print count as the number of elements whose square is already present in the array." }, { "code": null, "e": 31089, "s": 31037, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 31095, "s": 31089, "text": "C++14" }, { "code": null, "e": 31100, "s": 31095, "text": "Java" }, { "code": null, "e": 31108, "s": 31100, "text": "Python3" }, { "code": null, "e": 31111, "s": 31108, "text": "C#" }, { "code": null, "e": 31122, "s": 31111, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of elements whose// squares is already present int the arrayint countSquares(int arr[], int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements unordered_map<int, int> m; // Traverse the array for (int i = 0; i < N; i++) { m[arr[i]] = m[arr[i]] + 1; } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += m[square]; } // Print the count cout << count;} // Driver Codeint main(){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function Call countSquares(arr, N); return 0;}", "e": 31975, "s": 31122, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the count of elements whose// squares is already present int the arraystatic void countSquares(int arr[], int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse the array for (int i = 0; i < N; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += mp.containsKey(square)?mp.get(square):0; } // Print the count System.out.print(count);} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.length; // Function Call countSquares(arr, N);}} // This code is contributed by 29AjayKumar", "e": 33072, "s": 31975, "text": null }, { "code": "# Python 3 program for the above approachfrom collections import defaultdict # Function to find the count of elements whose# squares is already present int the arraydef countSquares( arr, N): # Stores the count of array elements count = 0; # Stores frequency of visited elements m = defaultdict(int); # Traverse the array for i in range(N): m[arr[i]] = m[arr[i]] + 1 for i in range( N ): # Square of the element square = arr[i] * arr[i] # Update the count count += m[square] # Print the count print(count) # Driver Codeif __name__ == \"__main__\": # Given array arr = [ 2, 4, 5, 20, 16 ] # Size of the array N = len(arr) # Function Call countSquares(arr, N); # This code is contributed by chitranayal.", "e": 33864, "s": 33072, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the count of elements whose// squares is already present int the arraystatic void countSquares(int []arr, int N){ // Stores the count of array elements int count = 0; // Stores frequency of visited elements Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse the array for (int i = 0; i < N; i++) { if(mp.ContainsKey(arr[i])) { mp.Add(arr[i], mp[arr[i]] + 1); } else { mp.Add(arr[i], 1); } } for (int i = 0; i < N; i++) { // Square of the element int square = arr[i] * arr[i]; // Update the count count += mp.ContainsKey(square)?mp[square]:0; } // Print the count Console.Write(count);} // Driver Codepublic static void Main(){ // Given array int []arr = { 2, 4, 5, 20, 16 }; // Size of the array int N = arr.Length; // Function Call countSquares(arr, N);}} // This code is contributed by Samim Hossain Mondal", "e": 34982, "s": 33864, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the count of elements whose// squares is already present int the arrayfunction countSquares(arr, N){ // Stores the count of array elements var count = 0; // Stores frequency of visited elements var m = new Map(); // Traverse the array for (var i = 0; i < N; i++) { if(m.has(arr[i])) m.set(arr[i], m.get(arr[i])+1) else m.set(arr[i], 1); } for (var i = 0; i < N; i++) { // Square of the element var square = arr[i] * arr[i]; // Update the count if(m.has(square)) count += m.get(square); } // Print the count document.write( count);} // Driver Code// Given arrayvar arr = [2, 4, 5, 20, 16];// Size of the arrayvar N = arr.length;// Function CallcountSquares(arr, N); </script>", "e": 35848, "s": 34982, "text": null }, { "code": null, "e": 35850, "s": 35848, "text": "2" }, { "code": null, "e": 35896, "s": 35852, "text": "Time Complexity: O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 35914, "s": 35896, "text": "divyeshrabadiya07" }, { "code": null, "e": 35931, "s": 35914, "text": "shikhasingrajput" }, { "code": null, "e": 35943, "s": 35931, "text": "29AjayKumar" }, { "code": null, "e": 35949, "s": 35943, "text": "ukasp" }, { "code": null, "e": 35955, "s": 35949, "text": "itsok" }, { "code": null, "e": 35964, "s": 35955, "text": "famously" }, { "code": null, "e": 35974, "s": 35964, "text": "samim2000" }, { "code": null, "e": 35991, "s": 35974, "text": "khushboogoyal499" }, { "code": null, "e": 36025, "s": 35991, "text": "Algorithms-Analysis of Algorithms" }, { "code": null, "e": 36032, "s": 36025, "text": "Arrays" }, { "code": null, "e": 36050, "s": 36032, "text": "cpp-unordered_map" }, { "code": null, "e": 36074, "s": 36050, "text": "Competitive Programming" }, { "code": null, "e": 36081, "s": 36074, "text": "Arrays" }, { "code": null, "e": 36179, "s": 36081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36234, "s": 36179, "text": "Top 15 Websites for Coding Challenges and Competitions" }, { "code": null, "e": 36280, "s": 36234, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 36338, "s": 36280, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 36353, "s": 36338, "text": "Runtime Errors" }, { "code": null, "e": 36386, "s": 36353, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 36470, "s": 36386, "text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)" }, { "code": null, "e": 36504, "s": 36470, "text": "Most important type of Algorithms" }, { "code": null, "e": 36549, "s": 36504, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 36590, "s": 36549, "text": "5 Best Books for Competitive Programming" } ]
Creating a Data Science Python Package Using Jupyter Notebook | by Abid Ali Awan | Towards Data Science
Have you wondered how Python packages like Scikit-learn, pandas, and NumPy are built? They are all based on Object Orient Programming (OOP) to create complex and easy-to-use packages. For a data scientist it's a necessity to learn OOP so they can use it in development of production ready products. We are going to use the cloud Jupyter Notebook to ease the setting up of the environment and completely focus on creating a package. The project includes fundamentals of OOP like Inheritance, objects, class, and magic functions. The project is highly influenced by AWS Machine Learning Foundations course, and it took me ten minutes to recreate the package once I knew how to build it. let’s dive into the coding and discuss our Parent class “Distribution” which will be used by both Gaussian and Binomial classes. We will be using the Jupyter notebook magic function %%witefile to create python files. %%writefile distributions/general.py The code above will create a python file into the distributions folder and to make things simple you need to create a test folder that should contain your test files, a distribution folder that should contain all your package’s files, and a data folder that contains a .txt. The Distribution class takes two arguments, mean and standard deviation, it also contains the read_data_file() function that is used to access data file. __init__ function initiate the variables. Everything in this class is working smoothly. We have added mean, standard deviation, and loaded the random.txt file to test ours Distribution class. The Gaussian distributions is important in statistics and are often used in social sciences to represent real random variables whose distributions are unknown. — Wikipedia The mean of a list of numbers is the sum of all the numbers divided by the number of samples. Mean — Wikipedia This is a measure of variation with in data. The BMJ The parameter mu is the mean, while the parameter sigma is the standard deviation. The x is the value in a list. We are going to inherit values and function from parent class Distribution and use python the magic functions. Initialize the parent class DistributionCreate plot_histogram_pdf function → the normalized histogram of the data and visualize the probability density function.Create magic function __add__ → add together two Gaussian distributions objects.Create magic function __repr__ → output the characteristics of the Gaussian instance. Initialize the parent class Distribution Create plot_histogram_pdf function → the normalized histogram of the data and visualize the probability density function. Create magic function __add__ → add together two Gaussian distributions objects. Create magic function __repr__ → output the characteristics of the Gaussian instance. Testing __repr__ magic function. Initializing gaussian1 object with 25 mean and 2 standard deviations and then reading random.txt file from data folder. Calculating probability function on 25 means and 2 Stdev on data. Then, calculating the mean and Stdev of random.txt. The new mean is 125.1 and Stdev to 210.77 which have changed our probability density function value from 0.19947 to 0.00169. Plotting histogram and line plot of probability density function. The unittest, is a testing framework which was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework, see the Documentation. Test-First is a great tool. It creates better understanding and productivity in the team. The result is high-quality code — both in terms of early success in finding bugs and implementing features correctly. — Gil Zilberfeld We are going to use the unittest library to test all our functions so that in the future if we make any changes, we can detect errors within few seconds. Creating TestGaussianClass that has all the functions to test the functions in Gaussian class. We have used the assertEqual method to hack the validity of functions. I have tested these values myself and then added them individually to test every possibility. Let’s run our test file from the test folder using !python. As you can see all tests have passed. In beginning I got multiple and debugging those issues have helped me better understand how the Gaussian class is working at each level. The binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent experiments, each asking a yes or no question, and each with its own Boolean-valued outcome: success (with probability p) or failure (with probability q = 1 − p). Binomial distribution — Wikipedia We will be using the mathematical functions mention above to create mean, standard deviation, and probability density functions. We have done the challenging work in previous class, now we are going to use similar pattern to code Binomial class. Initialize the probability and size variable → p,nInitialize the parent class Distribution → calculating mean and Stdev and adding it to the parent class.Create replace_stats_with_data function → That will calculate probability, size from imported data. The new mean and standard deviation will be updated.Create plot_bar function → display bar chart using the matplotlib library.Create pdf function → calculate the probability density function of data using mean and stdev.Create plot_bar_pdf function → plot the pdf of the Binomial distribution.Create magic function __add__ → add together with two Binomial distributions objects.Create magic function __repr__ → output the characteristics of the Binomial instance Initialize the probability and size variable → p,n Initialize the parent class Distribution → calculating mean and Stdev and adding it to the parent class. Create replace_stats_with_data function → That will calculate probability, size from imported data. The new mean and standard deviation will be updated. Create plot_bar function → display bar chart using the matplotlib library. Create pdf function → calculate the probability density function of data using mean and stdev. Create plot_bar_pdf function → plot the pdf of the Binomial distribution. Create magic function __add__ → add together with two Binomial distributions objects. Create magic function __repr__ → output the characteristics of the Binomial instance Testing __repr__ magic function Testing Binomial object and read_data_file function. Testing pdf of the initial value of p 0.4 and n 20. We will be using replace_stats_with_data to calculate p and n of data and then recalculating PDF. Testing bar plot Testing Probability Density Function bar plot. We are going to use the unittest library to test all our functions so that in the future if we make any changes, we can detect errors within few seconds. Creating TestBinomialClass which has all the functions to test the Binomial class. Running the test_binomial.py shows that no error was found during testing. We need to create __init__.py file in the distributions folder to initialize the classes within the python file. This will help us call specific classes directly. We have initiated both Binomial and Gaussian class. This setuptools is required for building python package. The setup function requires package information, version, description, author name and email. The image below shows the package directory contain all required files. (venv) [email protected]:~/work # pip install -U . Using pip install . or pip install -U . to install the python package which we can use in any project. As we can see our distribution package is successfully installed. Processing /workBuilding wheels for collected packages: distributions Building wheel for distributions (setup.py) ... done Created wheel for distributions: filename=distributions-0.2-py3-none-any.whl size=4800 sha256=39bc76cbf407b2870caea42b684b05efc15641c0583f195f36a315b3bc4476da Stored in directory: /tmp/pip-ephem-wheel-cache-ef8q6wh9/wheels/95/55/fb/4ee852231f420991169c6c5d3eb5b02c36aea6b6f444965b4bSuccessfully built distributionsInstalling collected packages: distributions Attempting uninstall: distributions Found existing installation: distributions 0.2 Uninstalling distributions-0.2: Successfully uninstalled distributions-0.2Successfully installed distributions-0.2 We will be running Python kernel within Linius terminal and then test both classes. Well done you have created your first Python package. >>> from distributions import Gaussian>>> from distributions import Binomial>>> >>> print(Gaussian(20,6))mean 20, standard deviation 6>>> print(Binomial(0.4,50))mean 20.0, standard deviation 3.4641016151377544, p 0.4, n 50>>> github.com If you are still facing problems, check out my GitHub repo or Deepnote project. You can follow me on LinkedIn and Polywork where I publish articles every week. The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion. Originally published at https://www.analyticsvidhya.com on July 30, 2021.
[ { "code": null, "e": 471, "s": 172, "text": "Have you wondered how Python packages like Scikit-learn, pandas, and NumPy are built? They are all based on Object Orient Programming (OOP) to create complex and easy-to-use packages. For a data scientist it's a necessity to learn OOP so they can use it in development of production ready products." }, { "code": null, "e": 857, "s": 471, "text": "We are going to use the cloud Jupyter Notebook to ease the setting up of the environment and completely focus on creating a package. The project includes fundamentals of OOP like Inheritance, objects, class, and magic functions. The project is highly influenced by AWS Machine Learning Foundations course, and it took me ten minutes to recreate the package once I knew how to build it." }, { "code": null, "e": 1074, "s": 857, "text": "let’s dive into the coding and discuss our Parent class “Distribution” which will be used by both Gaussian and Binomial classes. We will be using the Jupyter notebook magic function %%witefile to create python files." }, { "code": null, "e": 1111, "s": 1074, "text": "%%writefile distributions/general.py" }, { "code": null, "e": 1386, "s": 1111, "text": "The code above will create a python file into the distributions folder and to make things simple you need to create a test folder that should contain your test files, a distribution folder that should contain all your package’s files, and a data folder that contains a .txt." }, { "code": null, "e": 1540, "s": 1386, "text": "The Distribution class takes two arguments, mean and standard deviation, it also contains the read_data_file() function that is used to access data file." }, { "code": null, "e": 1582, "s": 1540, "text": "__init__ function initiate the variables." }, { "code": null, "e": 1732, "s": 1582, "text": "Everything in this class is working smoothly. We have added mean, standard deviation, and loaded the random.txt file to test ours Distribution class." }, { "code": null, "e": 1904, "s": 1732, "text": "The Gaussian distributions is important in statistics and are often used in social sciences to represent real random variables whose distributions are unknown. — Wikipedia" }, { "code": null, "e": 2015, "s": 1904, "text": "The mean of a list of numbers is the sum of all the numbers divided by the number of samples. Mean — Wikipedia" }, { "code": null, "e": 2068, "s": 2015, "text": "This is a measure of variation with in data. The BMJ" }, { "code": null, "e": 2181, "s": 2068, "text": "The parameter mu is the mean, while the parameter sigma is the standard deviation. The x is the value in a list." }, { "code": null, "e": 2292, "s": 2181, "text": "We are going to inherit values and function from parent class Distribution and use python the magic functions." }, { "code": null, "e": 2619, "s": 2292, "text": "Initialize the parent class DistributionCreate plot_histogram_pdf function → the normalized histogram of the data and visualize the probability density function.Create magic function __add__ → add together two Gaussian distributions objects.Create magic function __repr__ → output the characteristics of the Gaussian instance." }, { "code": null, "e": 2660, "s": 2619, "text": "Initialize the parent class Distribution" }, { "code": null, "e": 2782, "s": 2660, "text": "Create plot_histogram_pdf function → the normalized histogram of the data and visualize the probability density function." }, { "code": null, "e": 2863, "s": 2782, "text": "Create magic function __add__ → add together two Gaussian distributions objects." }, { "code": null, "e": 2949, "s": 2863, "text": "Create magic function __repr__ → output the characteristics of the Gaussian instance." }, { "code": null, "e": 2982, "s": 2949, "text": "Testing __repr__ magic function." }, { "code": null, "e": 3102, "s": 2982, "text": "Initializing gaussian1 object with 25 mean and 2 standard deviations and then reading random.txt file from data folder." }, { "code": null, "e": 3345, "s": 3102, "text": "Calculating probability function on 25 means and 2 Stdev on data. Then, calculating the mean and Stdev of random.txt. The new mean is 125.1 and Stdev to 210.77 which have changed our probability density function value from 0.19947 to 0.00169." }, { "code": null, "e": 3411, "s": 3345, "text": "Plotting histogram and line plot of probability density function." }, { "code": null, "e": 3762, "s": 3411, "text": "The unittest, is a testing framework which was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework, see the Documentation." }, { "code": null, "e": 3987, "s": 3762, "text": "Test-First is a great tool. It creates better understanding and productivity in the team. The result is high-quality code — both in terms of early success in finding bugs and implementing features correctly. — Gil Zilberfeld" }, { "code": null, "e": 4141, "s": 3987, "text": "We are going to use the unittest library to test all our functions so that in the future if we make any changes, we can detect errors within few seconds." }, { "code": null, "e": 4307, "s": 4141, "text": "Creating TestGaussianClass that has all the functions to test the functions in Gaussian class. We have used the assertEqual method to hack the validity of functions." }, { "code": null, "e": 4401, "s": 4307, "text": "I have tested these values myself and then added them individually to test every possibility." }, { "code": null, "e": 4461, "s": 4401, "text": "Let’s run our test file from the test folder using !python." }, { "code": null, "e": 4636, "s": 4461, "text": "As you can see all tests have passed. In beginning I got multiple and debugging those issues have helped me better understand how the Gaussian class is working at each level." }, { "code": null, "e": 4982, "s": 4636, "text": "The binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent experiments, each asking a yes or no question, and each with its own Boolean-valued outcome: success (with probability p) or failure (with probability q = 1 − p). Binomial distribution — Wikipedia" }, { "code": null, "e": 5228, "s": 4982, "text": "We will be using the mathematical functions mention above to create mean, standard deviation, and probability density functions. We have done the challenging work in previous class, now we are going to use similar pattern to code Binomial class." }, { "code": null, "e": 5945, "s": 5228, "text": "Initialize the probability and size variable → p,nInitialize the parent class Distribution → calculating mean and Stdev and adding it to the parent class.Create replace_stats_with_data function → That will calculate probability, size from imported data. The new mean and standard deviation will be updated.Create plot_bar function → display bar chart using the matplotlib library.Create pdf function → calculate the probability density function of data using mean and stdev.Create plot_bar_pdf function → plot the pdf of the Binomial distribution.Create magic function __add__ → add together with two Binomial distributions objects.Create magic function __repr__ → output the characteristics of the Binomial instance" }, { "code": null, "e": 5996, "s": 5945, "text": "Initialize the probability and size variable → p,n" }, { "code": null, "e": 6101, "s": 5996, "text": "Initialize the parent class Distribution → calculating mean and Stdev and adding it to the parent class." }, { "code": null, "e": 6254, "s": 6101, "text": "Create replace_stats_with_data function → That will calculate probability, size from imported data. The new mean and standard deviation will be updated." }, { "code": null, "e": 6329, "s": 6254, "text": "Create plot_bar function → display bar chart using the matplotlib library." }, { "code": null, "e": 6424, "s": 6329, "text": "Create pdf function → calculate the probability density function of data using mean and stdev." }, { "code": null, "e": 6498, "s": 6424, "text": "Create plot_bar_pdf function → plot the pdf of the Binomial distribution." }, { "code": null, "e": 6584, "s": 6498, "text": "Create magic function __add__ → add together with two Binomial distributions objects." }, { "code": null, "e": 6669, "s": 6584, "text": "Create magic function __repr__ → output the characteristics of the Binomial instance" }, { "code": null, "e": 6701, "s": 6669, "text": "Testing __repr__ magic function" }, { "code": null, "e": 6754, "s": 6701, "text": "Testing Binomial object and read_data_file function." }, { "code": null, "e": 6904, "s": 6754, "text": "Testing pdf of the initial value of p 0.4 and n 20. We will be using replace_stats_with_data to calculate p and n of data and then recalculating PDF." }, { "code": null, "e": 6921, "s": 6904, "text": "Testing bar plot" }, { "code": null, "e": 6968, "s": 6921, "text": "Testing Probability Density Function bar plot." }, { "code": null, "e": 7122, "s": 6968, "text": "We are going to use the unittest library to test all our functions so that in the future if we make any changes, we can detect errors within few seconds." }, { "code": null, "e": 7205, "s": 7122, "text": "Creating TestBinomialClass which has all the functions to test the Binomial class." }, { "code": null, "e": 7280, "s": 7205, "text": "Running the test_binomial.py shows that no error was found during testing." }, { "code": null, "e": 7443, "s": 7280, "text": "We need to create __init__.py file in the distributions folder to initialize the classes within the python file. This will help us call specific classes directly." }, { "code": null, "e": 7495, "s": 7443, "text": "We have initiated both Binomial and Gaussian class." }, { "code": null, "e": 7646, "s": 7495, "text": "This setuptools is required for building python package. The setup function requires package information, version, description, author name and email." }, { "code": null, "e": 7718, "s": 7646, "text": "The image below shows the package directory contain all required files." }, { "code": null, "e": 7769, "s": 7718, "text": "(venv) [email protected]:~/work # pip install -U ." }, { "code": null, "e": 7938, "s": 7769, "text": "Using pip install . or pip install -U . to install the python package which we can use in any project. As we can see our distribution package is successfully installed." }, { "code": null, "e": 8633, "s": 7938, "text": "Processing /workBuilding wheels for collected packages: distributions Building wheel for distributions (setup.py) ... done Created wheel for distributions: filename=distributions-0.2-py3-none-any.whl size=4800 sha256=39bc76cbf407b2870caea42b684b05efc15641c0583f195f36a315b3bc4476da Stored in directory: /tmp/pip-ephem-wheel-cache-ef8q6wh9/wheels/95/55/fb/4ee852231f420991169c6c5d3eb5b02c36aea6b6f444965b4bSuccessfully built distributionsInstalling collected packages: distributions Attempting uninstall: distributions Found existing installation: distributions 0.2 Uninstalling distributions-0.2: Successfully uninstalled distributions-0.2Successfully installed distributions-0.2" }, { "code": null, "e": 8717, "s": 8633, "text": "We will be running Python kernel within Linius terminal and then test both classes." }, { "code": null, "e": 8771, "s": 8717, "text": "Well done you have created your first Python package." }, { "code": null, "e": 8997, "s": 8771, "text": ">>> from distributions import Gaussian>>> from distributions import Binomial>>> >>> print(Gaussian(20,6))mean 20, standard deviation 6>>> print(Binomial(0.4,50))mean 20.0, standard deviation 3.4641016151377544, p 0.4, n 50>>>" }, { "code": null, "e": 9008, "s": 8997, "text": "github.com" }, { "code": null, "e": 9088, "s": 9008, "text": "If you are still facing problems, check out my GitHub repo or Deepnote project." }, { "code": null, "e": 9168, "s": 9088, "text": "You can follow me on LinkedIn and Polywork where I publish articles every week." }, { "code": null, "e": 9275, "s": 9168, "text": "The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion." } ]
Tracking Keyword Trends on Google Search with Pytrends | by Sidney Kung | Towards Data Science
Pytrends is an unofficial API for tracking Google Search trends, and we can use matplotlib to visualize these trends over time. You can read more about the package in the project’s GitHub repository here. Well, we all know what Google Search is. We all use it several times a day, sometimes without a second thought, to access millions of search results for a wide range of topics. Fun fact, the Google Search Toolbar was first released in 2000 for Internet Explorer 5! By looking at a time series visualization of Google Search keywords over a decade, we can draw valuable insights about almost any topic. Let’s dive right into an example. Let’s take a look at the trends for the keyword “Data Science”. Here are the trends of the keyword “Data Science” from 2016 to 2021. I’ll share a tutorial on how you can generate this visualization too! It’s super easy. With any package, we start with installing it onto the local machine. You can do this with a simple line. ! pip install pytrends Once pytrends is installed, we are going to import the method TrendReq from the package. from pytrends.request import TrendReq Next, we need to connect to Google. We can use TrendReq and pass several parameters. For this example, we’ll use hl and tz. # connect to googlepytrends = TrendReq(hl='en-US', tz=360) The hl parameter specifies host language for accessing Google Trends. Please note that only https proxies will work, and you need to add the port number after the proxy ip address. The tz parameter is the timezone offset. So, for example, US CST is 360. After the API has been initialized, we need to query the actual keyword term that we want to search for. To do that, we use the method build_payload to tell the API which keywords we want. As mentioned, we’re using “Data Science” for this example. # keywords to search forpytrends.build_payload(kw_list=['data science']) Now the hard part is over! Next, we just need to create a dataframe that holds the time series data for this query. There is an API method, Interest over Time, that returns historical, indexed data for when the keyword was searched most as shown on Google Trends’ Interest Over Time section. # dataframetime_df = pytrends.interest_over_time() Take a look at what the first 5 rows of that dataframe looks like by running a simple time_df.head(). Once everything has been set up, we can use matplotlib to visualize this dataframe! I won’t explain that part, but here is the full code that I used for this project. As you can see, the whole project only took about 22 lines of code to accomplish. This mini exercise was just one of the many things that we can do with the pytrends package. For instance, we can look at the historical hourly interest, interest by region, related topics, related queries, and even more. Feel free to install Pytrends and play around with the package yourself! There are an endless amount of terms to search.
[ { "code": null, "e": 377, "s": 172, "text": "Pytrends is an unofficial API for tracking Google Search trends, and we can use matplotlib to visualize these trends over time. You can read more about the package in the project’s GitHub repository here." }, { "code": null, "e": 642, "s": 377, "text": "Well, we all know what Google Search is. We all use it several times a day, sometimes without a second thought, to access millions of search results for a wide range of topics. Fun fact, the Google Search Toolbar was first released in 2000 for Internet Explorer 5!" }, { "code": null, "e": 877, "s": 642, "text": "By looking at a time series visualization of Google Search keywords over a decade, we can draw valuable insights about almost any topic. Let’s dive right into an example. Let’s take a look at the trends for the keyword “Data Science”." }, { "code": null, "e": 1033, "s": 877, "text": "Here are the trends of the keyword “Data Science” from 2016 to 2021. I’ll share a tutorial on how you can generate this visualization too! It’s super easy." }, { "code": null, "e": 1139, "s": 1033, "text": "With any package, we start with installing it onto the local machine. You can do this with a simple line." }, { "code": null, "e": 1162, "s": 1139, "text": "! pip install pytrends" }, { "code": null, "e": 1251, "s": 1162, "text": "Once pytrends is installed, we are going to import the method TrendReq from the package." }, { "code": null, "e": 1289, "s": 1251, "text": "from pytrends.request import TrendReq" }, { "code": null, "e": 1413, "s": 1289, "text": "Next, we need to connect to Google. We can use TrendReq and pass several parameters. For this example, we’ll use hl and tz." }, { "code": null, "e": 1472, "s": 1413, "text": "# connect to googlepytrends = TrendReq(hl='en-US', tz=360)" }, { "code": null, "e": 1726, "s": 1472, "text": "The hl parameter specifies host language for accessing Google Trends. Please note that only https proxies will work, and you need to add the port number after the proxy ip address. The tz parameter is the timezone offset. So, for example, US CST is 360." }, { "code": null, "e": 1974, "s": 1726, "text": "After the API has been initialized, we need to query the actual keyword term that we want to search for. To do that, we use the method build_payload to tell the API which keywords we want. As mentioned, we’re using “Data Science” for this example." }, { "code": null, "e": 2047, "s": 1974, "text": "# keywords to search forpytrends.build_payload(kw_list=['data science'])" }, { "code": null, "e": 2339, "s": 2047, "text": "Now the hard part is over! Next, we just need to create a dataframe that holds the time series data for this query. There is an API method, Interest over Time, that returns historical, indexed data for when the keyword was searched most as shown on Google Trends’ Interest Over Time section." }, { "code": null, "e": 2390, "s": 2339, "text": "# dataframetime_df = pytrends.interest_over_time()" }, { "code": null, "e": 2492, "s": 2390, "text": "Take a look at what the first 5 rows of that dataframe looks like by running a simple time_df.head()." }, { "code": null, "e": 2741, "s": 2492, "text": "Once everything has been set up, we can use matplotlib to visualize this dataframe! I won’t explain that part, but here is the full code that I used for this project. As you can see, the whole project only took about 22 lines of code to accomplish." }, { "code": null, "e": 2963, "s": 2741, "text": "This mini exercise was just one of the many things that we can do with the pytrends package. For instance, we can look at the historical hourly interest, interest by region, related topics, related queries, and even more." } ]
PHP Array Sort Techniques | sort() rsort() asort() arsort() ksort() krsort() TutorialsPoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In the previous tutorials, we have discussed how to create an array in php and different types of arrays in php. Now, in this tutorials we are going to learn different types of php array sort techniques. Sorting arrays provides a way to organize data sets in either alphabetical order or in numbers, in an ascending or descending manner. PHP provides many predefined functions to sort an array. Here are the list. sort() – It will sort an given array in ascending order. rsort() – It will sort an given arrays in descending order asort() – It will sort an given associative array in ascending order, according to the value ksort() – It will sort an given associative array in ascending order, according to the key arsort() – It will sort an given associative array in descending order, according to the value krsort() – It will sort an given associative array in descending order, according to the key The sort() is a default method given by PHP. It is used to sort the given array in ascending order. <?php $marks[0] = "English"; $marks[1] = "Math"; $marks[2] = "Geography"; $marks[3] = "Science"; echo "Cara loves to study. " . $marks[0] . " and " . $marks[1] . " are her favorite subjects</br>"; echo "She studies a total of " . count($marks) . " subjects. They are: </br>"; $length = count($marks); for ($i = 0; $i < $length; $i++) { sort($marks); echo $marks[$i]; echo "</br>"; } ?> Output: Cara loves to study. English and Math are her favorite subjects She studies a total of 4 subjects. They are: English Geography Math Science Notice that the subjects are now organized in alphabetical order. The rsort() is a default method given by PHP. It is used to sort the given array in descending order. <?php $marks[0] = "English"; $marks[1] = "Math"; $marks[2] = "Geography"; $marks[3] = "Science"; echo "Cara loves to study. " . $marks[0] . " and " . $marks[1] . " are her favorite subjects</br>"; echo "She studies a total of " . count($marks) . " subjects. They are: </br>"; $length = count($marks); for ($i = 0; $i < $length; $i++) { rsort($marks); echo $marks[$i]; echo "</br>"; } ?> Output: Cara loves to study. English and Math are her favorite subjects She studies a total of 4 subjects. They are: Science Math Geography English Notice that the subjects are now organized in alphabetical as descending order. The asort() is a default method given by PHP. It is used to sort the given associative array in ascending order, according to the value. <?php $marks['English'] = "91"; $marks['Math'] = "87"; $marks['Geography'] = "68"; $marks['Science'] = "99"; echo "Cara got " . $marks['English'] . " in English and " . $marks['Science'] . " in Science.</br>"; asort($marks); foreach ($marks as $x => $x_value) { echo "Subject=" . $x . ", Marks=" . $x_value . "</br>"; } ?> Output: Cara got 91 in English and 99 in Science. Subject=Geography, Marks=68 Subject=Math, Marks=87 Subject=English, Marks=91 Subject=Science, Marks=99 The arsort() is a default method given by PHP. It is used to sort the given associative array in descending order, according to the value. <?php $marks['English'] = "91"; $marks['Math'] = "87"; $marks['Geography'] = "68"; $marks['Science'] = "99"; echo "Cara got " . $marks['English'] . " in English and " . $marks['Science'] . " in Science.</br>"; arsort($marks); foreach ($marks as $x => $x_value) { echo "Subject=" . $x . ", Marks=" . $x_value . "</br>"; } ?> Output: Cara got 91 in English and 99 in Science. Subject=Science, Marks=99 Subject=English, Marks=91 Subject=Math, Marks=87 Subject=Geography, Marks=68 The ksort() is a default method given by PHP. It is used to sort the given associative array in ascending order, according to the key. <?php $marks['English'] = "91"; $marks['Math'] = "87"; $marks['Geography'] = "68"; $marks['Science'] = "99"; echo "Cara got " . $marks['English'] . " in English and " . $marks['Science'] . " in Science.</br>"; ksort($marks); foreach ($marks as $x => $x_value) { echo "Subject=" . $x . ", Marks=" . $x_value . "</br>"; } ?> Output: Cara got 91 in English and 99 in Science. Subject=English, Marks=91 Subject=Geography, Marks=68 Subject=Math, Marks=87 Subject=Science, Marks=99 The krsort() is a default method given by PHP. It is used to sort the given associative array in descending order, according to the key. <?php $marks['English'] = "91"; $marks['Math'] = "87"; $marks['Geography'] = "68"; $marks['Science'] = "99"; echo "Cara got " . $marks['English'] . " in English and " . $marks['Science'] . " in Science.</br>"; krsort($marks); foreach ($marks as $x => $x_value) { echo "Subject=" . $x . ", Marks=" . $x_value . "</br>"; } ?> Output: Cara got 91 in English and 99 in Science. Subject=Science, Marks=99 Subject=Math, Marks=87 Subject=Geography, Marks=68 Subject=English, Marks=91 Happy Learning 🙂 How to Sort ArrayList in Java Descending Order Using Array in AngularJs Example How to sort a Map using Java8 PHP Multidimensional Arrays Example Bubble Sort In Java Java Insertion Sort Java 8 Stream Filter Example with Objects Selection Sort In Java PHP Array Example Tutorials How to Sort an Array in Parallel in Java 8 PHP Introduction Tutorials PHP Syntax Example Tutorials PHP Operators Example Tutorials PHP Variables Example Tutorials PHP Functions Example Tutorials How to Sort ArrayList in Java Descending Order Using Array in AngularJs Example How to sort a Map using Java8 PHP Multidimensional Arrays Example Bubble Sort In Java Java Insertion Sort Java 8 Stream Filter Example with Objects Selection Sort In Java PHP Array Example Tutorials How to Sort an Array in Parallel in Java 8 PHP Introduction Tutorials PHP Syntax Example Tutorials PHP Operators Example Tutorials PHP Variables Example Tutorials PHP Functions Example Tutorials
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 602, "s": 398, "text": "In the previous tutorials, we have discussed how to create an array in php and different types of arrays in php. Now, in this tutorials we are going to learn different types of php array sort techniques." }, { "code": null, "e": 736, "s": 602, "text": "Sorting arrays provides a way to organize data sets in either alphabetical order or in numbers, in an ascending or descending manner." }, { "code": null, "e": 812, "s": 736, "text": "PHP provides many predefined functions to sort an array. Here are the list." }, { "code": null, "e": 869, "s": 812, "text": "sort() – It will sort an given array in ascending order." }, { "code": null, "e": 928, "s": 869, "text": "rsort() – It will sort an given arrays in descending order" }, { "code": null, "e": 1021, "s": 928, "text": "asort() – It will sort an given associative array in ascending order, according to the value" }, { "code": null, "e": 1112, "s": 1021, "text": "ksort() – It will sort an given associative array in ascending order, according to the key" }, { "code": null, "e": 1207, "s": 1112, "text": "arsort() – It will sort an given associative array in descending order, according to the value" }, { "code": null, "e": 1300, "s": 1207, "text": "krsort() – It will sort an given associative array in descending order, according to the key" }, { "code": null, "e": 1400, "s": 1300, "text": "The sort() is a default method given by PHP. It is used to sort the given array in ascending order." }, { "code": null, "e": 1799, "s": 1400, "text": "<?php\n\n$marks[0] = \"English\";\n$marks[1] = \"Math\";\n$marks[2] = \"Geography\";\n$marks[3] = \"Science\";\necho \"Cara loves to study. \" . $marks[0] . \" and \" . $marks[1] . \" are her favorite subjects</br>\";\necho \"She studies a total of \" . count($marks) . \" subjects. They are: </br>\";\n$length = count($marks);\nfor ($i = 0; $i < $length; $i++) {\n sort($marks);\n echo $marks[$i];\n echo \"</br>\";\n}\n?>" }, { "code": null, "e": 1807, "s": 1799, "text": "Output:" }, { "code": null, "e": 1947, "s": 1807, "text": "Cara loves to study. English and Math are her favorite subjects\nShe studies a total of 4 subjects. They are:\nEnglish\nGeography\nMath\nScience" }, { "code": null, "e": 2013, "s": 1947, "text": "Notice that the subjects are now organized in alphabetical order." }, { "code": null, "e": 2115, "s": 2013, "text": "The rsort() is a default method given by PHP. It is used to sort the given array in descending order." }, { "code": null, "e": 2514, "s": 2115, "text": "<?php $marks[0] = \"English\";\n$marks[1] = \"Math\";\n$marks[2] = \"Geography\";\n$marks[3] = \"Science\";\necho \"Cara loves to study. \" . $marks[0] . \" and \" . $marks[1] . \" are her favorite subjects</br>\";\necho \"She studies a total of \" . count($marks) . \" subjects. They are: </br>\";\n$length = count($marks);\nfor ($i = 0; $i < $length; $i++) {\n rsort($marks);\n echo $marks[$i];\n echo \"</br>\";\n} ?>" }, { "code": null, "e": 2522, "s": 2514, "text": "Output:" }, { "code": null, "e": 2662, "s": 2522, "text": "Cara loves to study. English and Math are her favorite subjects\nShe studies a total of 4 subjects. They are:\nScience\nMath\nGeography\nEnglish" }, { "code": null, "e": 2742, "s": 2662, "text": "Notice that the subjects are now organized in alphabetical as descending order." }, { "code": null, "e": 2879, "s": 2742, "text": "The asort() is a default method given by PHP. It is used to sort the given associative array in ascending order, according to the value." }, { "code": null, "e": 3206, "s": 2879, "text": "<?php $marks['English'] = \"91\";\n$marks['Math'] = \"87\";\n$marks['Geography'] = \"68\";\n$marks['Science'] = \"99\";\necho \"Cara got \" . $marks['English'] . \" in English and \" . $marks['Science'] . \" in Science.</br>\";\nasort($marks);\nforeach ($marks as $x => $x_value) {\n echo \"Subject=\" . $x . \", Marks=\" . $x_value . \"</br>\";\n} ?>" }, { "code": null, "e": 3214, "s": 3206, "text": "Output:" }, { "code": null, "e": 3359, "s": 3214, "text": "Cara got 91 in English and 99 in Science.\nSubject=Geography, Marks=68\nSubject=Math, Marks=87\nSubject=English, Marks=91\nSubject=Science, Marks=99" }, { "code": null, "e": 3498, "s": 3359, "text": "The arsort() is a default method given by PHP. It is used to sort the given associative array in descending order, according to the value." }, { "code": null, "e": 3826, "s": 3498, "text": "<?php $marks['English'] = \"91\";\n$marks['Math'] = \"87\";\n$marks['Geography'] = \"68\";\n$marks['Science'] = \"99\";\necho \"Cara got \" . $marks['English'] . \" in English and \" . $marks['Science'] . \" in Science.</br>\";\narsort($marks);\nforeach ($marks as $x => $x_value) {\n echo \"Subject=\" . $x . \", Marks=\" . $x_value . \"</br>\";\n} ?>" }, { "code": null, "e": 3834, "s": 3826, "text": "Output:" }, { "code": null, "e": 3979, "s": 3834, "text": "Cara got 91 in English and 99 in Science.\nSubject=Science, Marks=99\nSubject=English, Marks=91\nSubject=Math, Marks=87\nSubject=Geography, Marks=68" }, { "code": null, "e": 4114, "s": 3979, "text": "The ksort() is a default method given by PHP. It is used to sort the given associative array in ascending order, according to the key." }, { "code": null, "e": 4441, "s": 4114, "text": "<?php $marks['English'] = \"91\";\n$marks['Math'] = \"87\";\n$marks['Geography'] = \"68\";\n$marks['Science'] = \"99\";\necho \"Cara got \" . $marks['English'] . \" in English and \" . $marks['Science'] . \" in Science.</br>\";\nksort($marks);\nforeach ($marks as $x => $x_value) {\n echo \"Subject=\" . $x . \", Marks=\" . $x_value . \"</br>\";\n} ?>" }, { "code": null, "e": 4449, "s": 4441, "text": "Output:" }, { "code": null, "e": 4594, "s": 4449, "text": "Cara got 91 in English and 99 in Science.\nSubject=English, Marks=91\nSubject=Geography, Marks=68\nSubject=Math, Marks=87\nSubject=Science, Marks=99" }, { "code": null, "e": 4731, "s": 4594, "text": "The krsort() is a default method given by PHP. It is used to sort the given associative array in descending order, according to the key." }, { "code": null, "e": 5059, "s": 4731, "text": "<?php $marks['English'] = \"91\";\n$marks['Math'] = \"87\";\n$marks['Geography'] = \"68\";\n$marks['Science'] = \"99\";\necho \"Cara got \" . $marks['English'] . \" in English and \" . $marks['Science'] . \" in Science.</br>\";\nkrsort($marks);\nforeach ($marks as $x => $x_value) {\n echo \"Subject=\" . $x . \", Marks=\" . $x_value . \"</br>\";\n} ?>" }, { "code": null, "e": 5067, "s": 5059, "text": "Output:" }, { "code": null, "e": 5212, "s": 5067, "text": "Cara got 91 in English and 99 in Science.\nSubject=Science, Marks=99\nSubject=Math, Marks=87\nSubject=Geography, Marks=68\nSubject=English, Marks=91" }, { "code": null, "e": 5229, "s": 5212, "text": "Happy Learning 🙂" }, { "code": null, "e": 5705, "s": 5229, "text": "\nHow to Sort ArrayList in Java Descending Order\nUsing Array in AngularJs Example\nHow to sort a Map using Java8\nPHP Multidimensional Arrays Example\nBubble Sort In Java\nJava Insertion Sort\nJava 8 Stream Filter Example with Objects\nSelection Sort In Java\nPHP Array Example Tutorials\nHow to Sort an Array in Parallel in Java 8\nPHP Introduction Tutorials\nPHP Syntax Example Tutorials\nPHP Operators Example Tutorials\nPHP Variables Example Tutorials\nPHP Functions Example Tutorials\n" }, { "code": null, "e": 5752, "s": 5705, "text": "How to Sort ArrayList in Java Descending Order" }, { "code": null, "e": 5785, "s": 5752, "text": "Using Array in AngularJs Example" }, { "code": null, "e": 5815, "s": 5785, "text": "How to sort a Map using Java8" }, { "code": null, "e": 5851, "s": 5815, "text": "PHP Multidimensional Arrays Example" }, { "code": null, "e": 5871, "s": 5851, "text": "Bubble Sort In Java" }, { "code": null, "e": 5891, "s": 5871, "text": "Java Insertion Sort" }, { "code": null, "e": 5933, "s": 5891, "text": "Java 8 Stream Filter Example with Objects" }, { "code": null, "e": 5956, "s": 5933, "text": "Selection Sort In Java" }, { "code": null, "e": 5984, "s": 5956, "text": "PHP Array Example Tutorials" }, { "code": null, "e": 6027, "s": 5984, "text": "How to Sort an Array in Parallel in Java 8" }, { "code": null, "e": 6054, "s": 6027, "text": "PHP Introduction Tutorials" }, { "code": null, "e": 6083, "s": 6054, "text": "PHP Syntax Example Tutorials" }, { "code": null, "e": 6115, "s": 6083, "text": "PHP Operators Example Tutorials" }, { "code": null, "e": 6147, "s": 6115, "text": "PHP Variables Example Tutorials" } ]
Weight Initialization in Neural Networks: A Journey From the Basics to Kaiming | by James Dellinger | Towards Data Science
I’d like to invite you to join me on an exploration through different approaches to initializing layer weights in neural networks. Step-by-step, through various short experiments and thought exercises, we’ll discover why adequate weight initialization is so important in training deep neural nets. Along the way we’ll cover various approaches that researchers have proposed over the years, and finally drill down on what works best for the contemporary network architectures that you’re most likely to be working with. The examples to follow come from my own re-implementation of a set of notebooks that Jeremy Howard covered in the latest version of fast.ai’s Deep Learning Part II course, currently being held this spring, 2019, at USF’s Data Institute. The aim of weight initialization is to prevent layer activation outputs from exploding or vanishing during the course of a forward pass through a deep neural network. If either occurs, loss gradients will either be too large or too small to flow backwards beneficially, and the network will take longer to converge, if it is even able to do so at all. Matrix multiplication is the essential math operation of a neural network. In deep neural nets with several layers, one forward pass simply entails performing consecutive matrix multiplications at each layer, between that layer’s inputs and weight matrix. The product of this multiplication at one layer becomes the inputs of the subsequent layer, and so on and so forth. For a quick-and-dirty example that illustrates this, let’s pretend that we have a vector x that contains some network inputs. It’s standard practice when training neural networks to ensure that our inputs’ values are scaled such that they fall inside such a normal distribution with a mean of 0 and a standard deviation of 1. Let’s also pretend that we have a simple 100-layer network with no activations , and that each layer has a matrix a that contains the layer’s weights. In order to complete a single forward pass we’ll have to perform a matrix multiplication between layer inputs and weights at each of the hundred layers, which will make for a grand total of 100 consecutive matrix multiplications. It turns out that initializing the values of layer weights from the same standard normal distribution to which we scaled our inputs is never a good idea. To see why, we can simulate a forward pass through our hypothetical network. Whoa! Somewhere during those 100 multiplications, the layer outputs got so big that even the computer wasn’t able to recognize their standard deviation and mean as numbers. We can actually see exactly how long that took to happen. The activation outputs exploded within 29 of our network’s layers. We clearly initialized our weights to be too large. Unfortunately, we also have to worry about preventing layer outputs from vanishing. To see what happens when we initialize network weights to be too small — we’ll scale our weight values such that, while they still fall inside a normal distribution with a mean of 0, they have a standard deviation of 0.01. During the course of the above hypothetical forward pass, the activation outputs completely vanished. To sum it up, if weights are initialized too large, the network won’t learn well. The same happens when weights are initialized too small. Remember that as mentioned above, the math required to complete a forward pass through a neural network entails nothing more than a succession of matrix multiplications. If we have an output y that is the product of a matrix multiplication between our input vector x and weight matrix a, each element i in y is defined as where i is a given row-index of weight matrix a, k is both a given column-index in weight matrix a and element-index in input vector x, and n is the range or total number of elements in x. This can also be defined in Python as: y[i] = sum([c*d for c,d in zip(a[i], x)]) We can demonstrate that at a given layer, the matrix product of our inputs x and weight matrix a that we initialized from a standard normal distribution will, on average, have a standard deviation very close to the square root of the number of input connections, which in our example is √512. This property isn’t surprising if we view it in terms of how matrix multiplication is defined: in order to calculate y we sum 512 products of the element-wise multiplication of one element of the inputs x by one column of the weights a. In our example where both x and a are initialized using standard normal distributions, each of these 512 products would have a mean of 0 and standard deviation of 1. It then follows that the sum of these 512 products would have a mean of 0, variance of 512, and therefore a standard deviation of √512. And this is why in our example above we saw our layer outputs exploding after 29 consecutive matrix multiplications. In the case of our bare-bones 100-layer network architecture, what we’d like is for each layer’s outputs to have a standard deviation of about 1. This conceivably would allow us to repeat matrix multiplications across as many network layers as we want, without activations exploding or vanishing. If we first scale the weight matrix a by dividing all its randomly chosen values by √512, the element-wise multiplication that fills in one element of the outputs y would now, on average, have a variance of only 1/√512. This means that the standard deviation of the matrix y, which contains each of the 512 values that are generated by way of the matrix multiplication between inputs x and weights a, would be 1. Let’s confirm this experimentally. Now let’s re-run our quick-and-dirty 100-layer network. As before, we first choose layer weights at random from standard normal distribution inside [-1,1], but this time we scale those weights by 1/√n, where n is the number of network input connections at a layer, which is 512 in our example. Success! Our layer outputs neither exploded nor vanished, even after 100 of our hypothetical layers. While at first glance it may seem like at this point we can call it a day, real-world neural networks aren’t quite as simple as our first example may seem to indicate. For the sake of simplicity, activation functions were omitted. However, we’d never do this in real life. It’s thanks to the placement of these non-linear activation functions at the tail end of network layers, that deep neural nets are able create close approximations of intricate functions that describe real-world phenomena, which can then be used to generate astoundingly impressive predictions, such as the classification of handwriting samples. Up until a few years ago, most commonly used activation functions were symmetric about a given value, and had ranges that asymptotically approached values that were plus/minus a certain distance from this midpoint. The hyperbolic tangent and softsign functions exemplify this class of activations. We’ll add a hyperbolic tangent activation function after each layer our hypothetical 100-layer network, and then see what happens when we use our home-grown weight initialization scheme where layer weights are scaled by 1/√n. The standard deviation of activation outputs of the 100th layer is down to about 0.06. This is definitely on the small side, but at least activations haven’t totally vanished! As intuitive as the journey to discovering our home-grown weight init strategy may now seem in retrospect, you may be surprised to hear that as recently as 2010, this was not the conventional approach for initializing weight layers. When Xavier Glorot and Yoshua Bengio published their landmark paper titled Understanding the difficulty of training deep feedforward neural networks, the “commonly used heuristic” to which they compared their experiments was that of initializing weights from a uniform distribution in [-1,1] and then scaling by 1/√n. It turns out this “standard” approach doesn’t actually work that well. Re-running our 100-layer tanh network with “standard” weight initialization caused activation gradients to become infinitesimally small — they’re just about as good as vanished. This poor performance is actually what spurred Glorot and Bengio to propose their own weight initialization strategy, which they referred to as “normalized initialization” in their paper, and which is now popularly termed “Xavier initialization.” Xavier initialization sets a layer’s weights to values chosen from a random uniform distribution that’s bounded between where ni is the number of incoming network connections, or “fan-in,” to the layer, and ni+1 is the number of outgoing network connections from that layer, also known as the “fan-out.” Glorot and Bengio believed that Xavier weight initialization would maintain the variance of activations and back-propagated gradients all the way up or down the layers of a network. In their experiments they observed that Xavier initialization enabled a 5-layer network to maintain near identical variances of its weight gradients across layers. Conversely, it turned out that using “standard” initialization brought about a much bigger gap in variance between weight gradients at the network’s lower layers, which were higher, and those at its top-most layers, which were approaching zero. To drive the point home, Glorot and Bengio demonstrated that networks initialized with Xavier achieved substantially quicker convergence and higher accuracy on the CIFAR-10 image classification task. Let’s re-run our 100-layer tanh network once more, this time using Xavier initialization: In our experimental network, Xavier initialization performs pretty identical to the home-grown method that we derived earlier, where we sampled values from a random normal distribution and scaled by the square root of number of incoming network connections, n. Conceptually, it makes sense that when using activation functions that are symmetric about zero and have outputs inside [-1,1], such as softsign and tanh, we’d want the activation outputs of each layer to have a mean of 0 and a standard deviation around 1, on average. This is precisely what our home-grown method and Xavier both enable. But what if we’re using ReLU activation functions? Would it still make sense to want to scale random initial weight values in the same way? To see what would happen, let’s use a ReLU activation instead of tanh in one of our hypothetical network’s layers and observe the expected standard deviation of its outputs. It turns out that when using a ReLU activation, a single layer will, on average have standard deviation that’s very close to the square root of the number of input connections, divided by the square root of two, or √512/√2 in our example. Scaling the values of the weight matrix a by this number will cause each individual ReLU layer to have a standard deviation of 1 on average. As we showed before, keeping the standard deviation of layers’ activations around 1 will allow us to stack several more layers in a deep neural network without gradients exploding or vanishing. This exploration into how to best initialize weights in networks with ReLU-like activations is what motivated Kaiming He et. al. to propose their own initialization scheme that’s tailored for deep neural nets that use these kinds of asymmetric, non-linear activations. In their 2015 paper, He et. al. demonstrated that deep networks (e.g. a 22-layer CNN) would converge much earlier if the following input weight initialization strategy is employed: Create a tensor with the dimensions appropriate for a weight matrix at a given layer, and populate it with numbers randomly chosen from a standard normal distribution.Multiply each randomly chosen number by √2/√n where n is the number of incoming connections coming into a given layer from the previous layer’s output (also known as the “fan-in”).Bias tensors are initialized to zero. Create a tensor with the dimensions appropriate for a weight matrix at a given layer, and populate it with numbers randomly chosen from a standard normal distribution. Multiply each randomly chosen number by √2/√n where n is the number of incoming connections coming into a given layer from the previous layer’s output (also known as the “fan-in”). Bias tensors are initialized to zero. We can follow these directions to implement our own version of Kaiming initialization and verify that it can indeed prevent activation outputs from exploding or vanishing if ReLU is used at all layers of our hypothetical 100-layer network. As a final comparison, here’s what would happen if we were to use Xavier initialization, instead. Ouch! When using Xavier to initialize weights, activation outputs have almost completely vanished by the 100th layer! Incidentally, when they trained even deeper networks that used ReLUs, He et. al. found that a 30-layer CNN using Xavier initialization stalled completely and didn’t learn at all. However, when the same network was initialized according to the three-step procedure outlined above, it enjoyed substantially greater convergence. The moral of the story for us is that any network we train from scratch, especially for computer vision applications, will almost certainly contain ReLU activation functions and be several layers deep. In such cases, Kaiming should be our go-to weight init strategy. Even more importantly, I’m not ashamed to admit that I felt intimidated when I saw the Xavier and Kaiming formulas for the first time. What with their respective square roots of six and two, part of me couldn’t help but feel like they must have been the result of some sort of oracular wisdom I couldn’t hope to fathom on my own. And let’s face it, sometimes the math in deep learning papers can look a lot like hieroglyphics, except with no Rosetta Stone to aid in translation. But I think the journey we took here showed us that this knee-jerk response of feeling of intimidated, while wholly understandable, is by no means unavoidable. Although the Kaiming and (especially) the Xavier papers do contain their fair share of math, we saw firsthand how experiments, empirical observation, and some straightforward common sense were enough to help derive the core set of principals underpinning what is currently the most widely-used weight initialization scheme. Alternately put: when in doubt, be courageous, try things out, and see what happens!
[ { "code": null, "e": 565, "s": 46, "text": "I’d like to invite you to join me on an exploration through different approaches to initializing layer weights in neural networks. Step-by-step, through various short experiments and thought exercises, we’ll discover why adequate weight initialization is so important in training deep neural nets. Along the way we’ll cover various approaches that researchers have proposed over the years, and finally drill down on what works best for the contemporary network architectures that you’re most likely to be working with." }, { "code": null, "e": 802, "s": 565, "text": "The examples to follow come from my own re-implementation of a set of notebooks that Jeremy Howard covered in the latest version of fast.ai’s Deep Learning Part II course, currently being held this spring, 2019, at USF’s Data Institute." }, { "code": null, "e": 1154, "s": 802, "text": "The aim of weight initialization is to prevent layer activation outputs from exploding or vanishing during the course of a forward pass through a deep neural network. If either occurs, loss gradients will either be too large or too small to flow backwards beneficially, and the network will take longer to converge, if it is even able to do so at all." }, { "code": null, "e": 1526, "s": 1154, "text": "Matrix multiplication is the essential math operation of a neural network. In deep neural nets with several layers, one forward pass simply entails performing consecutive matrix multiplications at each layer, between that layer’s inputs and weight matrix. The product of this multiplication at one layer becomes the inputs of the subsequent layer, and so on and so forth." }, { "code": null, "e": 1852, "s": 1526, "text": "For a quick-and-dirty example that illustrates this, let’s pretend that we have a vector x that contains some network inputs. It’s standard practice when training neural networks to ensure that our inputs’ values are scaled such that they fall inside such a normal distribution with a mean of 0 and a standard deviation of 1." }, { "code": null, "e": 2233, "s": 1852, "text": "Let’s also pretend that we have a simple 100-layer network with no activations , and that each layer has a matrix a that contains the layer’s weights. In order to complete a single forward pass we’ll have to perform a matrix multiplication between layer inputs and weights at each of the hundred layers, which will make for a grand total of 100 consecutive matrix multiplications." }, { "code": null, "e": 2464, "s": 2233, "text": "It turns out that initializing the values of layer weights from the same standard normal distribution to which we scaled our inputs is never a good idea. To see why, we can simulate a forward pass through our hypothetical network." }, { "code": null, "e": 2695, "s": 2464, "text": "Whoa! Somewhere during those 100 multiplications, the layer outputs got so big that even the computer wasn’t able to recognize their standard deviation and mean as numbers. We can actually see exactly how long that took to happen." }, { "code": null, "e": 2814, "s": 2695, "text": "The activation outputs exploded within 29 of our network’s layers. We clearly initialized our weights to be too large." }, { "code": null, "e": 3121, "s": 2814, "text": "Unfortunately, we also have to worry about preventing layer outputs from vanishing. To see what happens when we initialize network weights to be too small — we’ll scale our weight values such that, while they still fall inside a normal distribution with a mean of 0, they have a standard deviation of 0.01." }, { "code": null, "e": 3223, "s": 3121, "text": "During the course of the above hypothetical forward pass, the activation outputs completely vanished." }, { "code": null, "e": 3362, "s": 3223, "text": "To sum it up, if weights are initialized too large, the network won’t learn well. The same happens when weights are initialized too small." }, { "code": null, "e": 3684, "s": 3362, "text": "Remember that as mentioned above, the math required to complete a forward pass through a neural network entails nothing more than a succession of matrix multiplications. If we have an output y that is the product of a matrix multiplication between our input vector x and weight matrix a, each element i in y is defined as" }, { "code": null, "e": 3912, "s": 3684, "text": "where i is a given row-index of weight matrix a, k is both a given column-index in weight matrix a and element-index in input vector x, and n is the range or total number of elements in x. This can also be defined in Python as:" }, { "code": null, "e": 3954, "s": 3912, "text": "y[i] = sum([c*d for c,d in zip(a[i], x)])" }, { "code": null, "e": 4247, "s": 3954, "text": "We can demonstrate that at a given layer, the matrix product of our inputs x and weight matrix a that we initialized from a standard normal distribution will, on average, have a standard deviation very close to the square root of the number of input connections, which in our example is √512." }, { "code": null, "e": 4650, "s": 4247, "text": "This property isn’t surprising if we view it in terms of how matrix multiplication is defined: in order to calculate y we sum 512 products of the element-wise multiplication of one element of the inputs x by one column of the weights a. In our example where both x and a are initialized using standard normal distributions, each of these 512 products would have a mean of 0 and standard deviation of 1." }, { "code": null, "e": 4786, "s": 4650, "text": "It then follows that the sum of these 512 products would have a mean of 0, variance of 512, and therefore a standard deviation of √512." }, { "code": null, "e": 5200, "s": 4786, "text": "And this is why in our example above we saw our layer outputs exploding after 29 consecutive matrix multiplications. In the case of our bare-bones 100-layer network architecture, what we’d like is for each layer’s outputs to have a standard deviation of about 1. This conceivably would allow us to repeat matrix multiplications across as many network layers as we want, without activations exploding or vanishing." }, { "code": null, "e": 5420, "s": 5200, "text": "If we first scale the weight matrix a by dividing all its randomly chosen values by √512, the element-wise multiplication that fills in one element of the outputs y would now, on average, have a variance of only 1/√512." }, { "code": null, "e": 5648, "s": 5420, "text": "This means that the standard deviation of the matrix y, which contains each of the 512 values that are generated by way of the matrix multiplication between inputs x and weights a, would be 1. Let’s confirm this experimentally." }, { "code": null, "e": 5942, "s": 5648, "text": "Now let’s re-run our quick-and-dirty 100-layer network. As before, we first choose layer weights at random from standard normal distribution inside [-1,1], but this time we scale those weights by 1/√n, where n is the number of network input connections at a layer, which is 512 in our example." }, { "code": null, "e": 6043, "s": 5942, "text": "Success! Our layer outputs neither exploded nor vanished, even after 100 of our hypothetical layers." }, { "code": null, "e": 6662, "s": 6043, "text": "While at first glance it may seem like at this point we can call it a day, real-world neural networks aren’t quite as simple as our first example may seem to indicate. For the sake of simplicity, activation functions were omitted. However, we’d never do this in real life. It’s thanks to the placement of these non-linear activation functions at the tail end of network layers, that deep neural nets are able create close approximations of intricate functions that describe real-world phenomena, which can then be used to generate astoundingly impressive predictions, such as the classification of handwriting samples." }, { "code": null, "e": 6960, "s": 6662, "text": "Up until a few years ago, most commonly used activation functions were symmetric about a given value, and had ranges that asymptotically approached values that were plus/minus a certain distance from this midpoint. The hyperbolic tangent and softsign functions exemplify this class of activations." }, { "code": null, "e": 7186, "s": 6960, "text": "We’ll add a hyperbolic tangent activation function after each layer our hypothetical 100-layer network, and then see what happens when we use our home-grown weight initialization scheme where layer weights are scaled by 1/√n." }, { "code": null, "e": 7362, "s": 7186, "text": "The standard deviation of activation outputs of the 100th layer is down to about 0.06. This is definitely on the small side, but at least activations haven’t totally vanished!" }, { "code": null, "e": 7595, "s": 7362, "text": "As intuitive as the journey to discovering our home-grown weight init strategy may now seem in retrospect, you may be surprised to hear that as recently as 2010, this was not the conventional approach for initializing weight layers." }, { "code": null, "e": 7913, "s": 7595, "text": "When Xavier Glorot and Yoshua Bengio published their landmark paper titled Understanding the difficulty of training deep feedforward neural networks, the “commonly used heuristic” to which they compared their experiments was that of initializing weights from a uniform distribution in [-1,1] and then scaling by 1/√n." }, { "code": null, "e": 7984, "s": 7913, "text": "It turns out this “standard” approach doesn’t actually work that well." }, { "code": null, "e": 8162, "s": 7984, "text": "Re-running our 100-layer tanh network with “standard” weight initialization caused activation gradients to become infinitesimally small — they’re just about as good as vanished." }, { "code": null, "e": 8409, "s": 8162, "text": "This poor performance is actually what spurred Glorot and Bengio to propose their own weight initialization strategy, which they referred to as “normalized initialization” in their paper, and which is now popularly termed “Xavier initialization.”" }, { "code": null, "e": 8529, "s": 8409, "text": "Xavier initialization sets a layer’s weights to values chosen from a random uniform distribution that’s bounded between" }, { "code": null, "e": 8713, "s": 8529, "text": "where ni is the number of incoming network connections, or “fan-in,” to the layer, and ni+1 is the number of outgoing network connections from that layer, also known as the “fan-out.”" }, { "code": null, "e": 9059, "s": 8713, "text": "Glorot and Bengio believed that Xavier weight initialization would maintain the variance of activations and back-propagated gradients all the way up or down the layers of a network. In their experiments they observed that Xavier initialization enabled a 5-layer network to maintain near identical variances of its weight gradients across layers." }, { "code": null, "e": 9304, "s": 9059, "text": "Conversely, it turned out that using “standard” initialization brought about a much bigger gap in variance between weight gradients at the network’s lower layers, which were higher, and those at its top-most layers, which were approaching zero." }, { "code": null, "e": 9504, "s": 9304, "text": "To drive the point home, Glorot and Bengio demonstrated that networks initialized with Xavier achieved substantially quicker convergence and higher accuracy on the CIFAR-10 image classification task." }, { "code": null, "e": 9594, "s": 9504, "text": "Let’s re-run our 100-layer tanh network once more, this time using Xavier initialization:" }, { "code": null, "e": 9855, "s": 9594, "text": "In our experimental network, Xavier initialization performs pretty identical to the home-grown method that we derived earlier, where we sampled values from a random normal distribution and scaled by the square root of number of incoming network connections, n." }, { "code": null, "e": 10193, "s": 9855, "text": "Conceptually, it makes sense that when using activation functions that are symmetric about zero and have outputs inside [-1,1], such as softsign and tanh, we’d want the activation outputs of each layer to have a mean of 0 and a standard deviation around 1, on average. This is precisely what our home-grown method and Xavier both enable." }, { "code": null, "e": 10333, "s": 10193, "text": "But what if we’re using ReLU activation functions? Would it still make sense to want to scale random initial weight values in the same way?" }, { "code": null, "e": 10507, "s": 10333, "text": "To see what would happen, let’s use a ReLU activation instead of tanh in one of our hypothetical network’s layers and observe the expected standard deviation of its outputs." }, { "code": null, "e": 10746, "s": 10507, "text": "It turns out that when using a ReLU activation, a single layer will, on average have standard deviation that’s very close to the square root of the number of input connections, divided by the square root of two, or √512/√2 in our example." }, { "code": null, "e": 10887, "s": 10746, "text": "Scaling the values of the weight matrix a by this number will cause each individual ReLU layer to have a standard deviation of 1 on average." }, { "code": null, "e": 11081, "s": 10887, "text": "As we showed before, keeping the standard deviation of layers’ activations around 1 will allow us to stack several more layers in a deep neural network without gradients exploding or vanishing." }, { "code": null, "e": 11350, "s": 11081, "text": "This exploration into how to best initialize weights in networks with ReLU-like activations is what motivated Kaiming He et. al. to propose their own initialization scheme that’s tailored for deep neural nets that use these kinds of asymmetric, non-linear activations." }, { "code": null, "e": 11531, "s": 11350, "text": "In their 2015 paper, He et. al. demonstrated that deep networks (e.g. a 22-layer CNN) would converge much earlier if the following input weight initialization strategy is employed:" }, { "code": null, "e": 11916, "s": 11531, "text": "Create a tensor with the dimensions appropriate for a weight matrix at a given layer, and populate it with numbers randomly chosen from a standard normal distribution.Multiply each randomly chosen number by √2/√n where n is the number of incoming connections coming into a given layer from the previous layer’s output (also known as the “fan-in”).Bias tensors are initialized to zero." }, { "code": null, "e": 12084, "s": 11916, "text": "Create a tensor with the dimensions appropriate for a weight matrix at a given layer, and populate it with numbers randomly chosen from a standard normal distribution." }, { "code": null, "e": 12265, "s": 12084, "text": "Multiply each randomly chosen number by √2/√n where n is the number of incoming connections coming into a given layer from the previous layer’s output (also known as the “fan-in”)." }, { "code": null, "e": 12303, "s": 12265, "text": "Bias tensors are initialized to zero." }, { "code": null, "e": 12543, "s": 12303, "text": "We can follow these directions to implement our own version of Kaiming initialization and verify that it can indeed prevent activation outputs from exploding or vanishing if ReLU is used at all layers of our hypothetical 100-layer network." }, { "code": null, "e": 12641, "s": 12543, "text": "As a final comparison, here’s what would happen if we were to use Xavier initialization, instead." }, { "code": null, "e": 12759, "s": 12641, "text": "Ouch! When using Xavier to initialize weights, activation outputs have almost completely vanished by the 100th layer!" }, { "code": null, "e": 13085, "s": 12759, "text": "Incidentally, when they trained even deeper networks that used ReLUs, He et. al. found that a 30-layer CNN using Xavier initialization stalled completely and didn’t learn at all. However, when the same network was initialized according to the three-step procedure outlined above, it enjoyed substantially greater convergence." }, { "code": null, "e": 13352, "s": 13085, "text": "The moral of the story for us is that any network we train from scratch, especially for computer vision applications, will almost certainly contain ReLU activation functions and be several layers deep. In such cases, Kaiming should be our go-to weight init strategy." }, { "code": null, "e": 13831, "s": 13352, "text": "Even more importantly, I’m not ashamed to admit that I felt intimidated when I saw the Xavier and Kaiming formulas for the first time. What with their respective square roots of six and two, part of me couldn’t help but feel like they must have been the result of some sort of oracular wisdom I couldn’t hope to fathom on my own. And let’s face it, sometimes the math in deep learning papers can look a lot like hieroglyphics, except with no Rosetta Stone to aid in translation." }, { "code": null, "e": 14315, "s": 13831, "text": "But I think the journey we took here showed us that this knee-jerk response of feeling of intimidated, while wholly understandable, is by no means unavoidable. Although the Kaiming and (especially) the Xavier papers do contain their fair share of math, we saw firsthand how experiments, empirical observation, and some straightforward common sense were enough to help derive the core set of principals underpinning what is currently the most widely-used weight initialization scheme." } ]
Sass - if() Function
Based on the condition, this built-in if() function returns only one result from two possible outcomes. The result of the function can be referred to the variable that may not be defined or to have further calculations. if( expression, value1, value2 ) The following example demonstrates the use of if() function in the SCSS file − <html> <head> <title>Control Directives & Expressions</title> <link rel = "stylesheet" type = "text/css" href = "style.css"/> </head> <body> <h2>Welcome to TutorialsPoint</h2> </body> </html> Next, create file style.scss. h2 { color: if( 1 + 1 == 2 , green , red); } You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command − sass --watch C:\ruby\lib\sass\style.scss:style.css Next, execute the above command; it will create the style.css file automatically with the following code − h2 { color: green; } Let us carry out the following steps to see how the above given code works − Save the above given html code in if_function.html file. Save the above given html code in if_function.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2072, "s": 1852, "text": "Based on the condition, this built-in if() function returns only one result from two possible outcomes. The result of the function can be referred to the variable that may not be defined or to have further calculations." }, { "code": null, "e": 2106, "s": 2072, "text": "if( expression, value1, value2 )\n" }, { "code": null, "e": 2185, "s": 2106, "text": "The following example demonstrates the use of if() function in the SCSS file −" }, { "code": null, "e": 2411, "s": 2185, "text": "<html>\n <head>\n <title>Control Directives & Expressions</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\"/>\n </head>\n \n <body>\n <h2>Welcome to TutorialsPoint</h2>\n </body>\n</html>" }, { "code": null, "e": 2441, "s": 2411, "text": "Next, create file style.scss." }, { "code": null, "e": 2489, "s": 2441, "text": "h2 {\n color: if( 1 + 1 == 2 , green , red);\n}" }, { "code": null, "e": 2605, "s": 2489, "text": "You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −" }, { "code": null, "e": 2657, "s": 2605, "text": "sass --watch C:\\ruby\\lib\\sass\\style.scss:style.css\n" }, { "code": null, "e": 2764, "s": 2657, "text": "Next, execute the above command; it will create the style.css file automatically with the following code −" }, { "code": null, "e": 2789, "s": 2764, "text": "h2 {\n color: green; \n}" }, { "code": null, "e": 2866, "s": 2789, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 2923, "s": 2866, "text": "Save the above given html code in if_function.html file." }, { "code": null, "e": 2980, "s": 2923, "text": "Save the above given html code in if_function.html file." }, { "code": null, "e": 3053, "s": 2980, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 3126, "s": 3053, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 3161, "s": 3126, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3178, "s": 3161, "text": " Code And Create" }, { "code": null, "e": 3213, "s": 3178, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 3226, "s": 3213, "text": " Juan Galvan" }, { "code": null, "e": 3263, "s": 3226, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 3283, "s": 3263, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 3320, "s": 3283, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 3336, "s": 3320, "text": " Muslim Helalee" }, { "code": null, "e": 3343, "s": 3336, "text": " Print" }, { "code": null, "e": 3354, "s": 3343, "text": " Add Notes" } ]
increment and decrement operators in Java (In Depth) - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see one of the most used and confused operators in java. That is increment and decrement operators. Increment and decrement operators are unary operators. We can only apply these operators on a single operand, hence these operators are called as unary operators. we can apply these unary operators on all primitive types except Boolean. the increment operator is an operator which is used to increase the value of a variable by 1, on which it is applied. Again these increment operators are two types: Pre increment (++x) Post increment (x++) If an Increment operator is used in front of an operand, then it is called as Pre Increment operator. Syntax: Example: class PreIncrement { public static void main(String[] args) { int x = 10; int y = ++x; System.out.println("y value is: " + y); } } Output: y value is: 11 If an Increment operator is used after an operand, then is called Post Increment operator. Syntax: Example: class PostIncrement { public static void main(String[] args) { int x = 10; int y = x++; System.out.println("y value is: " + y); } } Output: y value is: 10 Post increment operator is applied on ‘x’, here the case is exact opposite of pre increment, first the value of variable ‘x’ is assigned to the variable ‘y’ and then the value of ‘x’ is incremented by 1 . As per example, the initial value of ‘x’ is 10. After applying post-increment operator the current values of ‘x’ (i.e, 10) is assigned to y, and then the value of ‘x’ is incremented by 1. So when displaying variable ‘y’ it is showing as 10. The Decrement operator is an operator which is used to decrease the value of the variable by 1, on which it is applied. Like increment operators, decrement operators are also 2 types, Pre decrement (- -x) Post decrement (x- -) If a decrement operator is used in front of an operand, then it is called Pre decrement operator. Syntax: Example: class PreDecrement { public static void main(String[] args) { int x = 10; int y = --x; System.out.println("y value is: " + y); } } Output: y value is: 9 Pre decrement operator is applied on ‘x’, first, the value of ‘x’ will be decremented by 1 and then the decremented value will be assigned to the variable ‘y’. As per example, the initial value of ‘x’ is 10. After applying pre decrement operator on ‘x’, the value of ‘x’ is decremented by 1 (i.e., 9) and that value is assigned to the variable ‘y’. So, when we display the variable ‘y’ it is showing as 9. If a decrement operator is used after an operand, then it is called Post decrement operator. Example: class PostDecrement { public static void main(String[] args) { int x = 10; int y = x--; System.out.println("y value is: " + y); } } Output: y value is: 10 Post decrement operator is applied on ‘x’, here the case is the complete opposite of pre decrement operator, first, the value of variable ‘x’ is assigned to the variable ‘y’ and then the value of ‘x’ is decremented by 1. Syntax: As per example, the initial value of ‘x’ is 10. After applying post decrement operator on variable ‘x’ the current values of ‘x’ (i.e, 10) is assigned to ‘y’, and then the value of ‘x’ is decremented by 1. So when displaying the value of ‘y’ it is showing as 10. We can apply Increment and decrement operators only for variables but not for constant values. If we apply, then we will get compile time error. class IncAndDecOperatorsDemo { public static void main(String[] args) { int x = 10; int y = ++10; System.out.println("Value of y : " + y); } } We can’t apply the nesting on increment and decrement operators. class IncAndDecOperatorsDemo { public static void main(String[] args) { int x = 100; int y = --(--x); System.out.println("Value of y : " + y); } } We can’t apply increment and decrement operators on final variables. class IncAndDecOperatorsDemo { public static void main(String[] args) { final int x = 100; int y = ++x; System.out.println("Value of y : " + y); } } We can’t apply increment and decrement operators on boolean types. class IncAndDecOperatorsDemo { public static void main(String[] args) { boolean b = true; --b; System.out.println(b); } } class IncrementOperator { public static void main(String[] args) { int x = 10; x = x++; x = x++; x = x++; x = x++; x = x++; System.out.println("The Value of x is : " + x); } } Output: Value of x : 10 The Step by Step Analysis on Output: STEP 1 : Initial value of ‘x’ = 10; STEP 2 : The value of ‘x’ is post incremented and assigned again to ‘x’. The variable ‘x’ will be incremented first but the previous ‘x’ value (10) is assigned again to ‘x’ variable, and the incremented (11) value will be used after assigning. But in this example, the next value of ‘x’ is overridden by previous value (10) always. STEP 3: The value of ‘x’ is post incremented and assigned to ‘x’ only. STEP 4: The value of ‘x’ is post incremented and assigned to ‘x’ only. STEP 5: The value of ‘x’ is post incremented and assigned to ‘x’ only. class IncrementOperator { public static void main(String[] args) { int x = 1; x = x++ + ++x + x++ + ++x + ++x; System.out.println("Value of x : " + x); } } Output: Value of x : 18 The Step by Step Analysis on Output: STEP 1 : initial ‘x’ value is 1 STEP 2 : x++ (1) STEP 3 : ++x (2+1=3) STEP 4 : x++ (3+1 (Post increment) =3) STEP 5 : ++x (4+1 = 5) STEP 6 : ++x (5+1=6) STEP 7 : Add values from STEP 2 to STEP 6 (1+3+3+5+6) STEP 8 : Answer is18 Happy Learning 🙂 Difference between b++ and b=b+1 Technical Features of Java Programming Python List Data Structure In Depth Python Tuple Data Structure in Depth Hello World Java Program Example Java instanceof Operator == Versus .equals() in Java Python Set Data Structure in Depth Lambda Expressions in Java Java variable types Example PHP Operators Example Tutorials Python Operators Example C Program Addition and Subtraction without using + – Operators How HashMap Works In Java What is Java Arrays and how it works ? Difference between b++ and b=b+1 Technical Features of Java Programming Python List Data Structure In Depth Python Tuple Data Structure in Depth Hello World Java Program Example Java instanceof Operator == Versus .equals() in Java Python Set Data Structure in Depth Lambda Expressions in Java Java variable types Example PHP Operators Example Tutorials Python Operators Example C Program Addition and Subtraction without using + – Operators How HashMap Works In Java What is Java Arrays and how it works ? Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 532, "s": 398, "text": "In this tutorial, we are going to see one of the most used and confused operators in java. That is increment and decrement operators." }, { "code": null, "e": 695, "s": 532, "text": "Increment and decrement operators are unary operators. We can only apply these operators on a single operand, hence these operators are called as unary operators." }, { "code": null, "e": 769, "s": 695, "text": "we can apply these unary operators on all primitive types except Boolean." }, { "code": null, "e": 887, "s": 769, "text": "the increment operator is an operator which is used to increase the value of a variable by 1, on which it is applied." }, { "code": null, "e": 934, "s": 887, "text": "Again these increment operators are two types:" }, { "code": null, "e": 954, "s": 934, "text": "Pre increment (++x)" }, { "code": null, "e": 975, "s": 954, "text": "Post increment (x++)" }, { "code": null, "e": 1078, "s": 975, "text": "If an Increment operator is used in front of an operand, then it is called as Pre Increment operator." }, { "code": null, "e": 1086, "s": 1078, "text": "Syntax:" }, { "code": null, "e": 1095, "s": 1086, "text": "Example:" }, { "code": null, "e": 1291, "s": 1095, "text": "class PreIncrement {\n \n public static void main(String[] args) { \n int x = 10; \n int y = ++x; \n System.out.println(\"y value is: \" + y); \n }\n\n}" }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1314, "s": 1299, "text": "y value is: 11" }, { "code": null, "e": 1405, "s": 1314, "text": "If an Increment operator is used after an operand, then is called Post Increment operator." }, { "code": null, "e": 1413, "s": 1405, "text": "Syntax:" }, { "code": null, "e": 1422, "s": 1413, "text": "Example:" }, { "code": null, "e": 1612, "s": 1422, "text": "class PostIncrement {\n\n public static void main(String[] args) { \n int x = 10; \n int y = x++; \n System.out.println(\"y value is: \" + y); \n }\n\n}" }, { "code": null, "e": 1620, "s": 1612, "text": "Output:" }, { "code": null, "e": 1635, "s": 1620, "text": "y value is: 10" }, { "code": null, "e": 1842, "s": 1635, "text": "Post increment operator is applied on ‘x’, here the case is exact opposite of pre increment, first the value of variable ‘x’ is assigned to the variable ‘y’ and then the value of ‘x’ is incremented by 1 ." }, { "code": null, "e": 2083, "s": 1842, "text": "As per example, the initial value of ‘x’ is 10. After applying post-increment operator the current values of ‘x’ (i.e, 10) is assigned to y, and then the value of ‘x’ is incremented by 1. So when displaying variable ‘y’ it is showing as 10." }, { "code": null, "e": 2203, "s": 2083, "text": "The Decrement operator is an operator which is used to decrease the value of the variable by 1, on which it is applied." }, { "code": null, "e": 2267, "s": 2203, "text": "Like increment operators, decrement operators are also 2 types," }, { "code": null, "e": 2288, "s": 2267, "text": "Pre decrement (- -x)" }, { "code": null, "e": 2310, "s": 2288, "text": "Post decrement (x- -)" }, { "code": null, "e": 2408, "s": 2310, "text": "If a decrement operator is used in front of an operand, then it is called Pre decrement operator." }, { "code": null, "e": 2416, "s": 2408, "text": "Syntax:" }, { "code": null, "e": 2425, "s": 2416, "text": "Example:" }, { "code": null, "e": 2588, "s": 2425, "text": "class PreDecrement {\n public static void main(String[] args) {\n int x = 10;\n int y = --x;\n System.out.println(\"y value is: \" + y);\n }\n}" }, { "code": null, "e": 2596, "s": 2588, "text": "Output:" }, { "code": null, "e": 2610, "s": 2596, "text": "y value is: 9" }, { "code": null, "e": 2770, "s": 2610, "text": "Pre decrement operator is applied on ‘x’, first, the value of ‘x’ will be decremented by 1 and then the decremented value will be assigned to the variable ‘y’." }, { "code": null, "e": 3016, "s": 2770, "text": "As per example, the initial value of ‘x’ is 10. After applying pre decrement operator on ‘x’, the value of ‘x’ is decremented by 1 (i.e., 9) and that value is assigned to the variable ‘y’. So, when we display the variable ‘y’ it is showing as 9." }, { "code": null, "e": 3109, "s": 3016, "text": "If a decrement operator is used after an operand, then it is called Post decrement operator." }, { "code": null, "e": 3118, "s": 3109, "text": "Example:" }, { "code": null, "e": 3282, "s": 3118, "text": "class PostDecrement {\n public static void main(String[] args) {\n int x = 10;\n int y = x--;\n System.out.println(\"y value is: \" + y);\n }\n}" }, { "code": null, "e": 3290, "s": 3282, "text": "Output:" }, { "code": null, "e": 3305, "s": 3290, "text": "y value is: 10" }, { "code": null, "e": 3797, "s": 3305, "text": "Post decrement operator is applied on ‘x’, here the case is the complete opposite of pre decrement operator, first, the value of variable ‘x’ is assigned to the variable ‘y’ and then the value of ‘x’ is decremented by 1.\nSyntax:\nAs per example, the initial value of ‘x’ is 10. After applying post decrement operator on variable ‘x’ the current values of ‘x’ (i.e, 10) is assigned to ‘y’, and then the value of ‘x’ is decremented by 1. So when displaying the value of ‘y’ it is showing as 10." }, { "code": null, "e": 3942, "s": 3797, "text": "We can apply Increment and decrement operators only for variables but not for constant values. If we apply, then we will get compile time error." }, { "code": null, "e": 4153, "s": 3942, "text": "class IncAndDecOperatorsDemo {\n\n public static void main(String[] args) { \n int x = 10; \n int y = ++10; \n System.out.println(\"Value of y : \" + y);\n\n \n }\n\n}" }, { "code": null, "e": 4218, "s": 4153, "text": "We can’t apply the nesting on increment and decrement operators." }, { "code": null, "e": 4421, "s": 4218, "text": "class IncAndDecOperatorsDemo {\n\n public static void main(String[] args) { \n int x = 100; \n int y = --(--x); \n System.out.println(\"Value of y : \" + y);\n\n }\n\n}" }, { "code": null, "e": 4490, "s": 4421, "text": "We can’t apply increment and decrement operators on final variables." }, { "code": null, "e": 4695, "s": 4490, "text": "class IncAndDecOperatorsDemo {\n\n public static void main(String[] args) { \n final int x = 100; \n int y = ++x; \n System.out.println(\"Value of y : \" + y);\n\n }\n\n}" }, { "code": null, "e": 4762, "s": 4695, "text": "We can’t apply increment and decrement operators on boolean types." }, { "code": null, "e": 4919, "s": 4762, "text": "class IncAndDecOperatorsDemo {\n\n public static void main(String[] args) {\n boolean b = true;\n --b;\n System.out.println(b);\n\n }\n\n}" }, { "code": null, "e": 5211, "s": 4919, "text": "class IncrementOperator {\n\n public static void main(String[] args) { \n int x = 10; \n x = x++; \n x = x++; \n x = x++; \n x = x++; \n x = x++; \n System.out.println(\"The Value of x is : \" + x);\n\n }\n\n}" }, { "code": null, "e": 5219, "s": 5211, "text": "Output:" }, { "code": null, "e": 5235, "s": 5219, "text": "Value of x : 10" }, { "code": null, "e": 5272, "s": 5235, "text": "The Step by Step Analysis on Output:" }, { "code": null, "e": 5308, "s": 5272, "text": "STEP 1 : Initial value of ‘x’ = 10;" }, { "code": null, "e": 5381, "s": 5308, "text": "STEP 2 : The value of ‘x’ is post incremented and assigned again to ‘x’." }, { "code": null, "e": 5641, "s": 5381, "text": "The variable ‘x’ will be incremented first but the previous ‘x’ value (10) is assigned again to ‘x’ variable, and the incremented (11) value will be used after assigning. But in this example, the next value of ‘x’ is overridden by previous value (10) always." }, { "code": null, "e": 5712, "s": 5641, "text": "STEP 3: The value of ‘x’ is post incremented and assigned to ‘x’ only." }, { "code": null, "e": 5783, "s": 5712, "text": "STEP 4: The value of ‘x’ is post incremented and assigned to ‘x’ only." }, { "code": null, "e": 5854, "s": 5783, "text": "STEP 5: The value of ‘x’ is post incremented and assigned to ‘x’ only." }, { "code": null, "e": 6066, "s": 5854, "text": "class IncrementOperator {\n\n public static void main(String[] args) { \n int x = 1; \n x = x++ + ++x + x++ + ++x + ++x; \n System.out.println(\"Value of x : \" + x);\n\n }\n\n}" }, { "code": null, "e": 6074, "s": 6066, "text": "Output:" }, { "code": null, "e": 6090, "s": 6074, "text": "Value of x : 18" }, { "code": null, "e": 6127, "s": 6090, "text": "The Step by Step Analysis on Output:" }, { "code": null, "e": 6159, "s": 6127, "text": "STEP 1 : initial ‘x’ value is 1" }, { "code": null, "e": 6176, "s": 6159, "text": "STEP 2 : x++ (1)" }, { "code": null, "e": 6197, "s": 6176, "text": "STEP 3 : ++x (2+1=3)" }, { "code": null, "e": 6236, "s": 6197, "text": "STEP 4 : x++ (3+1 (Post increment) =3)" }, { "code": null, "e": 6259, "s": 6236, "text": "STEP 5 : ++x (4+1 = 5)" }, { "code": null, "e": 6280, "s": 6259, "text": "STEP 6 : ++x (5+1=6)" }, { "code": null, "e": 6334, "s": 6280, "text": "STEP 7 : Add values from STEP 2 to STEP 6 (1+3+3+5+6)" }, { "code": null, "e": 6355, "s": 6334, "text": "STEP 8 : Answer is18" }, { "code": null, "e": 6372, "s": 6355, "text": "Happy Learning 🙂" }, { "code": null, "e": 6880, "s": 6372, "text": "\nDifference between b++ and b=b+1\nTechnical Features of Java Programming\nPython List Data Structure In Depth\nPython Tuple Data Structure in Depth\nHello World Java Program Example\nJava instanceof Operator\n== Versus .equals() in Java\nPython Set Data Structure in Depth\nLambda Expressions in Java\nJava variable types Example\nPHP Operators Example Tutorials\nPython Operators Example\nC Program Addition and Subtraction without using + – Operators\nHow HashMap Works In Java\nWhat is Java Arrays and how it works ?\n" }, { "code": null, "e": 6913, "s": 6880, "text": "Difference between b++ and b=b+1" }, { "code": null, "e": 6952, "s": 6913, "text": "Technical Features of Java Programming" }, { "code": null, "e": 6988, "s": 6952, "text": "Python List Data Structure In Depth" }, { "code": null, "e": 7025, "s": 6988, "text": "Python Tuple Data Structure in Depth" }, { "code": null, "e": 7058, "s": 7025, "text": "Hello World Java Program Example" }, { "code": null, "e": 7083, "s": 7058, "text": "Java instanceof Operator" }, { "code": null, "e": 7111, "s": 7083, "text": "== Versus .equals() in Java" }, { "code": null, "e": 7146, "s": 7111, "text": "Python Set Data Structure in Depth" }, { "code": null, "e": 7173, "s": 7146, "text": "Lambda Expressions in Java" }, { "code": null, "e": 7201, "s": 7173, "text": "Java variable types Example" }, { "code": null, "e": 7233, "s": 7201, "text": "PHP Operators Example Tutorials" }, { "code": null, "e": 7258, "s": 7233, "text": "Python Operators Example" }, { "code": null, "e": 7321, "s": 7258, "text": "C Program Addition and Subtraction without using + – Operators" }, { "code": null, "e": 7347, "s": 7321, "text": "How HashMap Works In Java" }, { "code": null, "e": 7386, "s": 7347, "text": "What is Java Arrays and how it works ?" }, { "code": null, "e": 7392, "s": 7390, "text": "Δ" }, { "code": null, "e": 7416, "s": 7392, "text": " Install Java on Mac OS" }, { "code": null, "e": 7444, "s": 7416, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 7473, "s": 7444, "text": " Install Minikube on Windows" }, { "code": null, "e": 7508, "s": 7473, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 7535, "s": 7508, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 7562, "s": 7535, "text": " Install Gradle on Windows" }, { "code": null, "e": 7591, "s": 7562, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 7617, "s": 7591, "text": " Install PuTTY on windows" }, { "code": null, "e": 7643, "s": 7617, "text": " Install Mysql on Windows" }, { "code": null, "e": 7679, "s": 7643, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 7713, "s": 7679, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 7739, "s": 7713, "text": " Install Maven on Windows" }, { "code": null, "e": 7764, "s": 7739, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 7798, "s": 7764, "text": " Install Maven on Windows Command" }, { "code": null, "e": 7833, "s": 7798, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 7857, "s": 7833, "text": " Install Ant on Windows" }, { "code": null, "e": 7886, "s": 7857, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 7918, "s": 7886, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 7951, "s": 7918, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 7976, "s": 7951, "text": " Java8 – Install Windows" }, { "code": null, "e": 7993, "s": 7976, "text": " Java8 – foreach" }, { "code": null, "e": 8021, "s": 7993, "text": " Java8 – forEach with index" }, { "code": null, "e": 8052, "s": 8021, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 8084, "s": 8052, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 8104, "s": 8084, "text": " Java8 – GroupingBy" }, { "code": null, "e": 8124, "s": 8104, "text": " Java8 – SummingInt" }, { "code": null, "e": 8148, "s": 8124, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 8178, "s": 8148, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 8210, "s": 8178, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 8246, "s": 8210, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 8290, "s": 8246, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 8322, "s": 8290, "text": " Howto – Convert List to String" }, { "code": null, "e": 8363, "s": 8322, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 8400, "s": 8363, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 8440, "s": 8400, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 8469, "s": 8440, "text": " Howto – Convert List to Map" }, { "code": null, "e": 8501, "s": 8469, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 8521, "s": 8501, "text": " Howto – Sort a Map" }, { "code": null, "e": 8543, "s": 8521, "text": " Howto – Filter a Map" }, { "code": null, "e": 8573, "s": 8543, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 8624, "s": 8573, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 8660, "s": 8624, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 8692, "s": 8660, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 8727, "s": 8692, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 8750, "s": 8727, "text": " Howto – Merge Streams" }, { "code": null, "e": 8797, "s": 8750, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 8822, "s": 8797, "text": " Howto -Get Stream count" }, { "code": null, "e": 8866, "s": 8822, "text": " Howto – Get Min and Max values in a Stream" } ]
Python | Pandas dataframe.get_dtype_counts() - GeeksforGeeks
19 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.get_dtype_counts() function returns the counts of dtypes in the given object. It returns a pandas series object containing the counts of all data types present in the pandas object. It works with pandas series as well as dataframe. Syntax: DataFrame.get_dtype_counts() Returns : value : Series : Counts of datatypes For link to CSV file Used in Code, click here Example #1: Use get_dtype_counts() function to find the counts of datatype of a pandas dataframe object. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf Now apply the get_dtype_counts() function. Find out the frequency of occurrence of each data type in the dataframe. # applying get_dtype_counts() function df.get_dtype_counts() Output : Notice, the output is a pandas series object containing the count of each data types in the dataframe. Example #2: Use get_dtype_counts() function over a selected no. of columns of the data frame only. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Applying get_dtype_counts() function to # find the data type counts in modified dataframe.df[["Salary", "Name", "Team"]].get_dtype_counts() Notice, the output is a pandas series object containing the count of each data types in the dataframe. We can verify all these results using this the dataframe.info() function. # Find out the types of all columns in the dataframedf.info() Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 26088, "s": 26060, "text": "\n19 Nov, 2018" }, { "code": null, "e": 26302, "s": 26088, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26551, "s": 26302, "text": "Pandas dataframe.get_dtype_counts() function returns the counts of dtypes in the given object. It returns a pandas series object containing the counts of all data types present in the pandas object. It works with pandas series as well as dataframe." }, { "code": null, "e": 26588, "s": 26551, "text": "Syntax: DataFrame.get_dtype_counts()" }, { "code": null, "e": 26635, "s": 26588, "text": "Returns : value : Series : Counts of datatypes" }, { "code": null, "e": 26681, "s": 26635, "text": "For link to CSV file Used in Code, click here" }, { "code": null, "e": 26786, "s": 26681, "text": "Example #1: Use get_dtype_counts() function to find the counts of datatype of a pandas dataframe object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf", "e": 26909, "s": 26786, "text": null }, { "code": null, "e": 27025, "s": 26909, "text": "Now apply the get_dtype_counts() function. Find out the frequency of occurrence of each data type in the dataframe." }, { "code": "# applying get_dtype_counts() function df.get_dtype_counts()", "e": 27086, "s": 27025, "text": null }, { "code": null, "e": 27095, "s": 27086, "text": "Output :" }, { "code": null, "e": 27199, "s": 27095, "text": "Notice, the output is a pandas series object containing the count of each data types in the dataframe. " }, { "code": null, "e": 27298, "s": 27199, "text": "Example #2: Use get_dtype_counts() function over a selected no. of columns of the data frame only." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Applying get_dtype_counts() function to # find the data type counts in modified dataframe.df[[\"Salary\", \"Name\", \"Team\"]].get_dtype_counts()", "e": 27539, "s": 27298, "text": null }, { "code": null, "e": 27716, "s": 27539, "text": "Notice, the output is a pandas series object containing the count of each data types in the dataframe. We can verify all these results using this the dataframe.info() function." }, { "code": "# Find out the types of all columns in the dataframedf.info()", "e": 27778, "s": 27716, "text": null }, { "code": null, "e": 27787, "s": 27778, "text": "Output :" }, { "code": null, "e": 27811, "s": 27787, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27843, "s": 27811, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27850, "s": 27843, "text": "Python" }, { "code": null, "e": 27948, "s": 27850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27980, "s": 27948, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28022, "s": 27980, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28064, "s": 28022, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28120, "s": 28064, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28147, "s": 28120, "text": "Python Classes and Objects" }, { "code": null, "e": 28169, "s": 28147, "text": "Defaultdict in Python" }, { "code": null, "e": 28198, "s": 28169, "text": "Create a directory in Python" }, { "code": null, "e": 28229, "s": 28198, "text": "Python | os.path.join() method" }, { "code": null, "e": 28265, "s": 28229, "text": "Python | Pandas dataframe.groupby()" } ]
Alphanumeric sorting using JavaScript
We have a mixed array that we need to sort by alphabet and then by digit − const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105']; The code for this will be − const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105']; const alphaNumericSort = (arr = []) => { arr.sort((a, b) => { const aPart = a.split('-'); const bPart = b.split('-'); return aPart[0].toLowerCase().localeCompare(bPart[0].toLowerCase()) || aPart[1] - bPart[1]; }); }; alphaNumericSort(arr); console.log(arr); And the output in the console will be − [ 'Ab-1', 'ab-2', 'ab-3', 'ab-10', 'Ab-11', 'Ab-12', 'ab-100', 'ab-101', 'ab-105' ]
[ { "code": null, "e": 1137, "s": 1062, "text": "We have a mixed array that we need to sort by alphabet and then by digit −" }, { "code": null, "e": 1231, "s": 1137, "text": "const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];" }, { "code": null, "e": 1259, "s": 1231, "text": "The code for this will be −" }, { "code": null, "e": 1635, "s": 1259, "text": "const arr = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab2', 'ab-3', 'ab-105'];\nconst alphaNumericSort = (arr = []) => {\n arr.sort((a, b) => {\n const aPart = a.split('-');\n const bPart = b.split('-');\n return aPart[0].toLowerCase().localeCompare(bPart[0].toLowerCase()) || aPart[1] - bPart[1];\n });\n};\nalphaNumericSort(arr);\nconsole.log(arr);" }, { "code": null, "e": 1675, "s": 1635, "text": "And the output in the console will be −" }, { "code": null, "e": 1774, "s": 1675, "text": "[\n 'Ab-1', 'ab-2',\n 'ab-3', 'ab-10',\n 'Ab-11', 'Ab-12',\n 'ab-100', 'ab-101',\n 'ab-105'\n]" } ]
Scraping Twitter data using python for NLP | by Anshaj Khare | Towards Data Science
“In God we trust. All others must bring data.” — W. Edwards Deming If you’re starting in the incredible field of NLP, you’ll want to get your hands dirty with real textual data that you can use to play around with the concepts you’ve learned. Twitter is an excellent source of such data. In this post, I’ll be presenting a scraper that you can use to scrape the tweets of the topics that you’re interested in and get all nerdy once you’ve obtained your dataset. I’ve used this amazing library that you can find here. I’ll go over how to install and use this library and also suggest some methods to make the entire process faster using parallelization. The library can be installed using pip3 using the following command pip3 install twitter_scraper The next task is to create a list of keywords that you want to use for scraping twitter. You’ll be searching twitter for these keywords and hence it is important that you make a comprehensive list of keywords that you’re interested in. Before we run our program to extract all the keywords, we’ll run our program with one keyword and print out the fields that we can extract from the object. In the code below, I’ve shown how to iterate over the returned object and print out the fields that you want to extract. You can see that we have the following fields that we extract Tweet IDIs a retweet or notTime of the tweetText of the tweetReplies to the tweetTotal retweetsLikes to the tweetEntries in the tweet Tweet ID Is a retweet or not Time of the tweet Text of the tweet Replies to the tweet Total retweets Likes to the tweet Entries in the tweet Now that we’ve decided what kind of data we want to store from our object, we’ll run our program sequentially to obtain the tweets of topics we’re interested in. We’ll do this using our familiar for loop to go over each keyword one by one and store the successful results. From the documentation, Multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. First, we’ll implement a function to scrape the data. Next, we’ll create subprocesses to run our code in parallel. As you can see, we reduced our process time to almost 1/4th of sequential execution. You can use this method for similar tasks and make your python code much faster.
[ { "code": null, "e": 239, "s": 172, "text": "“In God we trust. All others must bring data.” — W. Edwards Deming" }, { "code": null, "e": 634, "s": 239, "text": "If you’re starting in the incredible field of NLP, you’ll want to get your hands dirty with real textual data that you can use to play around with the concepts you’ve learned. Twitter is an excellent source of such data. In this post, I’ll be presenting a scraper that you can use to scrape the tweets of the topics that you’re interested in and get all nerdy once you’ve obtained your dataset." }, { "code": null, "e": 825, "s": 634, "text": "I’ve used this amazing library that you can find here. I’ll go over how to install and use this library and also suggest some methods to make the entire process faster using parallelization." }, { "code": null, "e": 893, "s": 825, "text": "The library can be installed using pip3 using the following command" }, { "code": null, "e": 922, "s": 893, "text": "pip3 install twitter_scraper" }, { "code": null, "e": 1158, "s": 922, "text": "The next task is to create a list of keywords that you want to use for scraping twitter. You’ll be searching twitter for these keywords and hence it is important that you make a comprehensive list of keywords that you’re interested in." }, { "code": null, "e": 1497, "s": 1158, "text": "Before we run our program to extract all the keywords, we’ll run our program with one keyword and print out the fields that we can extract from the object. In the code below, I’ve shown how to iterate over the returned object and print out the fields that you want to extract. You can see that we have the following fields that we extract" }, { "code": null, "e": 1631, "s": 1497, "text": "Tweet IDIs a retweet or notTime of the tweetText of the tweetReplies to the tweetTotal retweetsLikes to the tweetEntries in the tweet" }, { "code": null, "e": 1640, "s": 1631, "text": "Tweet ID" }, { "code": null, "e": 1660, "s": 1640, "text": "Is a retweet or not" }, { "code": null, "e": 1678, "s": 1660, "text": "Time of the tweet" }, { "code": null, "e": 1696, "s": 1678, "text": "Text of the tweet" }, { "code": null, "e": 1717, "s": 1696, "text": "Replies to the tweet" }, { "code": null, "e": 1732, "s": 1717, "text": "Total retweets" }, { "code": null, "e": 1751, "s": 1732, "text": "Likes to the tweet" }, { "code": null, "e": 1772, "s": 1751, "text": "Entries in the tweet" }, { "code": null, "e": 2045, "s": 1772, "text": "Now that we’ve decided what kind of data we want to store from our object, we’ll run our program sequentially to obtain the tweets of topics we’re interested in. We’ll do this using our familiar for loop to go over each keyword one by one and store the successful results." }, { "code": null, "e": 2069, "s": 2045, "text": "From the documentation," }, { "code": null, "e": 2463, "s": 2069, "text": "Multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine." }, { "code": null, "e": 2517, "s": 2463, "text": "First, we’ll implement a function to scrape the data." }, { "code": null, "e": 2578, "s": 2517, "text": "Next, we’ll create subprocesses to run our code in parallel." } ]
How to convert a string into integer in JavaScript?
To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn’t contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces. If any particular number with spaces is sent then the part of the number that presents before space will be returned as the output. parseInt(value); This function takes a string and converts it into an integer. If there is no integer present in the string, NaN will be the output. In the following example, various cases of strings such as only strings, strings with numbers, etc have been taken and sent through the parseInt() function. Later on, their integer values, if present, have displayed as shown in the output. <html> <body> <script> var a = "10"; var b = parseInt(a); document.write("value is " + b); var c = parseInt("423-0-567"); document.write("</br>"); document.write('value is ' + c); document.write("</br>"); var d = "string"; var e = parseInt(d); document.write("value is " + e); document.write("</br>"); var f = parseInt("2string"); document.write("value is " + f); </script> </body> </html> value is 10 value is 423 value is NaN value is 2
[ { "code": null, "e": 1481, "s": 1062, "text": "To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn’t contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces. If any particular number with spaces is sent then the part of the number that presents before space will be returned as the output." }, { "code": null, "e": 1498, "s": 1481, "text": "parseInt(value);" }, { "code": null, "e": 1630, "s": 1498, "text": "This function takes a string and converts it into an integer. If there is no integer present in the string, NaN will be the output." }, { "code": null, "e": 1870, "s": 1630, "text": "In the following example, various cases of strings such as only strings, strings with numbers, etc have been taken and sent through the parseInt() function. Later on, their integer values, if present, have displayed as shown in the output." }, { "code": null, "e": 2299, "s": 1870, "text": "<html>\n<body>\n<script>\n var a = \"10\";\n var b = parseInt(a);\n document.write(\"value is \" + b);\n var c = parseInt(\"423-0-567\");\n document.write(\"</br>\");\n document.write('value is ' + c);\n document.write(\"</br>\");\n var d = \"string\";\n var e = parseInt(d);\n document.write(\"value is \" + e);\n document.write(\"</br>\");\n var f = parseInt(\"2string\");\n document.write(\"value is \" + f);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2348, "s": 2299, "text": "value is 10\nvalue is 423\nvalue is NaN\nvalue is 2" } ]
Arduino - nested loop
C language allows you to use one loop inside another loop. The following example illustrates the concept. for ( initialize ;control; increment or decrement) { // statement block for ( initialize ;control; increment or decrement) { // statement block } } for(counter = 0;counter <= 9;counter++) { //statements block will executed 10 times for(i = 0;i <= 99;i++) { //statements block will executed 100 times } } 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2976, "s": 2870, "text": "C language allows you to use one loop inside another loop. The following example illustrates the concept." }, { "code": null, "e": 3140, "s": 2976, "text": "for ( initialize ;control; increment or decrement) {\n // statement block\n for ( initialize ;control; increment or decrement) {\n // statement block\n }\n}\n" }, { "code": null, "e": 3311, "s": 3140, "text": "for(counter = 0;counter <= 9;counter++) {\n //statements block will executed 10 times\n for(i = 0;i <= 99;i++) {\n //statements block will executed 100 times\n }\n}" }, { "code": null, "e": 3346, "s": 3311, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3357, "s": 3346, "text": " Amit Rana" }, { "code": null, "e": 3390, "s": 3357, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3401, "s": 3390, "text": " Amit Rana" }, { "code": null, "e": 3434, "s": 3401, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3447, "s": 3434, "text": " Ashraf Said" }, { "code": null, "e": 3482, "s": 3447, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3495, "s": 3482, "text": " Ashraf Said" }, { "code": null, "e": 3527, "s": 3495, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 3540, "s": 3527, "text": " Ashraf Said" }, { "code": null, "e": 3571, "s": 3540, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3584, "s": 3571, "text": " Ashraf Said" }, { "code": null, "e": 3591, "s": 3584, "text": " Print" }, { "code": null, "e": 3602, "s": 3591, "text": " Add Notes" } ]
How to copy a section of one Array to another in C#?
The Array.Copy() method in C# is used to copy section of one array to another array. The following is the syntax − Array.Copy(src, dest, length); Here, src = array to be copied src = array to be copied dest = destination array dest = destination array length = how many elements to copy length = how many elements to copy The following is an example showing the usage of Copy(,,) method of array class in C# − using System; class Program { static void Main() { int[] arrSource = new int[4]; arrSource[0] = 1; arrSource[1] = 2; arrSource[2] = 3; arrSource[3] = 4; int[] arrTarget = new int[2]; Array.Copy(arrSource, arrTarget, 2); Console.WriteLine("Destination Array ..."); foreach (int value in arrTarget) { Console.WriteLine(value); } } }
[ { "code": null, "e": 1147, "s": 1062, "text": "The Array.Copy() method in C# is used to copy section of one array to another array." }, { "code": null, "e": 1177, "s": 1147, "text": "The following is the syntax −" }, { "code": null, "e": 1208, "s": 1177, "text": "Array.Copy(src, dest, length);" }, { "code": null, "e": 1214, "s": 1208, "text": "Here," }, { "code": null, "e": 1239, "s": 1214, "text": "src = array to be copied" }, { "code": null, "e": 1264, "s": 1239, "text": "src = array to be copied" }, { "code": null, "e": 1289, "s": 1264, "text": "dest = destination array" }, { "code": null, "e": 1314, "s": 1289, "text": "dest = destination array" }, { "code": null, "e": 1349, "s": 1314, "text": "length = how many elements to copy" }, { "code": null, "e": 1384, "s": 1349, "text": "length = how many elements to copy" }, { "code": null, "e": 1472, "s": 1384, "text": "The following is an example showing the usage of Copy(,,) method of array class in C# −" }, { "code": null, "e": 1882, "s": 1472, "text": "using System;\n\nclass Program {\n static void Main() {\n int[] arrSource = new int[4];\n arrSource[0] = 1;\n arrSource[1] = 2;\n arrSource[2] = 3;\n arrSource[3] = 4;\n\n int[] arrTarget = new int[2];\n\n Array.Copy(arrSource, arrTarget, 2);\n\n Console.WriteLine(\"Destination Array ...\");\n foreach (int value in arrTarget) {\n Console.WriteLine(value);\n }\n }\n}" } ]
Return the Index label if some condition is satisfied over a column in Pandas Dataframe
26 Jan, 2019 Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column. Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition. # importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'], 'Last_Price':[1200, 1500, 1600, 352], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 10, 10, 10]}) # Create the indexesdf.index =['Item 1', 'Item 2', 'Item 3', 'Item 4'] # Print the dataframeprint(df) Output : Now, we want to find out the index labels of all items whose ‘Updated_Price’ is greater than 1000. # Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df[df['Updated Price']>1000].index.tolist() # Print all the labelsprint(Index_label) Output :As we can see in the output, the above operation has successfully evaluated all the values and has returned a list containing the index labels. Solution #2: We can use Pandas Dataframe.query() function to select all the rows which satisfies some condition over a given column. # importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'], 'Last_Price':[1200, 1500, 1600, 352], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 10, 10, 10]}) # Create the indexesdf.index =['Item 1', 'Item 2', 'Item 3', 'Item 4'] # Print the dataframeprint(df) Output : Now, we want to find out the index labels of all items whose ‘Updated_Price’ is greater than 1000. # Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df.query('Updated_Price > 1000').index.tolist() # Print all the labelsprint(Index_label) Output : pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jan, 2019" }, { "code": null, "e": 139, "s": 28, "text": "Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column." }, { "code": null, "e": 267, "s": 139, "text": "Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition." }, { "code": "# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'], 'Last_Price':[1200, 1500, 1600, 352], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 10, 10, 10]}) # Create the indexesdf.index =['Item 1', 'Item 2', 'Item 3', 'Item 4'] # Print the dataframeprint(df)", "e": 758, "s": 267, "text": null }, { "code": null, "e": 767, "s": 758, "text": "Output :" }, { "code": null, "e": 866, "s": 767, "text": "Now, we want to find out the index labels of all items whose ‘Updated_Price’ is greater than 1000." }, { "code": "# Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df[df['Updated Price']>1000].index.tolist() # Print all the labelsprint(Index_label)", "e": 1065, "s": 866, "text": null }, { "code": null, "e": 1350, "s": 1065, "text": "Output :As we can see in the output, the above operation has successfully evaluated all the values and has returned a list containing the index labels. Solution #2: We can use Pandas Dataframe.query() function to select all the rows which satisfies some condition over a given column." }, { "code": "# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'], 'Last_Price':[1200, 1500, 1600, 352], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 10, 10, 10]}) # Create the indexesdf.index =['Item 1', 'Item 2', 'Item 3', 'Item 4'] # Print the dataframeprint(df)", "e": 1841, "s": 1350, "text": null }, { "code": null, "e": 1850, "s": 1841, "text": "Output :" }, { "code": null, "e": 1949, "s": 1850, "text": "Now, we want to find out the index labels of all items whose ‘Updated_Price’ is greater than 1000." }, { "code": "# Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df.query('Updated_Price > 1000').index.tolist() # Print all the labelsprint(Index_label)", "e": 2152, "s": 1949, "text": null }, { "code": null, "e": 2161, "s": 2152, "text": "Output :" }, { "code": null, "e": 2186, "s": 2161, "text": "pandas-dataframe-program" }, { "code": null, "e": 2210, "s": 2186, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2224, "s": 2210, "text": "Python-pandas" }, { "code": null, "e": 2231, "s": 2224, "text": "Python" } ]
How to unset JavaScript variables?
22 Apr, 2019 To know how to unset a variable we must know what are JS variables and how to declare a variable first. JavaScript variables are containers for storing data values. Variables can be declared using the ‘var’ keyword. Example: var x = 5; In the above code declaration, the value 5 has been assigned to the variable ‘x’. The unsetting of a variable means to destroy it once its purpose in the code has been fulfilled. Here a question arises, do we really need to unset the variables in JavaScript once their job is done?The answer is ‘No’. Also, it should be kept in mind that, variables set in the global scope cannot be deleted. It is advised to use var to declare variables in JS, however, the property declared using var keyword cannot be deleted as well. However, if the variable x was defined without using the ‘var’ keyword, then deleting it would have been possible using this method. nxt = undefined; // window is used in JS to access// the global variableswindow.nxt = 'I am next'; delete window.nxt; As far as memory management goes, the JavaScript interpreter performs automatic garbage collection for memory management. The job of a garbage collector is to track memory allocation and find when a piece of the allocated memory is no longer needed, in such a case the memory will be freed automatically. The ‘Garbage Collector’ frees the programmer from the worries of the destruction or reallocation of the objects. Also, as already mentioned above, the variable cannot be destroyed in JavaScript. So, what could be done now? Some developers may suggest using ‘delete’, but the delete operator removes a property from an object. It cannot remove a variable. So what’s the closest thing that can be done to unset a variable in JS? We cannot undeclare a variable. However, we can set its value to undefined for the purpose nxt = undefined; Example 1: This example describes delete keywords when var is not used. <script>x = 20;delete x;console.log(x);</script> Output: There will be no output in the console, as x gets deleted in this case. However, when var will be used to declare the value of x, the delete function will not work. Example 2: The delete doesn’t work when var is used. <script>var x = 20;delete x;console.log(x);</script> Output:The console will display output as 20. ‘var’ has been used to initialize the value of x and thus ‘delete’ function will not work in this case. JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2019" }, { "code": null, "e": 268, "s": 52, "text": "To know how to unset a variable we must know what are JS variables and how to declare a variable first. JavaScript variables are containers for storing data values. Variables can be declared using the ‘var’ keyword." }, { "code": null, "e": 277, "s": 268, "text": "Example:" }, { "code": "var x = 5;", "e": 288, "s": 277, "text": null }, { "code": null, "e": 467, "s": 288, "text": "In the above code declaration, the value 5 has been assigned to the variable ‘x’. The unsetting of a variable means to destroy it once its purpose in the code has been fulfilled." }, { "code": null, "e": 942, "s": 467, "text": "Here a question arises, do we really need to unset the variables in JavaScript once their job is done?The answer is ‘No’. Also, it should be kept in mind that, variables set in the global scope cannot be deleted. It is advised to use var to declare variables in JS, however, the property declared using var keyword cannot be deleted as well. However, if the variable x was defined without using the ‘var’ keyword, then deleting it would have been possible using this method." }, { "code": "nxt = undefined; // window is used in JS to access// the global variableswindow.nxt = 'I am next'; delete window.nxt;", "e": 1062, "s": 942, "text": null }, { "code": null, "e": 1480, "s": 1062, "text": "As far as memory management goes, the JavaScript interpreter performs automatic garbage collection for memory management. The job of a garbage collector is to track memory allocation and find when a piece of the allocated memory is no longer needed, in such a case the memory will be freed automatically. The ‘Garbage Collector’ frees the programmer from the worries of the destruction or reallocation of the objects." }, { "code": null, "e": 1794, "s": 1480, "text": "Also, as already mentioned above, the variable cannot be destroyed in JavaScript. So, what could be done now? Some developers may suggest using ‘delete’, but the delete operator removes a property from an object. It cannot remove a variable. So what’s the closest thing that can be done to unset a variable in JS?" }, { "code": null, "e": 1885, "s": 1794, "text": "We cannot undeclare a variable. However, we can set its value to undefined for the purpose" }, { "code": "nxt = undefined;", "e": 1902, "s": 1885, "text": null }, { "code": null, "e": 1974, "s": 1902, "text": "Example 1: This example describes delete keywords when var is not used." }, { "code": "<script>x = 20;delete x;console.log(x);</script>", "e": 2023, "s": 1974, "text": null }, { "code": null, "e": 2031, "s": 2023, "text": "Output:" }, { "code": null, "e": 2196, "s": 2031, "text": "There will be no output in the console, as x gets deleted in this case. However, when var will be used to declare the value of x, the delete function will not work." }, { "code": null, "e": 2249, "s": 2196, "text": "Example 2: The delete doesn’t work when var is used." }, { "code": "<script>var x = 20;delete x;console.log(x);</script>", "e": 2302, "s": 2249, "text": null }, { "code": null, "e": 2452, "s": 2302, "text": "Output:The console will display output as 20. ‘var’ has been used to initialize the value of x and thus ‘delete’ function will not work in this case." }, { "code": null, "e": 2468, "s": 2452, "text": "JavaScript-Misc" }, { "code": null, "e": 2475, "s": 2468, "text": "Picked" }, { "code": null, "e": 2486, "s": 2475, "text": "JavaScript" }, { "code": null, "e": 2503, "s": 2486, "text": "Web Technologies" }, { "code": null, "e": 2530, "s": 2503, "text": "Web technologies Questions" } ]
HTML | <script> async Attribute
02 Jun, 2022 The HTML,<script> async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously when it is available. This attribute only works for external scripts (and used only in when src attribute is present ).Note: There are so many ways in which external script execute: when async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) when async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately before the browser continues parsing the page Syntax: <script async> Example: Index.html html <!DOCTYPE html><html> <body> <center> <h1 style="color:green"> Geeksforgeeks </h1> <p id="p1">Hello GFG</p> <script src="geeks.js" async></script> </center></body> </html> geeks.js javascript alert("Hello GFG"); Output: Supported Browsers: The browsers supported by HTML <script> async attribute are listed below Google Chrome 1.0 and above Edge 12 and above Firefox 1 and above Apple Safari Opera Internet Explorer simmytarika5 kumargaurav97520 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2022" }, { "code": null, "e": 345, "s": 28, "text": "The HTML,<script> async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously when it is available. This attribute only works for external scripts (and used only in when src attribute is present ).Note: There are so many ways in which external script execute: " }, { "code": null, "e": 499, "s": 345, "text": "when async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)" }, { "code": null, "e": 605, "s": 499, "text": "when async is not present and defer is present: The script is executed when the page has finished parsing" }, { "code": null, "e": 736, "s": 605, "text": "If neither async or defer is present: The script is fetched and executed immediately before the browser continues parsing the page" }, { "code": null, "e": 746, "s": 736, "text": "Syntax: " }, { "code": null, "e": 761, "s": 746, "text": "<script async>" }, { "code": null, "e": 783, "s": 761, "text": "Example: Index.html " }, { "code": null, "e": 788, "s": 783, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> Geeksforgeeks </h1> <p id=\"p1\">Hello GFG</p> <script src=\"geeks.js\" async></script> </center></body> </html>", "e": 1003, "s": 788, "text": null }, { "code": null, "e": 1014, "s": 1003, "text": "geeks.js " }, { "code": null, "e": 1025, "s": 1014, "text": "javascript" }, { "code": "alert(\"Hello GFG\"); ", "e": 1046, "s": 1025, "text": null }, { "code": null, "e": 1056, "s": 1046, "text": "Output: " }, { "code": null, "e": 1151, "s": 1056, "text": "Supported Browsers: The browsers supported by HTML <script> async attribute are listed below " }, { "code": null, "e": 1179, "s": 1151, "text": "Google Chrome 1.0 and above" }, { "code": null, "e": 1197, "s": 1179, "text": "Edge 12 and above" }, { "code": null, "e": 1217, "s": 1197, "text": "Firefox 1 and above" }, { "code": null, "e": 1231, "s": 1217, "text": "Apple Safari " }, { "code": null, "e": 1238, "s": 1231, "text": "Opera " }, { "code": null, "e": 1256, "s": 1238, "text": "Internet Explorer" }, { "code": null, "e": 1271, "s": 1258, "text": "simmytarika5" }, { "code": null, "e": 1288, "s": 1271, "text": "kumargaurav97520" }, { "code": null, "e": 1304, "s": 1288, "text": "HTML-Attributes" }, { "code": null, "e": 1309, "s": 1304, "text": "HTML" }, { "code": null, "e": 1326, "s": 1309, "text": "Web Technologies" }, { "code": null, "e": 1331, "s": 1326, "text": "HTML" } ]
How to call a function repeatedly every 5 seconds in JavaScript ?
13 Dec, 2021 The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function. Syntax: setInterval(function, milliseconds, param1, param2, ...) Parameters: This function accepts the following parameters: function: This parameter holds the function name which to be called periodically. milliseconds: This parameter holds the period, in milliseconds, setInterval() calls/executes the function above. param1, param2, ... : Some additional parameters to be passed as input parameters to function. Return Value: This method returns the ID representing timer set by the method. This ID can be used to clear/unset the timer by calling clearInterval() method and passing it this ID as a parameter.Example: Suppose we want to create a reminder timer which goes off every 5 seconds and alerts through a JavaScript alert box. javascript <!DOCTYPE html><html> <head> <title> How to call a function repeatedly every 5 seconds in JavaScript ? </title></head> <body> <p> Click the button to start timer, you will be alerted every 5 seconds until you close the window or press the button to stop timer </p> <button onclick="startTimer()"> Start Timer </button> <button onclick="stopTimer()"> Stop Timer </button> <script> var timer; function startTimer() { timer = setInterval(function() { alert("5 seconds are up"); }, 5000); } function stopTimer() { alert("Timer stopped"); clearInterval(timer); } </script></body> </html> Output: Before clicking the button: After clicking the button: In the above example, the setInterval() method repeatedly evaluates an expression/calls a function. The way to clear/unset the timer set by setInterval() method is to use the clearInterval() method and passing it the ID/value returned on calling setInterval(). akshaysingh98088 ruhelaa48 JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Dec, 2021" }, { "code": null, "e": 164, "s": 28, "text": "The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function. Syntax: " }, { "code": null, "e": 221, "s": 164, "text": "setInterval(function, milliseconds, param1, param2, ...)" }, { "code": null, "e": 283, "s": 221, "text": "Parameters: This function accepts the following parameters: " }, { "code": null, "e": 365, "s": 283, "text": "function: This parameter holds the function name which to be called periodically." }, { "code": null, "e": 478, "s": 365, "text": "milliseconds: This parameter holds the period, in milliseconds, setInterval() calls/executes the function above." }, { "code": null, "e": 573, "s": 478, "text": "param1, param2, ... : Some additional parameters to be passed as input parameters to function." }, { "code": null, "e": 895, "s": 573, "text": "Return Value: This method returns the ID representing timer set by the method. This ID can be used to clear/unset the timer by calling clearInterval() method and passing it this ID as a parameter.Example: Suppose we want to create a reminder timer which goes off every 5 seconds and alerts through a JavaScript alert box." }, { "code": null, "e": 906, "s": 895, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <title> How to call a function repeatedly every 5 seconds in JavaScript ? </title></head> <body> <p> Click the button to start timer, you will be alerted every 5 seconds until you close the window or press the button to stop timer </p> <button onclick=\"startTimer()\"> Start Timer </button> <button onclick=\"stopTimer()\"> Stop Timer </button> <script> var timer; function startTimer() { timer = setInterval(function() { alert(\"5 seconds are up\"); }, 5000); } function stopTimer() { alert(\"Timer stopped\"); clearInterval(timer); } </script></body> </html>", "e": 1720, "s": 906, "text": null }, { "code": null, "e": 1730, "s": 1720, "text": "Output: " }, { "code": null, "e": 1760, "s": 1730, "text": "Before clicking the button: " }, { "code": null, "e": 1789, "s": 1760, "text": "After clicking the button: " }, { "code": null, "e": 2050, "s": 1789, "text": "In the above example, the setInterval() method repeatedly evaluates an expression/calls a function. The way to clear/unset the timer set by setInterval() method is to use the clearInterval() method and passing it the ID/value returned on calling setInterval()." }, { "code": null, "e": 2067, "s": 2050, "text": "akshaysingh98088" }, { "code": null, "e": 2077, "s": 2067, "text": "ruhelaa48" }, { "code": null, "e": 2093, "s": 2077, "text": "JavaScript-Misc" }, { "code": null, "e": 2100, "s": 2093, "text": "Picked" }, { "code": null, "e": 2111, "s": 2100, "text": "JavaScript" }, { "code": null, "e": 2128, "s": 2111, "text": "Web Technologies" }, { "code": null, "e": 2155, "s": 2128, "text": "Web technologies Questions" } ]
Python program to find largest number in a list
08 Jun, 2022 Given a list of numbers, the task is to write a Python program to find the largest number in given list. Examples: Input : list1 = [10, 20, 4] Output : 20 Input : list2 = [20, 10, 20, 4, 100] Output : 100 Method 1 : Sort the list in ascending order and print the last element in the list. Python3 # Python program to find largest# number in a list # list of numberslist1 = [10, 20, 4, 45, 99] # sorting the listlist1.sort() # printing the last elementprint("Largest element is:", list1[-1]) Largest element is: 99 Method 2 : Using max() method Python3 # Python program to find largest# number in a list # list of numberslist1 = [10, 20, 4, 45, 99] # printing the maximum elementprint("Largest element is:", max(list1)) 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. Largest element is: 99 Method 3 : Find max list element on inputs provided by user Python3 # Python program to find largest# number in a list # creating empty listlist1 = [] # asking number of elements to put in listnum = int(input("Enter number of elements in list: ")) # iterating till num to append elements in listfor i in range(1, num + 1): ele = int(input("Enter elements: ")) list1.append(ele) # print maximum elementprint("Largest element is:", max(list1)) Output: Enter number of elements in list: 4 Enter elements: 12 Enter elements: 19 Enter elements: 1 Enter elements: 99 Largest element is: 99 Method 4 : Without using built in functions in python: Python3 # Python program to find largest# number in a list def myMax(list1): # Assume first number in list is largest # initially and assign it to variable "max" max = list1[0] # Now traverse through the list and compare # each number with "max" value. Whichever is # largest assign that value to "max'. for x in list1: if x > max : max = x # after complete traversing the list # return the "max" value return max # Driver codelist1 = [10, 20, 4, 45, 99]print("Largest element is:", myMax(list1)) Largest element is: 99 Method: Use the max() and def functions to find the largest element in a given list. The max() function prints the largest element in the list. Python3 # Python code# To find the largest number in a list def maxelement(lst): # displaying largest element # one line solution print(max(lst)) # driver code# input listlst = [20, 10, 20, 4, 100]# the above input can also be given as# lst = list(map(int, input().split())) # -> taking input from the usermaxelement(lst) # this code is contributed by gangarajula laxmi 100 inboxofanirban laxmigangarajula03 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 167, "s": 52, "text": "Given a list of numbers, the task is to write a Python program to find the largest number in given list. Examples:" }, { "code": null, "e": 258, "s": 167, "text": "Input : list1 = [10, 20, 4]\nOutput : 20\n\nInput : list2 = [20, 10, 20, 4, 100]\nOutput : 100" }, { "code": null, "e": 343, "s": 258, "text": "Method 1 : Sort the list in ascending order and print the last element in the list. " }, { "code": null, "e": 351, "s": 343, "text": "Python3" }, { "code": "# Python program to find largest# number in a list # list of numberslist1 = [10, 20, 4, 45, 99] # sorting the listlist1.sort() # printing the last elementprint(\"Largest element is:\", list1[-1])", "e": 545, "s": 351, "text": null }, { "code": null, "e": 568, "s": 545, "text": "Largest element is: 99" }, { "code": null, "e": 599, "s": 568, "text": "Method 2 : Using max() method " }, { "code": null, "e": 607, "s": 599, "text": "Python3" }, { "code": "# Python program to find largest# number in a list # list of numberslist1 = [10, 20, 4, 45, 99] # printing the maximum elementprint(\"Largest element is:\", max(list1))", "e": 775, "s": 607, "text": null }, { "code": null, "e": 784, "s": 775, "text": "Chapters" }, { "code": null, "e": 811, "s": 784, "text": "descriptions off, selected" }, { "code": null, "e": 861, "s": 811, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 884, "s": 861, "text": "captions off, selected" }, { "code": null, "e": 892, "s": 884, "text": "English" }, { "code": null, "e": 916, "s": 892, "text": "This is a modal window." }, { "code": null, "e": 985, "s": 916, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1007, "s": 985, "text": "End of dialog window." }, { "code": null, "e": 1030, "s": 1007, "text": "Largest element is: 99" }, { "code": null, "e": 1091, "s": 1030, "text": "Method 3 : Find max list element on inputs provided by user " }, { "code": null, "e": 1099, "s": 1091, "text": "Python3" }, { "code": "# Python program to find largest# number in a list # creating empty listlist1 = [] # asking number of elements to put in listnum = int(input(\"Enter number of elements in list: \")) # iterating till num to append elements in listfor i in range(1, num + 1): ele = int(input(\"Enter elements: \")) list1.append(ele) # print maximum elementprint(\"Largest element is:\", max(list1))", "e": 1483, "s": 1099, "text": null }, { "code": null, "e": 1491, "s": 1483, "text": "Output:" }, { "code": null, "e": 1625, "s": 1491, "text": "Enter number of elements in list: 4\nEnter elements: 12\nEnter elements: 19\nEnter elements: 1\nEnter elements: 99\nLargest element is: 99" }, { "code": null, "e": 1681, "s": 1625, "text": "Method 4 : Without using built in functions in python: " }, { "code": null, "e": 1689, "s": 1681, "text": "Python3" }, { "code": "# Python program to find largest# number in a list def myMax(list1): # Assume first number in list is largest # initially and assign it to variable \"max\" max = list1[0] # Now traverse through the list and compare # each number with \"max\" value. Whichever is # largest assign that value to \"max'. for x in list1: if x > max : max = x # after complete traversing the list # return the \"max\" value return max # Driver codelist1 = [10, 20, 4, 45, 99]print(\"Largest element is:\", myMax(list1))", "e": 2231, "s": 1689, "text": null }, { "code": null, "e": 2254, "s": 2231, "text": "Largest element is: 99" }, { "code": null, "e": 2400, "s": 2254, "text": "Method: Use the max() and def functions to find the largest element in a given list. The max() function prints the largest element in the list. " }, { "code": null, "e": 2408, "s": 2400, "text": "Python3" }, { "code": "# Python code# To find the largest number in a list def maxelement(lst): # displaying largest element # one line solution print(max(lst)) # driver code# input listlst = [20, 10, 20, 4, 100]# the above input can also be given as# lst = list(map(int, input().split())) # -> taking input from the usermaxelement(lst) # this code is contributed by gangarajula laxmi", "e": 2774, "s": 2408, "text": null }, { "code": null, "e": 2778, "s": 2774, "text": "100" }, { "code": null, "e": 2793, "s": 2778, "text": "inboxofanirban" }, { "code": null, "e": 2812, "s": 2793, "text": "laxmigangarajula03" }, { "code": null, "e": 2833, "s": 2812, "text": "Python list-programs" }, { "code": null, "e": 2845, "s": 2833, "text": "python-list" }, { "code": null, "e": 2852, "s": 2845, "text": "Python" }, { "code": null, "e": 2868, "s": 2852, "text": "Python Programs" }, { "code": null, "e": 2880, "s": 2868, "text": "python-list" } ]
How to Access the File System in Node.js ?
19 Oct, 2021 In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6 Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses a single-threaded non-blocking I/O model. We can access the file system in NodeJS using some inbuilt modules. File System: A file is a collection of related information stored in secondary storage Or a file is a collection of similar types of entities that work with the file and manage it also called a File System. If you want to know more about the file system refer to this article. File System Module (fs module): One of the popular inbuilt modules for working with the file system in NodeJS is the file system module which is also called the “fs” module in short. fs module is very powerful for doing any task in NodeJS related to File systems. Access the File System in Node JS means performing some basic operations on files. This is also known as CRUD operations. CRUD Operations: C => Create the files R => Read the files U => Update the files D => Delete the file Basic operations on files using the “fs” module: Step 1: Create a file with “.js” extension. Step 2: Add the “fs” module to the codebase. Syntax: const fs = require('fs'); After required the fs module, you can perform the following operations on files: Operation 1: Create a File Syntax: const fs = require('fs'); fs.writeFileSync('./{file_name}', 'Content_For_Writing'); The fs.writeFileSync method is used to write something to the file, but if the file does not exist, it creates new files along with writing the contents. Operation 2: Read the File Syntax: const fs = require('fs'); const file_content = fs.readFileSync('./{file_name}', '{content_formate}').toString(); // For show the data on console console.log(file_content); The fs.readFileSync method is used to read data from a file, the first argument to readFileSync is the path to the file, and the second argument takes the options {format, flag, etc} and returns the buffer object of the stream. So we can use the buffer String assigned to a variable named file_content using toString() method and after assigning data to file_content the data is shown on the console using console.log() method. Operation 3: Update the File Syntax: const fs = require('fs'); fs.appendFileSync('./{file_name}', " {Updated_Data}"); const file_content = fs.readFileSync( './{file_name}', '{file_formate}').toString(); console.log(file_content); The fs.appendFileSync method is used for updating the data of a file. Operation 4: Delete a File const fs = require('fs'); fs.unlinkSync('./{file_name}'); The fs.unlinkSync() method is used to delete the file with passing the file name. Below is the code implementation for the above operations: Example:The filename is index.js Javascript const fs = require('fs'); /* The fs.writeFileSync method is usedto write something to the file, but ifthe file does not exist, it creates newfiles along with writing the contents */fs.writeFileSync('./testfile', 'This is a file');var file_content = fs.readFileSync( './testfile', 'utf8').toString(); console.log(file_content); /* The fs.appendFileSync method is usedfor updating the data of a file */fs.appendFileSync('./testfile', " Updated Data");file_content = fs.readFileSync( './testfile', 'utf8').toString();console.log(file_content); /* The fs.unlinkSync method are used to deletethe file. With passing the file name */fs.unlinkSync('./testfile'); Try Out the code and run it using node.js by using the following command: node index.js Finally, we saw how to access the file system and also tried many operations on it. arorakashish0911 gabaa406 Node.js-fs-module NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Oct, 2021" }, { "code": null, "e": 176, "s": 54, "text": "In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files." }, { "code": null, "e": 190, "s": 176, "text": "Prerequisite:" }, { "code": null, "e": 213, "s": 190, "text": "Basic knowledge of ES6" }, { "code": null, "e": 239, "s": 213, "text": "Basic knowledge of NodeJS" }, { "code": null, "e": 466, "s": 239, "text": "NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses a single-threaded non-blocking I/O model. We can access the file system in NodeJS using some inbuilt modules." }, { "code": null, "e": 674, "s": 466, "text": "File System: A file is a collection of related information stored in secondary storage Or a file is a collection of similar types of entities that work with the file and manage it also called a File System. " }, { "code": null, "e": 744, "s": 674, "text": "If you want to know more about the file system refer to this article." }, { "code": null, "e": 1008, "s": 744, "text": "File System Module (fs module): One of the popular inbuilt modules for working with the file system in NodeJS is the file system module which is also called the “fs” module in short. fs module is very powerful for doing any task in NodeJS related to File systems." }, { "code": null, "e": 1130, "s": 1008, "text": "Access the File System in Node JS means performing some basic operations on files. This is also known as CRUD operations." }, { "code": null, "e": 1147, "s": 1130, "text": "CRUD Operations:" }, { "code": null, "e": 1169, "s": 1147, "text": "C => Create the files" }, { "code": null, "e": 1189, "s": 1169, "text": "R => Read the files" }, { "code": null, "e": 1211, "s": 1189, "text": "U => Update the files" }, { "code": null, "e": 1232, "s": 1211, "text": "D => Delete the file" }, { "code": null, "e": 1281, "s": 1232, "text": "Basic operations on files using the “fs” module:" }, { "code": null, "e": 1325, "s": 1281, "text": "Step 1: Create a file with “.js” extension." }, { "code": null, "e": 1370, "s": 1325, "text": "Step 2: Add the “fs” module to the codebase." }, { "code": null, "e": 1378, "s": 1370, "text": "Syntax:" }, { "code": null, "e": 1404, "s": 1378, "text": "const fs = require('fs');" }, { "code": null, "e": 1485, "s": 1404, "text": "After required the fs module, you can perform the following operations on files:" }, { "code": null, "e": 1512, "s": 1485, "text": "Operation 1: Create a File" }, { "code": null, "e": 1520, "s": 1512, "text": "Syntax:" }, { "code": null, "e": 1604, "s": 1520, "text": "const fs = require('fs');\nfs.writeFileSync('./{file_name}', 'Content_For_Writing');" }, { "code": null, "e": 1758, "s": 1604, "text": "The fs.writeFileSync method is used to write something to the file, but if the file does not exist, it creates new files along with writing the contents." }, { "code": null, "e": 1785, "s": 1758, "text": "Operation 2: Read the File" }, { "code": null, "e": 1793, "s": 1785, "text": "Syntax:" }, { "code": null, "e": 1971, "s": 1793, "text": "const fs = require('fs');\nconst file_content = fs.readFileSync('./{file_name}', \n '{content_formate}').toString();\n\n// For show the data on console\nconsole.log(file_content);" }, { "code": null, "e": 2399, "s": 1971, "text": "The fs.readFileSync method is used to read data from a file, the first argument to readFileSync is the path to the file, and the second argument takes the options {format, flag, etc} and returns the buffer object of the stream. So we can use the buffer String assigned to a variable named file_content using toString() method and after assigning data to file_content the data is shown on the console using console.log() method." }, { "code": null, "e": 2428, "s": 2399, "text": "Operation 3: Update the File" }, { "code": null, "e": 2436, "s": 2428, "text": "Syntax:" }, { "code": null, "e": 2635, "s": 2436, "text": "const fs = require('fs');\nfs.appendFileSync('./{file_name}', \" {Updated_Data}\");\n\nconst file_content = fs.readFileSync(\n './{file_name}', '{file_formate}').toString();\n\nconsole.log(file_content);" }, { "code": null, "e": 2705, "s": 2635, "text": "The fs.appendFileSync method is used for updating the data of a file." }, { "code": null, "e": 2732, "s": 2705, "text": "Operation 4: Delete a File" }, { "code": null, "e": 2790, "s": 2732, "text": "const fs = require('fs');\nfs.unlinkSync('./{file_name}');" }, { "code": null, "e": 2872, "s": 2790, "text": "The fs.unlinkSync() method is used to delete the file with passing the file name." }, { "code": null, "e": 2931, "s": 2872, "text": "Below is the code implementation for the above operations:" }, { "code": null, "e": 2964, "s": 2931, "text": "Example:The filename is index.js" }, { "code": null, "e": 2975, "s": 2964, "text": "Javascript" }, { "code": "const fs = require('fs'); /* The fs.writeFileSync method is usedto write something to the file, but ifthe file does not exist, it creates newfiles along with writing the contents */fs.writeFileSync('./testfile', 'This is a file');var file_content = fs.readFileSync( './testfile', 'utf8').toString(); console.log(file_content); /* The fs.appendFileSync method is usedfor updating the data of a file */fs.appendFileSync('./testfile', \" Updated Data\");file_content = fs.readFileSync( './testfile', 'utf8').toString();console.log(file_content); /* The fs.unlinkSync method are used to deletethe file. With passing the file name */fs.unlinkSync('./testfile');", "e": 3640, "s": 2975, "text": null }, { "code": null, "e": 3714, "s": 3640, "text": "Try Out the code and run it using node.js by using the following command:" }, { "code": null, "e": 3728, "s": 3714, "text": "node index.js" }, { "code": null, "e": 3812, "s": 3728, "text": "Finally, we saw how to access the file system and also tried many operations on it." }, { "code": null, "e": 3829, "s": 3812, "text": "arorakashish0911" }, { "code": null, "e": 3838, "s": 3829, "text": "gabaa406" }, { "code": null, "e": 3856, "s": 3838, "text": "Node.js-fs-module" }, { "code": null, "e": 3873, "s": 3856, "text": "NodeJS-Questions" }, { "code": null, "e": 3880, "s": 3873, "text": "Picked" }, { "code": null, "e": 3888, "s": 3880, "text": "Node.js" }, { "code": null, "e": 3905, "s": 3888, "text": "Web Technologies" } ]
GATE | GATE-CS-2014-(Set-2) | Question 65
20 Jun, 2017 A FAT (file allocation table) based file system is being used and the total overhead of each entry in the FAT is 4 bytes in size. Given a 100 x 106 bytes disk on which the file system is stored and data block size is 103 bytes, the maximum size of a file that can be stored on this disk in units of 106 bytes is ____________. (A) 99.55 to 99.65(B) 100.5 to 101.4(C) 97.2 to 98.5(D) 89.1 to 91.2Answer: (A)Explanation: Here block size is 10^3 B. No. of entries in the FAT = Disk capacity/ Block size = 10^8/10^3 = 10^5 Total space consumed by FAT = 10^5 *4B = 0.4*10^6B Max. size of file that can be stored = 100*10^6-0.4*10^6 = 99.6*10^6B. So answer 99.6. Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2017" }, { "code": null, "e": 380, "s": 54, "text": "A FAT (file allocation table) based file system is being used and the total overhead of each entry in the FAT is 4 bytes in size. Given a 100 x 106 bytes disk on which the file system is stored and data block size is 103 bytes, the maximum size of a file that can be stored on this disk in units of 106 bytes is ____________." }, { "code": null, "e": 472, "s": 380, "text": "(A) 99.55 to 99.65(B) 100.5 to 101.4(C) 97.2 to 98.5(D) 89.1 to 91.2Answer: (A)Explanation:" }, { "code": null, "e": 830, "s": 472, "text": "Here block size is 10^3 B.\nNo. of entries in the FAT = Disk capacity/ Block size \n = 10^8/10^3 \n = 10^5\nTotal space consumed by FAT = 10^5 *4B \n = 0.4*10^6B\nMax. size of file that can be stored = 100*10^6-0.4*10^6\n = 99.6*10^6B.\nSo answer 99.6." }, { "code": null, "e": 852, "s": 830, "text": "Quiz of this Question" }, { "code": null, "e": 873, "s": 852, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 899, "s": 873, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 904, "s": 899, "text": "GATE" } ]
Check if two Dictionary objects are equal in C#
01 Feb, 2019 Equals(Object) Method which is inherited from the Object class is used to check if a specified Dictionary object is equal to another Dictionary object or not. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is to be compared with the current object. Return Value: This method return true if the specified object is equal to the current object otherwise it returns false. Below programs illustrate the use of above-discussed method: Example 1: // C# code to check if two// Dictionary are equal or notusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Dictionary named myDict Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // Checking whether myDict is // equal to itself or not Console.WriteLine(myDict.Equals(myDict)); }} True Example 2: // C# code to check if two// Dictionary are equal or notusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Dictionary named myDict Dictionary<string, string> myDict1 = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict1.Add("I", "first"); myDict1.Add("II", "second"); myDict1.Add("III", "third"); myDict1.Add("IV", "fourth"); myDict1.Add("V", "fifth"); // Creating a Dictionary named myDict2 Dictionary<string, string> myDict2 = new Dictionary<string, string>(); myDict2.Add("1st", "C"); myDict2.Add("2nd", "C++"); myDict2.Add("3rd", "Java"); myDict2.Add("4th", "C#"); myDict2.Add("5th", "HTML"); myDict2.Add("6th", "PHP"); // Checking whether myDict1 is // equal to myDict2 or not Console.WriteLine(myDict1.Equals(myDict2)); // Creating a new Dictionary Dictionary<string, string> myDict3 = new Dictionary<string, string>(); // Assigning myDict2 to myDict3 myDict3 = myDict2; // Checking whether myDict3 is // equal to myDict2 or not Console.WriteLine(myDict3.Equals(myDict2)); }} False True Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality. CSharp Dictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 187, "s": 28, "text": "Equals(Object) Method which is inherited from the Object class is used to check if a specified Dictionary object is equal to another Dictionary object or not." }, { "code": null, "e": 195, "s": 187, "text": "Syntax:" }, { "code": null, "e": 236, "s": 195, "text": "public virtual bool Equals (object obj);" }, { "code": null, "e": 309, "s": 236, "text": "Here, obj is the object which is to be compared with the current object." }, { "code": null, "e": 430, "s": 309, "text": "Return Value: This method return true if the specified object is equal to the current object otherwise it returns false." }, { "code": null, "e": 491, "s": 430, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 502, "s": 491, "text": "Example 1:" }, { "code": "// C# code to check if two// Dictionary are equal or notusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Dictionary named myDict Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // Checking whether myDict is // equal to itself or not Console.WriteLine(myDict.Equals(myDict)); }}", "e": 1231, "s": 502, "text": null }, { "code": null, "e": 1237, "s": 1231, "text": "True\n" }, { "code": null, "e": 1248, "s": 1237, "text": "Example 2:" }, { "code": "// C# code to check if two// Dictionary are equal or notusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Dictionary named myDict Dictionary<string, string> myDict1 = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict1.Add(\"I\", \"first\"); myDict1.Add(\"II\", \"second\"); myDict1.Add(\"III\", \"third\"); myDict1.Add(\"IV\", \"fourth\"); myDict1.Add(\"V\", \"fifth\"); // Creating a Dictionary named myDict2 Dictionary<string, string> myDict2 = new Dictionary<string, string>(); myDict2.Add(\"1st\", \"C\"); myDict2.Add(\"2nd\", \"C++\"); myDict2.Add(\"3rd\", \"Java\"); myDict2.Add(\"4th\", \"C#\"); myDict2.Add(\"5th\", \"HTML\"); myDict2.Add(\"6th\", \"PHP\"); // Checking whether myDict1 is // equal to myDict2 or not Console.WriteLine(myDict1.Equals(myDict2)); // Creating a new Dictionary Dictionary<string, string> myDict3 = new Dictionary<string, string>(); // Assigning myDict2 to myDict3 myDict3 = myDict2; // Checking whether myDict3 is // equal to myDict2 or not Console.WriteLine(myDict3.Equals(myDict2)); }}", "e": 2569, "s": 1248, "text": null }, { "code": null, "e": 2581, "s": 2569, "text": "False\nTrue\n" }, { "code": null, "e": 2689, "s": 2581, "text": "Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality." }, { "code": null, "e": 2713, "s": 2689, "text": "CSharp Dictionary Class" }, { "code": null, "e": 2738, "s": 2713, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 2752, "s": 2738, "text": "CSharp-method" }, { "code": null, "e": 2755, "s": 2752, "text": "C#" } ]
Minimum squares to evenly cut a rectangle
19 Jul, 2021 Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not minimum. If we make square with side of 2, then we have 6 squares. and this is our required answer. And also we can’t make square with side 3, if we select 3 as square side, then whole sheet can’t be converted into squares of equal length. Input :l=3 w=5 Output :15 Optimal length of the side of a square is equal to GCD of two numbers C++ Java Python3 C# PHP Javascript // CPP program to find minimum number of// squares to make a given rectangle.#include <bits/stdc++.h>using namespace std; int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codeint main(){ int l = 4, w = 6; cout << countRectangles(l, w) << endl; return 0;} // Java program to find minimum number of// squares to make a given rectangle. class GFG{static int __gcd(int a, int b) { if (b==0) return a; return __gcd(b,a%b);}static int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codepublic static void main(String[] args){ int l = 4, w = 6; System.out.println(countRectangles(l, w));}}// This code is contributed by mits # Python3 code to find minimum number of# squares to make a given rectangle. import math def countRectangles(l, w): # if we take gcd(l, w), this # will be largest possible # side for square, hence minimum # number of square. squareSide = math.gcd(l,w) # Number of squares. return (l*w)/(squareSide*squareSide) # Driver Code if __name__ == '__main__': l = 4 w = 6 ans = countRectangles(l, w) print (int(ans)) # this code is contributed by# SURENDRA_GANGWAR // C# program to find minimum number of// squares to make a given rectangle. class GFG{static int __gcd(int a, int b) {if (b==0) return a;return __gcd(b,a%b);}static int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codepublic static void Main(){ int l = 4, w = 6; System.Console.WriteLine(countRectangles(l, w));}}// This code is contributed by mits <?php// PHP program to find minimum number// of squares to make a given rectangle. function gcd($a, $b){ return $b ? gcd($b, $a % $b) : $a;} function countRectangles($l, $w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. $squareSide = gcd($l, $w); // Number of squares. return ($l * $w) / ($squareSide * $squareSide);} // Driver code$l = 4;$w = 6;echo countRectangles($l, $w) . "\n"; // This code is contributed// by ChitraNayal?> <script> // Javascript program to find minimum number of// squares to make a given rectangle. function __gcd(a, b) { if (b==0) return a; return __gcd(b,a%b);} function countRectangles(l, w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. let squareSide = __gcd(l, w); // Number of squares. return parseInt((l * w) / (squareSide * squareSide));} // Driver code let l = 4, w = 6; document.write(countRectangles(l, w)); </script> 6 SURENDRA_GANGWAR ukasp Mithun Kumar rishavmahato348 sagar0719kumar GCD-LCM square-rectangle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jul, 2021" }, { "code": null, "e": 233, "s": 52, "text": "Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: " }, { "code": null, "e": 592, "s": 233, "text": "Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not minimum. If we make square with side of 2, then we have 6 squares. and this is our required answer. And also we can’t make square with side 3, if we select 3 as square side, then whole sheet can’t be converted into squares of equal length. " }, { "code": null, "e": 618, "s": 592, "text": "Input :l=3 w=5 Output :15" }, { "code": null, "e": 691, "s": 620, "text": "Optimal length of the side of a square is equal to GCD of two numbers " }, { "code": null, "e": 695, "s": 691, "text": "C++" }, { "code": null, "e": 700, "s": 695, "text": "Java" }, { "code": null, "e": 708, "s": 700, "text": "Python3" }, { "code": null, "e": 711, "s": 708, "text": "C#" }, { "code": null, "e": 715, "s": 711, "text": "PHP" }, { "code": null, "e": 726, "s": 715, "text": "Javascript" }, { "code": "// CPP program to find minimum number of// squares to make a given rectangle.#include <bits/stdc++.h>using namespace std; int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codeint main(){ int l = 4, w = 6; cout << countRectangles(l, w) << endl; return 0;}", "e": 1218, "s": 726, "text": null }, { "code": "// Java program to find minimum number of// squares to make a given rectangle. class GFG{static int __gcd(int a, int b) { if (b==0) return a; return __gcd(b,a%b);}static int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codepublic static void main(String[] args){ int l = 4, w = 6; System.out.println(countRectangles(l, w));}}// This code is contributed by mits", "e": 1817, "s": 1218, "text": null }, { "code": "# Python3 code to find minimum number of# squares to make a given rectangle. import math def countRectangles(l, w): # if we take gcd(l, w), this # will be largest possible # side for square, hence minimum # number of square. squareSide = math.gcd(l,w) # Number of squares. return (l*w)/(squareSide*squareSide) # Driver Code if __name__ == '__main__': l = 4 w = 6 ans = countRectangles(l, w) print (int(ans)) # this code is contributed by# SURENDRA_GANGWAR", "e": 2320, "s": 1817, "text": null }, { "code": "// C# program to find minimum number of// squares to make a given rectangle. class GFG{static int __gcd(int a, int b) {if (b==0) return a;return __gcd(b,a%b);}static int countRectangles(int l, int w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. int squareSide = __gcd(l, w); // Number of squares. return (l * w) / (squareSide * squareSide);} // Driver codepublic static void Main(){ int l = 4, w = 6; System.Console.WriteLine(countRectangles(l, w));}}// This code is contributed by mits", "e": 2904, "s": 2320, "text": null }, { "code": "<?php// PHP program to find minimum number// of squares to make a given rectangle. function gcd($a, $b){ return $b ? gcd($b, $a % $b) : $a;} function countRectangles($l, $w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. $squareSide = gcd($l, $w); // Number of squares. return ($l * $w) / ($squareSide * $squareSide);} // Driver code$l = 4;$w = 6;echo countRectangles($l, $w) . \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 3450, "s": 2904, "text": null }, { "code": "<script> // Javascript program to find minimum number of// squares to make a given rectangle. function __gcd(a, b) { if (b==0) return a; return __gcd(b,a%b);} function countRectangles(l, w){ // if we take gcd(l, w), this // will be largest possible // side for square, hence minimum // number of square. let squareSide = __gcd(l, w); // Number of squares. return parseInt((l * w) / (squareSide * squareSide));} // Driver code let l = 4, w = 6; document.write(countRectangles(l, w)); </script>", "e": 3977, "s": 3450, "text": null }, { "code": null, "e": 3979, "s": 3977, "text": "6" }, { "code": null, "e": 3998, "s": 3981, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4004, "s": 3998, "text": "ukasp" }, { "code": null, "e": 4017, "s": 4004, "text": "Mithun Kumar" }, { "code": null, "e": 4033, "s": 4017, "text": "rishavmahato348" }, { "code": null, "e": 4048, "s": 4033, "text": "sagar0719kumar" }, { "code": null, "e": 4056, "s": 4048, "text": "GCD-LCM" }, { "code": null, "e": 4073, "s": 4056, "text": "square-rectangle" }, { "code": null, "e": 4083, "s": 4073, "text": "Geometric" }, { "code": null, "e": 4096, "s": 4083, "text": "Mathematical" }, { "code": null, "e": 4109, "s": 4096, "text": "Mathematical" }, { "code": null, "e": 4119, "s": 4109, "text": "Geometric" } ]
Plot mean and standard deviation using ggplot2 in R
21 Jul, 2021 An error bar shows the confidence and precision in a set of measurements or calculated values based on the errors that occur in the data set. It helps visually display the errors in an area of the data frame and shows an actual and exact missing part. As a descriptive behavior, error bars provide details about variances in data as well as recommendations to make changes so that data becomes more insightful and impactful for users. geom_errorbar(): This function is used to produce the error bars. Syntax: geom_errorbar(mapping = NULL, data = NULL, stat = “identity”, position = “identity”, ...) Example: Plot to display mean and standard deviation on a barplot. R df<-data.frame(Mean=c(0.24,0.25,0.37,0.643,0.54), sd=c(0.00362,0.281,0.3068,0.2432,0.322), Quality=as.factor(c("good","bad","good", "very good","very good")), Category=c("A","B","C","D","E"), Insert= c(0.0, 0.1, 0.3, 0.5, 1.0)) # Load ggplot2library(ggplot2) ggplot(df, aes(x=Category, y=Mean, fill=Quality)) + geom_bar(position=position_dodge(), stat="identity", colour='black') + geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.2) Output: Now let us look at the point plot, if we want to add points to the same dataframe, simply add geom_point(). Syntax: geom_point(mapping = NULL, data = NULL, stat = “identity”, position = “identity”,..., na.rm = FALSE,show.legend = NA,inherit.aes = TRUE) Example1: Plot with points R # creating a data frame dfdf<-data.frame(Mean=c(0.24,0.25,0.37,0.643,0.54), sd=c(0.00362,0.281,0.3068,0.2432,0.322), Quality=as.factor(c("good","bad","good", "very good","very good")), Category=c("A","B","C","D","E"), Insert= c(0.0, 0.1, 0.3, 0.5, 1.0)) # plot the point plotp<-ggplot(df, aes(x=Category, y=Mean, fill=Quality)) + geom_point()+ geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.2, position=position_dodge(0.05)) p Output: Different methods are used by different groups to illustrate their differences. Alternatively, dot plots or point plots are used. To tell ggplot that a column or dot represents a mean, we need to indicate a mean statistic. Let us explore this in detail using a different dataframe. To do this, we can use ggplot’s “stat”-functions. Let’s visualize the results using bar charts of means. In place of using the *stat=count>’, we will tell the stat we would like a summary measure, namely the mean. Then, the dataframe is divided into groups, and the mean and standard deviation for each is noted and plotted. This can be done using summarize and group_by(). File in use: Crop_recommendation Example: Plot with mean and standard deviation for each group. R # load crop_recomendation csv file and # store it in dsds <- read.csv("Crop_recommendation.csv", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot() # create a new dataframe crop_meanscrop_means <- ds %>% group_by(label) %>% summarize(mean_temperature=mean(temperature)) crop_means # Creating barplots of meansggplot(crop_means, aes(x=label, y=mean_temperature)) +geom_bar(stat="identity") Output: Now, if you want to point the point plot then you can also do that by using the geom_point() function. Syntax: geom_point(stat=”summary”, fun.y=”mean”) Example: point plot R # load crop_recomendation csv file and # store it in dsds <- read.csv("Crop_recommendation.csv", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot() # create a new dataframe crop_meanscrop_means <- ds %>% group_by(label) %>% summarize(mean_temperature=mean(temperature)) crop_means # creating point plots of meansggplot(ds, aes(x=label, y=temperature)) + geom_point(stat="summary", fun.y="mean") Output: For plotting Standard Deviation(SD) you need to use geom_errorbar(). First, we can create a new dataset, which is the most labor-intensive way of creating error bars. We will also calculate the standard error this time (which equals the standard deviation divided by the square root of N). Syntax: geom_errorbar() Parameters: ymin or xmin : Lower Value of custom point ymax or xmax: Upper Value of custom point height: height of errorbar alpha: Opacity of error bar color: Color of error bar group: Differentiate points by group linetype size Example: Plotting standard deviation R # load a crop recommendation csv file datasetds <- read.csv("Crop_recommendation.csv", header = TRUE) # create a new dataframe crop_means_Secrop_means_se <- ds %>% group_by(label) %>% summarize(mean_N=mean(N), sd_N=sd(N), N_N=n(), se=sd_N/sqrt(N_N), upper_limit=mean_N+se, lower_limit=mean_N-se ) crop_means_se ggplot(crop_means_se, aes(x=label, y=mean_N)) + geom_bar(stat="identity") + geom_errorbar(aes(ymin=lower_limit, ymax=upper_limit)) Output: You can also create your own “se” function by using geom_errorbar(). Xmin & Xmax and Ymin & Ymax can be used to plot the errorbar horizontally or vertically. Syntax: geom_errorbar(stat=”summary”,fun.ymin=function(x){mean(x-sd(x)/sqrt(length(x))}, fun.ymax=function(x){mean(x)+sd(x)/sqrt(length(x))}). Here, we calculate ymin and ymax values to plot the errorbar vertically, and these values are created by a separate function in which average of( x-sd(x)/sqrt(length(x)) is calculated for a minimum of y or ymin and the average of (x+sd(x)/sqrt(length(x)) is calculated for a maximum of y or ymax. Example: Plotting standard deviation R # load a crop recommendation csv file datasetds <- read.csv("Crop_recommendation.csv", header = TRUE) ggplot(ds, aes(x=label, y=N)) + geom_bar(stat="summary", fun.y="mean") + geom_errorbar(stat="summary", fun.ymin=function(x) {mean(x)-sd(x)/sqrt(length(x))}, fun.ymax=function(x) {mean(x)+sd(x)/sqrt(length(x))}) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jul, 2021" }, { "code": null, "e": 487, "s": 52, "text": "An error bar shows the confidence and precision in a set of measurements or calculated values based on the errors that occur in the data set. It helps visually display the errors in an area of the data frame and shows an actual and exact missing part. As a descriptive behavior, error bars provide details about variances in data as well as recommendations to make changes so that data becomes more insightful and impactful for users." }, { "code": null, "e": 553, "s": 487, "text": "geom_errorbar(): This function is used to produce the error bars." }, { "code": null, "e": 561, "s": 553, "text": "Syntax:" }, { "code": null, "e": 651, "s": 561, "text": "geom_errorbar(mapping = NULL, data = NULL, stat = “identity”, position = “identity”, ...)" }, { "code": null, "e": 718, "s": 651, "text": "Example: Plot to display mean and standard deviation on a barplot." }, { "code": null, "e": 720, "s": 718, "text": "R" }, { "code": "df<-data.frame(Mean=c(0.24,0.25,0.37,0.643,0.54), sd=c(0.00362,0.281,0.3068,0.2432,0.322), Quality=as.factor(c(\"good\",\"bad\",\"good\", \"very good\",\"very good\")), Category=c(\"A\",\"B\",\"C\",\"D\",\"E\"), Insert= c(0.0, 0.1, 0.3, 0.5, 1.0)) # Load ggplot2library(ggplot2) ggplot(df, aes(x=Category, y=Mean, fill=Quality)) + geom_bar(position=position_dodge(), stat=\"identity\", colour='black') + geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.2)", "e": 1264, "s": 720, "text": null }, { "code": null, "e": 1272, "s": 1264, "text": "Output:" }, { "code": null, "e": 1380, "s": 1272, "text": "Now let us look at the point plot, if we want to add points to the same dataframe, simply add geom_point()." }, { "code": null, "e": 1389, "s": 1380, "text": "Syntax: " }, { "code": null, "e": 1526, "s": 1389, "text": "geom_point(mapping = NULL, data = NULL, stat = “identity”, position = “identity”,..., na.rm = FALSE,show.legend = NA,inherit.aes = TRUE)" }, { "code": null, "e": 1553, "s": 1526, "text": "Example1: Plot with points" }, { "code": null, "e": 1555, "s": 1553, "text": "R" }, { "code": "# creating a data frame dfdf<-data.frame(Mean=c(0.24,0.25,0.37,0.643,0.54), sd=c(0.00362,0.281,0.3068,0.2432,0.322), Quality=as.factor(c(\"good\",\"bad\",\"good\", \"very good\",\"very good\")), Category=c(\"A\",\"B\",\"C\",\"D\",\"E\"), Insert= c(0.0, 0.1, 0.3, 0.5, 1.0)) # plot the point plotp<-ggplot(df, aes(x=Category, y=Mean, fill=Quality)) + geom_point()+ geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.2, position=position_dodge(0.05)) p", "e": 2100, "s": 1555, "text": null }, { "code": null, "e": 2109, "s": 2100, "text": "Output: " }, { "code": null, "e": 2441, "s": 2109, "text": "Different methods are used by different groups to illustrate their differences. Alternatively, dot plots or point plots are used. To tell ggplot that a column or dot represents a mean, we need to indicate a mean statistic. Let us explore this in detail using a different dataframe. To do this, we can use ggplot’s “stat”-functions." }, { "code": null, "e": 2765, "s": 2441, "text": "Let’s visualize the results using bar charts of means. In place of using the *stat=count>’, we will tell the stat we would like a summary measure, namely the mean. Then, the dataframe is divided into groups, and the mean and standard deviation for each is noted and plotted. This can be done using summarize and group_by()." }, { "code": null, "e": 2798, "s": 2765, "text": "File in use: Crop_recommendation" }, { "code": null, "e": 2861, "s": 2798, "text": "Example: Plot with mean and standard deviation for each group." }, { "code": null, "e": 2863, "s": 2861, "text": "R" }, { "code": "# load crop_recomendation csv file and # store it in dsds <- read.csv(\"Crop_recommendation.csv\", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot() # create a new dataframe crop_meanscrop_means <- ds %>% group_by(label) %>% summarize(mean_temperature=mean(temperature)) crop_means # Creating barplots of meansggplot(crop_means, aes(x=label, y=mean_temperature)) +geom_bar(stat=\"identity\") ", "e": 3282, "s": 2863, "text": null }, { "code": null, "e": 3290, "s": 3282, "text": "Output:" }, { "code": null, "e": 3393, "s": 3290, "text": "Now, if you want to point the point plot then you can also do that by using the geom_point() function." }, { "code": null, "e": 3401, "s": 3393, "text": "Syntax:" }, { "code": null, "e": 3442, "s": 3401, "text": "geom_point(stat=”summary”, fun.y=”mean”)" }, { "code": null, "e": 3463, "s": 3442, "text": "Example: point plot " }, { "code": null, "e": 3465, "s": 3463, "text": "R" }, { "code": "# load crop_recomendation csv file and # store it in dsds <- read.csv(\"Crop_recommendation.csv\", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot() # create a new dataframe crop_meanscrop_means <- ds %>% group_by(label) %>% summarize(mean_temperature=mean(temperature)) crop_means # creating point plots of meansggplot(ds, aes(x=label, y=temperature)) + geom_point(stat=\"summary\", fun.y=\"mean\") ", "e": 3890, "s": 3465, "text": null }, { "code": null, "e": 3898, "s": 3890, "text": "Output:" }, { "code": null, "e": 4188, "s": 3898, "text": "For plotting Standard Deviation(SD) you need to use geom_errorbar(). First, we can create a new dataset, which is the most labor-intensive way of creating error bars. We will also calculate the standard error this time (which equals the standard deviation divided by the square root of N)." }, { "code": null, "e": 4196, "s": 4188, "text": "Syntax:" }, { "code": null, "e": 4212, "s": 4196, "text": "geom_errorbar()" }, { "code": null, "e": 4224, "s": 4212, "text": "Parameters:" }, { "code": null, "e": 4267, "s": 4224, "text": "ymin or xmin : Lower Value of custom point" }, { "code": null, "e": 4309, "s": 4267, "text": "ymax or xmax: Upper Value of custom point" }, { "code": null, "e": 4336, "s": 4309, "text": "height: height of errorbar" }, { "code": null, "e": 4364, "s": 4336, "text": "alpha: Opacity of error bar" }, { "code": null, "e": 4390, "s": 4364, "text": "color: Color of error bar" }, { "code": null, "e": 4427, "s": 4390, "text": "group: Differentiate points by group" }, { "code": null, "e": 4436, "s": 4427, "text": "linetype" }, { "code": null, "e": 4441, "s": 4436, "text": "size" }, { "code": null, "e": 4478, "s": 4441, "text": "Example: Plotting standard deviation" }, { "code": null, "e": 4480, "s": 4478, "text": "R" }, { "code": "# load a crop recommendation csv file datasetds <- read.csv(\"Crop_recommendation.csv\", header = TRUE) # create a new dataframe crop_means_Secrop_means_se <- ds %>% group_by(label) %>% summarize(mean_N=mean(N), sd_N=sd(N), N_N=n(), se=sd_N/sqrt(N_N), upper_limit=mean_N+se, lower_limit=mean_N-se ) crop_means_se ggplot(crop_means_se, aes(x=label, y=mean_N)) + geom_bar(stat=\"identity\") + geom_errorbar(aes(ymin=lower_limit, ymax=upper_limit))", "e": 4993, "s": 4480, "text": null }, { "code": null, "e": 5001, "s": 4993, "text": "Output:" }, { "code": null, "e": 5159, "s": 5001, "text": "You can also create your own “se” function by using geom_errorbar(). Xmin & Xmax and Ymin & Ymax can be used to plot the errorbar horizontally or vertically." }, { "code": null, "e": 5167, "s": 5159, "text": "Syntax:" }, { "code": null, "e": 5303, "s": 5167, "text": "geom_errorbar(stat=”summary”,fun.ymin=function(x){mean(x-sd(x)/sqrt(length(x))}, fun.ymax=function(x){mean(x)+sd(x)/sqrt(length(x))}). " }, { "code": null, "e": 5600, "s": 5303, "text": "Here, we calculate ymin and ymax values to plot the errorbar vertically, and these values are created by a separate function in which average of( x-sd(x)/sqrt(length(x)) is calculated for a minimum of y or ymin and the average of (x+sd(x)/sqrt(length(x)) is calculated for a maximum of y or ymax." }, { "code": null, "e": 5637, "s": 5600, "text": "Example: Plotting standard deviation" }, { "code": null, "e": 5639, "s": 5637, "text": "R" }, { "code": "# load a crop recommendation csv file datasetds <- read.csv(\"Crop_recommendation.csv\", header = TRUE) ggplot(ds, aes(x=label, y=N)) + geom_bar(stat=\"summary\", fun.y=\"mean\") + geom_errorbar(stat=\"summary\", fun.ymin=function(x) {mean(x)-sd(x)/sqrt(length(x))}, fun.ymax=function(x) {mean(x)+sd(x)/sqrt(length(x))})", "e": 5987, "s": 5639, "text": null }, { "code": null, "e": 5995, "s": 5987, "text": "Output:" }, { "code": null, "e": 6002, "s": 5995, "text": "Picked" }, { "code": null, "e": 6011, "s": 6002, "text": "R-ggplot" }, { "code": null, "e": 6022, "s": 6011, "text": "R Language" } ]
Largest Rectangular Area in a Histogram | Set 1
21 Jun, 2022 Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit. For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible is 12 (see the below figure, the max area rectangle is highlighted in red) A simple solution is to one by one consider all bars as starting points and calculate area of all rectangles starting with every bar. Finally return maximum of all possible areas. Time complexity of this solution would be O(n^2). We can use Divide and Conquer to solve this in O(nLogn) time. The idea is to find the minimum value in the given array. Once we have index of the minimum value, the max area is maximum of following three values. Maximum area in left side of minimum value (Not including the min value) Maximum area in right side of minimum value (Not including the min value) Number of bars multiplied by minimum value. Maximum area in left side of minimum value (Not including the min value) Maximum area in right side of minimum value (Not including the min value) Number of bars multiplied by minimum value. The areas in left and right of minimum value bar can be calculated recursively. If we use linear search to find the minimum value, then the worst case time complexity of this algorithm becomes O(n^2). In worst case, we always have (n-1) elements in one side and 0 elements in other side and if the finding minimum takes O(n) time, we get the recurrence similar to worst case of Quick Sort. How to find the minimum efficiently? Range Minimum Query using Segment Tree can be used for this. We build segment tree of the given histogram heights. Once the segment tree is built, all range minimum queries take O(Logn) time. So over all complexity of the algorithm becomes. Overall Time = Time to build Segment Tree + Time to recursively find maximum areaTime to build segment tree is O(n). Let the time to recursively find max area be T(n). It can be written as following. T(n) = O(Logn) + T(n-1) The solution of above recurrence is O(nLogn). So overall time is O(n) + O(nLogn) which is O(nLogn).Following is C++ implementation of the above algorithm. Implementation: C++ Java Python3 C# // A Divide and Conquer Program to find maximum rectangular area in a histogram#include <bits/stdc++.h>using namespace std; // A utility function to find minimum of three integersint max(int x, int y, int z){ return max(max(x, y), z); } // A utility function to get minimum of two numbers in hist[]int minVal(int *hist, int i, int j){ if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j;} // A utility function to get the middle index from corner indexes.int getMid(int s, int e){ return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist --> Input array for which segment tree is built st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int RMQUtil(int *hist, int *st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal(hist, RMQUtil(hist, st, ss, mid, qs, qe, 2*index+1), RMQUtil(hist, st, mid+1, se, qs, qe, 2*index+2));} // Return index of minimum element in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()int RMQ(int *hist, int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { cout << "Invalid Input"; return -1; } return RMQUtil(hist, st, 0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for hist[ss..se].// si is index of current node in segment tree stint constructSTUtil(int hist[], int ss, int se, int *st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal(hist, constructSTUtil(hist, ss, mid, st, si*2+1), constructSTUtil(hist, mid+1, se, st, si*2+2)); return st[si];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructST(int hist[], int n){ // Allocate memory for segment tree int x = (int)(ceil(log2(n))); //Height of segment tree int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(hist, 0, n-1, st, 0); // Return the constructed segment tree return st;} // A recursive function to find the maximum rectangular area.// It uses segment tree 'st' to find the minimum value in hist[l..r]int getMaxAreaRec(int *hist, int *st, int n, int l, int r){ // Base cases if (l > r) return INT_MIN; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ(hist, st, n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec(hist, st, n, l, m-1), getMaxAreaRec(hist, st, n, m+1, r), (r-l+1)*(hist[m]) );} // The main function to find max areaint getMaxArea(int hist[], int n){ // Build segment tree from given array. This takes // O(n) time int *st = constructST(hist, n); // Use recursive utility function to find the // maximum area return getMaxAreaRec(hist, st, n, 0, n-1);} // Driver program to test above functionsint main(){ int hist[] = {6, 1, 5, 4, 5, 2, 6}; int n = sizeof(hist)/sizeof(hist[0]); cout << "Maximum area is " << getMaxArea(hist, n); return 0;} // A Divide and Conquer Program to find maximum rectangular area in a histogramimport java.util.*; class GFG{ static int[] hist; static int[] st; // A utility function to find minimum of three integers static int max(int x, int y, int z) { return Math.max(Math.max(x, y), z); } // A utility function to get minimum of two numbers in hist[] static int minVal(int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } // A utility function to get the middle index from corner indexes. static int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist -. Input array for which segment tree is built st -. Pointer to segment tree index -. Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se -. Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe -. Starting and ending indexes of query range */ static int RMQUtil( int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal( RMQUtil(ss, mid, qs, qe, 2*index+1), RMQUtil( mid+1, se, qs, qe, 2*index+2)); } // Return index of minimum element in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() static int RMQ( int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { System.out.print("Invalid Input"); return -1; } return RMQUtil( 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for hist[ss..se]. // si is index of current node in segment tree st static int constructSTUtil(int ss, int se, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal( constructSTUtil( ss, mid, si*2+1), constructSTUtil( mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static void constructST(int n) { // Allocate memory for segment tree int x = (int)(Math.ceil(Math.log(n))); //Height of segment tree int max_size = 2*(int)Math.pow(2, x) - 1; //Maximum size of segment tree st = new int[max_size*2]; // Fill the allocated memory st constructSTUtil( 0, n-1, 0); // Return the constructed segment tree // return st; } // A recursive function to find the maximum rectangular area. // It uses segment tree 'st' to find the minimum value in hist[l..r] static int getMaxAreaRec( int n, int l, int r) { // Base cases if (l > r) return Integer.MIN_VALUE; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ( n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec( n, l, m - 1), getMaxAreaRec( n, m + 1, r), (r - l + 1)*(hist[m]) ); } // The main function to find max area static int getMaxArea( int n) { // Build segment tree from given array. This takes // O(n) time constructST(n); // Use recursive utility function to find the // maximum area return getMaxAreaRec( n, 0, n - 1); } // Driver program to test above functions public static void main(String[] args) { int[] a = {6, 1, 5, 4, 5, 2, 6}; int n = a.length; hist = new int[n]; hist = a; System.out.print("Maximum area is " + getMaxArea(n)); }} // This code is contributed by Rajput-Ji # Python3 program for range minimum # query using segment tree # modified to return index of minimum instead of minimum itself# for further reference link# https://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ #-------------------------------------------------------------------------from math import ceil,log2; # A utility function to get # minimum of two numbers def minVal(hist,x, y) : if x==-1: return y if y==-1: return x return x if (hist[x] < hist[y]) else y; # A utility function to get the # middle index from corner indexes. def getMid(s, e) : return s + (e - s) // 2; """ A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range """def RMQUtil( hist,st, ss, se, qs, qe, index) : # If segment of this node is a part # of given range, then return # the min of the segment if (qs <= ss and qe >= se) : return st[index]; # If segment of this node # is outside the given range if (se < qs or ss > qe) : return -1; # If a part of this segment # overlaps with the given range mid = getMid(ss, se); return minVal(hist,RMQUtil(hist,st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(hist,st, mid + 1, se, qs, qe, 2 * index + 2)); # Return minimum of elements in range # from index qs (query start) to # qe (query end). It mainly uses RMQUtil() def RMQ( hist,st, n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print("Invalid Input"); return -1; return RMQUtil(hist,st, 0, n - 1, qs, qe, 0); # A recursive function that constructs # Segment Tree for array[ss..se]. # si is index of current node in segment tree st def constructSTUtil(hist, ss, se, st, si) : # If there is one element in array, # store it in current node of # segment tree and return if (ss == se) : st[si] = ss; return st[si]; # If there are more than one elements, # then recur for left and right subtrees # and store the minimum of two values in this node mid = getMid(ss, se); st[si] = minVal(hist,constructSTUtil(hist, ss, mid, st, si * 2 + 1), constructSTUtil(hist, mid + 1, se, st, si * 2 + 2)); return st[si]; """Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory """def constructST( hist, n) : # Allocate memory for segment tree # Height of segment tree x = (int)(ceil(log2(n))); # Maximum size of segment tree max_size = 2 * (int)(2**x) - 1; st = [0] * (max_size); # Fill the allocated memory st constructSTUtil(hist, 0, n - 1, st, 0); # Return the constructed segment tree return st; #---------------------------------------------------------------- # main program# Python3 program using Divide and Conquer# to find maximum rectangular area under a histogram def max_area_histogram(hist): area=0 #initialize area st = constructST(hist, len(hist)) # construct the segment tree try: # try except block is generally used in this way # to suppress all type of exceptions raised. def fun(left,right): # this function "fun" calculates area # recursively between indices left and right nonlocal area # global area won't work here as # variable area is defined inside function # not in main(). if left==right: return # the recursion has reached end index = RMQ(hist,st, len(hist), left, right-1) # RMQ function returns index # of minimum value # in the range of [left,right-1] # can also be found by using min() but # results in O(n) instead of O(log n) for traversing area=max(area,hist[index]*(right-left)) # calculate area with minimum above fun(index+1,right) fun(left,index) # initiate further recursion return fun(0,len(hist)) # initializes the recursion return(area) # return the max area to calling function # in this case "print" except: pass # Driver Code hist = [6, 2, 5, 4, 5, 1, 6] print("Maximum area is", max_area_histogram(hist)) # This code is contributed # by Vishnudev C. // C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { static int[] hist; static int[] st; // A utility function to find minimum of three integers static int max(int x, int y, int z) { return Math.Max(Math.Max(x, y), z); } // A utility function to get minimum of two numbers in hist[] static int minVal(int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } // A utility function to get the middle index from corner indexes. static int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist -. Input array for which segment tree is built st -. Pointer to segment tree index -. Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se -. Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe -. Starting and ending indexes of query range */ static int RMQUtil( int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal( RMQUtil(ss, mid, qs, qe, 2*index+1), RMQUtil( mid+1, se, qs, qe, 2*index+2)); } // Return index of minimum element in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() static int RMQ( int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { Console.Write("Invalid Input"); return -1; } return RMQUtil( 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for hist[ss..se]. // si is index of current node in segment tree st static int constructSTUtil(int ss, int se, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal( constructSTUtil( ss, mid, si*2+1), constructSTUtil( mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static void constructST(int n) { // Allocate memory for segment tree int x = (int)(Math.Ceiling(Math.Log(n))); //Height of segment tree int max_size = 2*(int)Math.Pow(2, x) - 1; //Maximum size of segment tree st = new int[max_size*2]; // Fill the allocated memory st constructSTUtil( 0, n-1, 0); // Return the constructed segment tree // return st; } // A recursive function to find the maximum rectangular area. // It uses segment tree 'st' to find the minimum value in hist[l..r] static int getMaxAreaRec( int n, int l, int r) { // Base cases if (l > r) return Int32.MinValue; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ( n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec( n, l, m - 1), getMaxAreaRec( n, m + 1, r), (r - l + 1)*(hist[m]) ); } // The main function to find max area static int getMaxArea( int n) { // Build segment tree from given array. This takes // O(n) time constructST(n); // Use recursive utility function to find the // maximum area return getMaxAreaRec( n, 0, n - 1); } // Driver Codepublic static void Main(string[] args){ int[] a = {6, 1, 5, 4, 5, 2, 6}; int n = a.Length; hist = new int[n]; hist = a; Console.WriteLine("Maximum area is " + getMaxArea(n));}} Maximum area is 12 This problem can be solved in linear time. See below set 2 for linear time solution. Linear time solution for Largest Rectangular Area in a Histogram itisvishnudev aksathe31 surinderdawra388 simmytarika5 GauravRajput1 sanjoy_62 hardikkoriintern Akosha Amazon Facebook MAQ Software Microsoft Paytm Segment-Tree Snapdeal Advanced Data Structure Divide and Conquer Stack Paytm Amazon Microsoft Snapdeal MAQ Software Facebook Divide and Conquer Stack Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 267, "s": 52, "text": "Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit. " }, { "code": null, "e": 475, "s": 267, "text": "For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible is 12 (see the below figure, the max area rectangle is highlighted in red) " }, { "code": null, "e": 705, "s": 475, "text": "A simple solution is to one by one consider all bars as starting points and calculate area of all rectangles starting with every bar. Finally return maximum of all possible areas. Time complexity of this solution would be O(n^2)." }, { "code": null, "e": 918, "s": 705, "text": "We can use Divide and Conquer to solve this in O(nLogn) time. The idea is to find the minimum value in the given array. Once we have index of the minimum value, the max area is maximum of following three values. " }, { "code": null, "e": 1110, "s": 918, "text": "Maximum area in left side of minimum value (Not including the min value) Maximum area in right side of minimum value (Not including the min value) Number of bars multiplied by minimum value. " }, { "code": null, "e": 1184, "s": 1110, "text": "Maximum area in left side of minimum value (Not including the min value) " }, { "code": null, "e": 1259, "s": 1184, "text": "Maximum area in right side of minimum value (Not including the min value) " }, { "code": null, "e": 1304, "s": 1259, "text": "Number of bars multiplied by minimum value. " }, { "code": null, "e": 1972, "s": 1304, "text": "The areas in left and right of minimum value bar can be calculated recursively. If we use linear search to find the minimum value, then the worst case time complexity of this algorithm becomes O(n^2). In worst case, we always have (n-1) elements in one side and 0 elements in other side and if the finding minimum takes O(n) time, we get the recurrence similar to worst case of Quick Sort. How to find the minimum efficiently? Range Minimum Query using Segment Tree can be used for this. We build segment tree of the given histogram heights. Once the segment tree is built, all range minimum queries take O(Logn) time. So over all complexity of the algorithm becomes." }, { "code": null, "e": 2352, "s": 1972, "text": "Overall Time = Time to build Segment Tree + Time to recursively find maximum areaTime to build segment tree is O(n). Let the time to recursively find max area be T(n). It can be written as following. T(n) = O(Logn) + T(n-1) The solution of above recurrence is O(nLogn). So overall time is O(n) + O(nLogn) which is O(nLogn).Following is C++ implementation of the above algorithm. " }, { "code": null, "e": 2368, "s": 2352, "text": "Implementation:" }, { "code": null, "e": 2372, "s": 2368, "text": "C++" }, { "code": null, "e": 2377, "s": 2372, "text": "Java" }, { "code": null, "e": 2385, "s": 2377, "text": "Python3" }, { "code": null, "e": 2388, "s": 2385, "text": "C#" }, { "code": "// A Divide and Conquer Program to find maximum rectangular area in a histogram#include <bits/stdc++.h>using namespace std; // A utility function to find minimum of three integersint max(int x, int y, int z){ return max(max(x, y), z); } // A utility function to get minimum of two numbers in hist[]int minVal(int *hist, int i, int j){ if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j;} // A utility function to get the middle index from corner indexes.int getMid(int s, int e){ return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist --> Input array for which segment tree is built st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int RMQUtil(int *hist, int *st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal(hist, RMQUtil(hist, st, ss, mid, qs, qe, 2*index+1), RMQUtil(hist, st, mid+1, se, qs, qe, 2*index+2));} // Return index of minimum element in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()int RMQ(int *hist, int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { cout << \"Invalid Input\"; return -1; } return RMQUtil(hist, st, 0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for hist[ss..se].// si is index of current node in segment tree stint constructSTUtil(int hist[], int ss, int se, int *st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal(hist, constructSTUtil(hist, ss, mid, st, si*2+1), constructSTUtil(hist, mid+1, se, st, si*2+2)); return st[si];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructST(int hist[], int n){ // Allocate memory for segment tree int x = (int)(ceil(log2(n))); //Height of segment tree int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(hist, 0, n-1, st, 0); // Return the constructed segment tree return st;} // A recursive function to find the maximum rectangular area.// It uses segment tree 'st' to find the minimum value in hist[l..r]int getMaxAreaRec(int *hist, int *st, int n, int l, int r){ // Base cases if (l > r) return INT_MIN; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ(hist, st, n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec(hist, st, n, l, m-1), getMaxAreaRec(hist, st, n, m+1, r), (r-l+1)*(hist[m]) );} // The main function to find max areaint getMaxArea(int hist[], int n){ // Build segment tree from given array. This takes // O(n) time int *st = constructST(hist, n); // Use recursive utility function to find the // maximum area return getMaxAreaRec(hist, st, n, 0, n-1);} // Driver program to test above functionsint main(){ int hist[] = {6, 1, 5, 4, 5, 2, 6}; int n = sizeof(hist)/sizeof(hist[0]); cout << \"Maximum area is \" << getMaxArea(hist, n); return 0;}", "e": 6842, "s": 2388, "text": null }, { "code": "// A Divide and Conquer Program to find maximum rectangular area in a histogramimport java.util.*; class GFG{ static int[] hist; static int[] st; // A utility function to find minimum of three integers static int max(int x, int y, int z) { return Math.max(Math.max(x, y), z); } // A utility function to get minimum of two numbers in hist[] static int minVal(int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } // A utility function to get the middle index from corner indexes. static int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist -. Input array for which segment tree is built st -. Pointer to segment tree index -. Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se -. Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe -. Starting and ending indexes of query range */ static int RMQUtil( int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal( RMQUtil(ss, mid, qs, qe, 2*index+1), RMQUtil( mid+1, se, qs, qe, 2*index+2)); } // Return index of minimum element in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() static int RMQ( int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { System.out.print(\"Invalid Input\"); return -1; } return RMQUtil( 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for hist[ss..se]. // si is index of current node in segment tree st static int constructSTUtil(int ss, int se, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal( constructSTUtil( ss, mid, si*2+1), constructSTUtil( mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static void constructST(int n) { // Allocate memory for segment tree int x = (int)(Math.ceil(Math.log(n))); //Height of segment tree int max_size = 2*(int)Math.pow(2, x) - 1; //Maximum size of segment tree st = new int[max_size*2]; // Fill the allocated memory st constructSTUtil( 0, n-1, 0); // Return the constructed segment tree // return st; } // A recursive function to find the maximum rectangular area. // It uses segment tree 'st' to find the minimum value in hist[l..r] static int getMaxAreaRec( int n, int l, int r) { // Base cases if (l > r) return Integer.MIN_VALUE; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ( n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec( n, l, m - 1), getMaxAreaRec( n, m + 1, r), (r - l + 1)*(hist[m]) ); } // The main function to find max area static int getMaxArea( int n) { // Build segment tree from given array. This takes // O(n) time constructST(n); // Use recursive utility function to find the // maximum area return getMaxAreaRec( n, 0, n - 1); } // Driver program to test above functions public static void main(String[] args) { int[] a = {6, 1, 5, 4, 5, 2, 6}; int n = a.length; hist = new int[n]; hist = a; System.out.print(\"Maximum area is \" + getMaxArea(n)); }} // This code is contributed by Rajput-Ji ", "e": 11359, "s": 6842, "text": null }, { "code": "# Python3 program for range minimum # query using segment tree # modified to return index of minimum instead of minimum itself# for further reference link# https://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ #-------------------------------------------------------------------------from math import ceil,log2; # A utility function to get # minimum of two numbers def minVal(hist,x, y) : if x==-1: return y if y==-1: return x return x if (hist[x] < hist[y]) else y; # A utility function to get the # middle index from corner indexes. def getMid(s, e) : return s + (e - s) // 2; \"\"\" A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range \"\"\"def RMQUtil( hist,st, ss, se, qs, qe, index) : # If segment of this node is a part # of given range, then return # the min of the segment if (qs <= ss and qe >= se) : return st[index]; # If segment of this node # is outside the given range if (se < qs or ss > qe) : return -1; # If a part of this segment # overlaps with the given range mid = getMid(ss, se); return minVal(hist,RMQUtil(hist,st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(hist,st, mid + 1, se, qs, qe, 2 * index + 2)); # Return minimum of elements in range # from index qs (query start) to # qe (query end). It mainly uses RMQUtil() def RMQ( hist,st, n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print(\"Invalid Input\"); return -1; return RMQUtil(hist,st, 0, n - 1, qs, qe, 0); # A recursive function that constructs # Segment Tree for array[ss..se]. # si is index of current node in segment tree st def constructSTUtil(hist, ss, se, st, si) : # If there is one element in array, # store it in current node of # segment tree and return if (ss == se) : st[si] = ss; return st[si]; # If there are more than one elements, # then recur for left and right subtrees # and store the minimum of two values in this node mid = getMid(ss, se); st[si] = minVal(hist,constructSTUtil(hist, ss, mid, st, si * 2 + 1), constructSTUtil(hist, mid + 1, se, st, si * 2 + 2)); return st[si]; \"\"\"Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory \"\"\"def constructST( hist, n) : # Allocate memory for segment tree # Height of segment tree x = (int)(ceil(log2(n))); # Maximum size of segment tree max_size = 2 * (int)(2**x) - 1; st = [0] * (max_size); # Fill the allocated memory st constructSTUtil(hist, 0, n - 1, st, 0); # Return the constructed segment tree return st; #---------------------------------------------------------------- # main program# Python3 program using Divide and Conquer# to find maximum rectangular area under a histogram def max_area_histogram(hist): area=0 #initialize area st = constructST(hist, len(hist)) # construct the segment tree try: # try except block is generally used in this way # to suppress all type of exceptions raised. def fun(left,right): # this function \"fun\" calculates area # recursively between indices left and right nonlocal area # global area won't work here as # variable area is defined inside function # not in main(). if left==right: return # the recursion has reached end index = RMQ(hist,st, len(hist), left, right-1) # RMQ function returns index # of minimum value # in the range of [left,right-1] # can also be found by using min() but # results in O(n) instead of O(log n) for traversing area=max(area,hist[index]*(right-left)) # calculate area with minimum above fun(index+1,right) fun(left,index) # initiate further recursion return fun(0,len(hist)) # initializes the recursion return(area) # return the max area to calling function # in this case \"print\" except: pass # Driver Code hist = [6, 2, 5, 4, 5, 1, 6] print(\"Maximum area is\", max_area_histogram(hist)) # This code is contributed # by Vishnudev C.", "e": 16676, "s": 11359, "text": null }, { "code": "// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { static int[] hist; static int[] st; // A utility function to find minimum of three integers static int max(int x, int y, int z) { return Math.Max(Math.Max(x, y), z); } // A utility function to get minimum of two numbers in hist[] static int minVal(int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } // A utility function to get the middle index from corner indexes. static int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist -. Input array for which segment tree is built st -. Pointer to segment tree index -. Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se -. Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe -. Starting and ending indexes of query range */ static int RMQUtil( int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal( RMQUtil(ss, mid, qs, qe, 2*index+1), RMQUtil( mid+1, se, qs, qe, 2*index+2)); } // Return index of minimum element in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() static int RMQ( int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { Console.Write(\"Invalid Input\"); return -1; } return RMQUtil( 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for hist[ss..se]. // si is index of current node in segment tree st static int constructSTUtil(int ss, int se, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal( constructSTUtil( ss, mid, si*2+1), constructSTUtil( mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static void constructST(int n) { // Allocate memory for segment tree int x = (int)(Math.Ceiling(Math.Log(n))); //Height of segment tree int max_size = 2*(int)Math.Pow(2, x) - 1; //Maximum size of segment tree st = new int[max_size*2]; // Fill the allocated memory st constructSTUtil( 0, n-1, 0); // Return the constructed segment tree // return st; } // A recursive function to find the maximum rectangular area. // It uses segment tree 'st' to find the minimum value in hist[l..r] static int getMaxAreaRec( int n, int l, int r) { // Base cases if (l > r) return Int32.MinValue; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ( n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec( n, l, m - 1), getMaxAreaRec( n, m + 1, r), (r - l + 1)*(hist[m]) ); } // The main function to find max area static int getMaxArea( int n) { // Build segment tree from given array. This takes // O(n) time constructST(n); // Use recursive utility function to find the // maximum area return getMaxAreaRec( n, 0, n - 1); } // Driver Codepublic static void Main(string[] args){ int[] a = {6, 1, 5, 4, 5, 2, 6}; int n = a.Length; hist = new int[n]; hist = a; Console.WriteLine(\"Maximum area is \" + getMaxArea(n));}}", "e": 21129, "s": 16676, "text": null }, { "code": null, "e": 21148, "s": 21129, "text": "Maximum area is 12" }, { "code": null, "e": 21298, "s": 21148, "text": "This problem can be solved in linear time. See below set 2 for linear time solution. Linear time solution for Largest Rectangular Area in a Histogram" }, { "code": null, "e": 21312, "s": 21298, "text": "itisvishnudev" }, { "code": null, "e": 21322, "s": 21312, "text": "aksathe31" }, { "code": null, "e": 21339, "s": 21322, "text": "surinderdawra388" }, { "code": null, "e": 21352, "s": 21339, "text": "simmytarika5" }, { "code": null, "e": 21366, "s": 21352, "text": "GauravRajput1" }, { "code": null, "e": 21376, "s": 21366, "text": "sanjoy_62" }, { "code": null, "e": 21393, "s": 21376, "text": "hardikkoriintern" }, { "code": null, "e": 21400, "s": 21393, "text": "Akosha" }, { "code": null, "e": 21407, "s": 21400, "text": "Amazon" }, { "code": null, "e": 21416, "s": 21407, "text": "Facebook" }, { "code": null, "e": 21429, "s": 21416, "text": "MAQ Software" }, { "code": null, "e": 21439, "s": 21429, "text": "Microsoft" }, { "code": null, "e": 21445, "s": 21439, "text": "Paytm" }, { "code": null, "e": 21458, "s": 21445, "text": "Segment-Tree" }, { "code": null, "e": 21467, "s": 21458, "text": "Snapdeal" }, { "code": null, "e": 21491, "s": 21467, "text": "Advanced Data Structure" }, { "code": null, "e": 21510, "s": 21491, "text": "Divide and Conquer" }, { "code": null, "e": 21516, "s": 21510, "text": "Stack" }, { "code": null, "e": 21522, "s": 21516, "text": "Paytm" }, { "code": null, "e": 21529, "s": 21522, "text": "Amazon" }, { "code": null, "e": 21539, "s": 21529, "text": "Microsoft" }, { "code": null, "e": 21548, "s": 21539, "text": "Snapdeal" }, { "code": null, "e": 21561, "s": 21548, "text": "MAQ Software" }, { "code": null, "e": 21570, "s": 21561, "text": "Facebook" }, { "code": null, "e": 21589, "s": 21570, "text": "Divide and Conquer" }, { "code": null, "e": 21595, "s": 21589, "text": "Stack" }, { "code": null, "e": 21608, "s": 21595, "text": "Segment-Tree" } ]
What is IPv6?
04 Jul, 2022 IP address is your digital identity. It’s a network address for your computer so the Internet knows where to send you emails, data, etc. IP address determines who and where you are in the network of billions of digital devices that are connected to the Internet. IPv6 or Internet Protocol Version 6 is a network layer protocol that allows communication to take place over the network. IPv6 was designed by Internet Engineering Task Force (IETF) in December 1998 with the purpose of superseding the IPv4 due to the global exponentially growing internet users. The common type of IP address (is known as IPv4, for “version 4”). Here’s an example of what an IP address might look like: 25.59.209.224 An IPv4 address consists of four numbers, each of which contains one to three digits, with a single dot (.) separating each number or set of digits. Each of the four numbers can range from 0 to 255. This group of separated numbers creates the addresses that let you and everyone around the globe to send and retrieve data over our Internet connections. The IPv4 uses a 32-bit address scheme allowing to store 2^32 addresses which is more than 4 billion addresses. To date, it is considered the primary Internet Protocol and carries 94% of Internet traffic. Initially, it was assumed it would never run out of addresses but the present situation paves a new way to IPv6, let’s see why? An IPv6 address consists of eight groups of four hexadecimal digits. Here’s an example IPv6 address: 3001:0da8:75a3:0000:0000:8a2e:0370:7334 This new IP address version is being deployed to fulfil the need for more Internet addresses. It was aimed to resolve issues which are associated with IPv4. With 128-bit address space, it allows 340 undecillion unique address space. IPv6 also called IPng (Internet Protocol next generation). IPv6 support a theoretical maximum of 340, 282, 366, 920, 938, 463, 463, 374, 607, 431, 768, 211, 456. To keep it straightforward, we will never run out of IP addresses again. Now that we know about what is IPv6 address let’s take a look at its different types. Unicast addresses It identifies a unique node on a network and usually refers to a single sender or a single receiver. Multicast addresses It represents a group of IP devices and can only be used as the destination of a datagram. Anycast addresses It is assigned to a set of interfaces that typically belong to different nodes. Reliability Faster Speeds: IPv6 supports multicast rather than broadcast in IPv4.This feature allows bandwidth-intensive packet flows (like multimedia streams) to be sent to multiple destinations all at once. Stronger Security: IPSecurity, which provides confidentiality, and data integrity, is embedded into IPv6. Routing efficiency Most importantly it’s the final solution for growing nodes in Global-network. Conversion: Due to widespread present usage of IPv4 it will take a long period to completely shift to IPv6. Communication: IPv4 and IPv6 machines cannot communicate directly with each other. They need an intermediate technology to make that possible. dipanshirawat2101 vivekpal23123451254 Picked Computer Networks Write From Home Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Types of Network Topology GSM in Wireless Communication RSA Algorithm in Cryptography Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 189, "s": 52, "text": "IP address is your digital identity. It’s a network address for your computer so the Internet knows where to send you emails, data, etc." }, { "code": null, "e": 315, "s": 189, "text": "IP address determines who and where you are in the network of billions of digital devices that are connected to the Internet." }, { "code": null, "e": 612, "s": 315, "text": " IPv6 or Internet Protocol Version 6 is a network layer protocol that allows communication to take place over the network. IPv6 was designed by Internet Engineering Task Force (IETF) in December 1998 with the purpose of superseding the IPv4 due to the global exponentially growing internet users." }, { "code": null, "e": 736, "s": 612, "text": "The common type of IP address (is known as IPv4, for “version 4”). Here’s an example of what an IP address might look like:" }, { "code": null, "e": 750, "s": 736, "text": "25.59.209.224" }, { "code": null, "e": 1536, "s": 750, "text": "An IPv4 address consists of four numbers, each of which contains one to three digits, with a single dot (.) separating each number or set of digits. Each of the four numbers can range from 0 to 255. This group of separated numbers creates the addresses that let you and everyone around the globe to send and retrieve data over our Internet connections. The IPv4 uses a 32-bit address scheme allowing to store 2^32 addresses which is more than 4 billion addresses. To date, it is considered the primary Internet Protocol and carries 94% of Internet traffic. Initially, it was assumed it would never run out of addresses but the present situation paves a new way to IPv6, let’s see why? An IPv6 address consists of eight groups of four hexadecimal digits. Here’s an example IPv6 address:" }, { "code": null, "e": 1576, "s": 1536, "text": "3001:0da8:75a3:0000:0000:8a2e:0370:7334" }, { "code": null, "e": 1868, "s": 1576, "text": "This new IP address version is being deployed to fulfil the need for more Internet addresses. It was aimed to resolve issues which are associated with IPv4. With 128-bit address space, it allows 340 undecillion unique address space. IPv6 also called IPng (Internet Protocol next generation)." }, { "code": null, "e": 2044, "s": 1868, "text": "IPv6 support a theoretical maximum of 340, 282, 366, 920, 938, 463, 463, 374, 607, 431, 768, 211, 456. To keep it straightforward, we will never run out of IP addresses again." }, { "code": null, "e": 2130, "s": 2044, "text": "Now that we know about what is IPv6 address let’s take a look at its different types." }, { "code": null, "e": 2249, "s": 2130, "text": "Unicast addresses It identifies a unique node on a network and usually refers to a single sender or a single receiver." }, { "code": null, "e": 2360, "s": 2249, "text": "Multicast addresses It represents a group of IP devices and can only be used as the destination of a datagram." }, { "code": null, "e": 2458, "s": 2360, "text": "Anycast addresses It is assigned to a set of interfaces that typically belong to different nodes." }, { "code": null, "e": 2470, "s": 2458, "text": "Reliability" }, { "code": null, "e": 2667, "s": 2470, "text": "Faster Speeds: IPv6 supports multicast rather than broadcast in IPv4.This feature allows bandwidth-intensive packet flows (like multimedia streams) to be sent to multiple destinations all at once." }, { "code": null, "e": 2773, "s": 2667, "text": "Stronger Security: IPSecurity, which provides confidentiality, and data integrity, is embedded into IPv6." }, { "code": null, "e": 2792, "s": 2773, "text": "Routing efficiency" }, { "code": null, "e": 2870, "s": 2792, "text": "Most importantly it’s the final solution for growing nodes in Global-network." }, { "code": null, "e": 2978, "s": 2870, "text": "Conversion: Due to widespread present usage of IPv4 it will take a long period to completely shift to IPv6." }, { "code": null, "e": 3121, "s": 2978, "text": "Communication: IPv4 and IPv6 machines cannot communicate directly with each other. They need an intermediate technology to make that possible." }, { "code": null, "e": 3139, "s": 3121, "text": "dipanshirawat2101" }, { "code": null, "e": 3159, "s": 3139, "text": "vivekpal23123451254" }, { "code": null, "e": 3166, "s": 3159, "text": "Picked" }, { "code": null, "e": 3184, "s": 3166, "text": "Computer Networks" }, { "code": null, "e": 3200, "s": 3184, "text": "Write From Home" }, { "code": null, "e": 3218, "s": 3200, "text": "Computer Networks" }, { "code": null, "e": 3316, "s": 3218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3346, "s": 3316, "text": "Wireless Application Protocol" }, { "code": null, "e": 3386, "s": 3346, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 3412, "s": 3386, "text": "Types of Network Topology" }, { "code": null, "e": 3442, "s": 3412, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3472, "s": 3442, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 3508, "s": 3472, "text": "Convert integer to string in Python" }, { "code": null, "e": 3544, "s": 3508, "text": "Convert string to integer in Python" }, { "code": null, "e": 3605, "s": 3544, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 3621, "s": 3605, "text": "Python infinity" } ]
ASP.NET - Data Binding
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which gives it an inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline data binding. Simple data binding involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control. On the other hand, some controls can bind records, lists, or columns of data into their structure through a DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative data binding. The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and editing data collections. The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes: DataBoundControl HierarchicalDataBoundControl The abstract class DataBoundControl is again inherited by two more abstract classes: ListControl CompositeDataBoundControl The controls capable of simple data binding are derived from the ListControl abstract class and these controls are: BulletedList CheckBoxList DropDownList ListBox RadioButtonList The controls capable of declarative data binding (a more complex data binding) are derived from the abstract class CompositeDataBoundControl. These controls are: DetailsView FormView GridView RecordList Simple data binding involves the read-only selection lists. These controls can bind to an array list or fields from a database. Selection lists takes two values from the database or the data source; one value is displayed by the list and the other is considered as the value corresponding to the display. Let us take up a small example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data source control to retrieve two values from your database (we use the same DotNetReferences table as in the previous chapter). Choosing a data source for the bulleted list control involves: Selecting the data source control Selecting a field to display, which is called the data field Selecting a field for the value When the application is executed, check that the entire title column is bound to the bulleted list and displayed. We have already used declarative data binding in the previous tutorial using GridView control. The other composite data bound controls capable of displaying and manipulating data in a tabular manner are the DetailsView, FormView, and RecordList control. In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET. However, the data binding involves the following objects: A dataset that stores the data retrieved from the database. A dataset that stores the data retrieved from the database. The data provider, which retrieves data from the database by using a command over a connection. The data provider, which retrieves data from the database by using a command over a connection. The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements. The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements. Relation between the data binding objects: Let us take the following steps: Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as booklist.cs. using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace databinding { public class booklist { protected String bookname; protected String authorname; public booklist(String bname, String aname) { this.bookname = bname; this.authorname = aname; } public String Book { get { return this.bookname; } set { this.bookname = value; } } public String Author { get { return this.authorname; } set { this.authorname = value; } } } } Step (2) : Add four list controls on the page a list box control, a radio button list, a check box list, and a drop down list and four labels along with these list controls. The page should look like this in design view: The source file should look as the following: <form id="form1" runat="server"> <div> <table style="width: 559px"> <tr> <td style="width: 228px; height: 157px;"> <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"> </asp:ListBox> </td> <td style="height: 157px"> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> </td> </tr> <tr> <td style="width: 228px; height: 40px;"> <asp:Label ID="lbllistbox" runat="server"></asp:Label> </td> <td style="height: 40px"> <asp:Label ID="lbldrpdown" runat="server"> </asp:Label> </td> </tr> <tr> <td style="width: 228px; height: 21px"> </td> <td style="height: 21px"> </td> </tr> <tr> <td style="width: 228px; height: 21px"> <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"> </asp:RadioButtonList> </td> <td style="height: 21px"> <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"> </asp:CheckBoxList> </td> </tr> <tr> <td style="width: 228px; height: 21px"> <asp:Label ID="lblrdlist" runat="server"> </asp:Label> </td> <td style="height: 21px"> <asp:Label ID="lblchklist" runat="server"> </asp:Label> </td> </tr> </table> </div> </form> Step (3) : Finally, write the following code behind routines of the application: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { IList bklist = createbooklist(); if (!this.IsPostBack) { this.ListBox1.DataSource = bklist; this.ListBox1.DataTextField = "Book"; this.ListBox1.DataValueField = "Author"; this.DropDownList1.DataSource = bklist; this.DropDownList1.DataTextField = "Book"; this.DropDownList1.DataValueField = "Author"; this.RadioButtonList1.DataSource = bklist; this.RadioButtonList1.DataTextField = "Book"; this.RadioButtonList1.DataValueField = "Author"; this.CheckBoxList1.DataSource = bklist; this.CheckBoxList1.DataTextField = "Book"; this.CheckBoxList1.DataValueField = "Author"; this.DataBind(); } } protected IList createbooklist() { ArrayList allbooks = new ArrayList(); booklist bl; bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS"); allbooks.Add(bl); bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN"); allbooks.Add(bl); bl = new booklist("DATA STRUCTURE", "TANENBAUM"); allbooks.Add(bl); bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN"); allbooks.Add(bl); bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP"); allbooks.Add(bl); bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS"); allbooks.Add(bl); return allbooks; } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { this.lbllistbox.Text = this.ListBox1.SelectedValue; } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { this.lbldrpdown.Text = this.DropDownList1.SelectedValue; } protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e) { this.lblrdlist.Text = this.RadioButtonList1.SelectedValue; } protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e) { this.lblchklist.Text = this.CheckBoxList1.SelectedValue; } } Observe the following: The booklist class has two properties: bookname and authorname. The booklist class has two properties: bookname and authorname. The createbooklist method is a user defined method that creates an array of booklist objects named allbooks. The createbooklist method is a user defined method that creates an array of booklist objects named allbooks. The Page_Load event handler ensures that a list of books is created. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list controls. The page load event handler binds the IList object 'bklist' with the list controls. The bookname property is to be displayed and the authorname property is considered as the value. The Page_Load event handler ensures that a list of books is created. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list controls. The page load event handler binds the IList object 'bklist' with the list controls. The bookname property is to be displayed and the authorname property is considered as the value. When the page is run, if the user selects a book, its name is selected and displayed by the list controls whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list control. When the page is run, if the user selects a book, its name is selected and displayed by the list controls whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list control. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2585, "s": 2347, "text": "Every ASP.NET web form control inherits the DataBind method from its parent Control class, which gives it an inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline data binding." }, { "code": null, "e": 2781, "s": 2585, "text": "Simple data binding involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control." }, { "code": null, "e": 3009, "s": 2781, "text": "On the other hand, some controls can bind records, lists, or columns of data into their structure through a DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative data binding." }, { "code": null, "e": 3145, "s": 3009, "text": "The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and editing data collections." }, { "code": null, "e": 3241, "s": 3145, "text": "The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:" }, { "code": null, "e": 3258, "s": 3241, "text": "DataBoundControl" }, { "code": null, "e": 3287, "s": 3258, "text": "HierarchicalDataBoundControl" }, { "code": null, "e": 3372, "s": 3287, "text": "The abstract class DataBoundControl is again inherited by two more abstract classes:" }, { "code": null, "e": 3384, "s": 3372, "text": "ListControl" }, { "code": null, "e": 3410, "s": 3384, "text": "CompositeDataBoundControl" }, { "code": null, "e": 3526, "s": 3410, "text": "The controls capable of simple data binding are derived from the ListControl abstract class and these controls are:" }, { "code": null, "e": 3539, "s": 3526, "text": "BulletedList" }, { "code": null, "e": 3552, "s": 3539, "text": "CheckBoxList" }, { "code": null, "e": 3565, "s": 3552, "text": "DropDownList" }, { "code": null, "e": 3573, "s": 3565, "text": "ListBox" }, { "code": null, "e": 3589, "s": 3573, "text": "RadioButtonList" }, { "code": null, "e": 3751, "s": 3589, "text": "The controls capable of declarative data binding (a more complex data binding) are derived from the abstract class CompositeDataBoundControl. These controls are:" }, { "code": null, "e": 3763, "s": 3751, "text": "DetailsView" }, { "code": null, "e": 3772, "s": 3763, "text": "FormView" }, { "code": null, "e": 3781, "s": 3772, "text": "GridView" }, { "code": null, "e": 3792, "s": 3781, "text": "RecordList" }, { "code": null, "e": 4097, "s": 3792, "text": "Simple data binding involves the read-only selection lists. These controls can bind to an array list or fields from a database. Selection lists takes two values from the database or the data source; one value is displayed by the list and the other is considered as the value corresponding to the display." }, { "code": null, "e": 4374, "s": 4097, "text": "Let us take up a small example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data source control to retrieve two values from your database (we use the same DotNetReferences table as in the previous chapter)." }, { "code": null, "e": 4437, "s": 4374, "text": "Choosing a data source for the bulleted list control involves:" }, { "code": null, "e": 4471, "s": 4437, "text": "Selecting the data source control" }, { "code": null, "e": 4532, "s": 4471, "text": "Selecting a field to display, which is called the data field" }, { "code": null, "e": 4564, "s": 4532, "text": "Selecting a field for the value" }, { "code": null, "e": 4678, "s": 4564, "text": "When the application is executed, check that the entire title column is bound to the bulleted list and displayed." }, { "code": null, "e": 4932, "s": 4678, "text": "We have already used declarative data binding in the previous tutorial using GridView control. The other composite data bound controls capable of displaying and manipulating data in a tabular manner are the DetailsView, FormView, and RecordList control." }, { "code": null, "e": 5024, "s": 4932, "text": "In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET." }, { "code": null, "e": 5082, "s": 5024, "text": "However, the data binding involves the following objects:" }, { "code": null, "e": 5142, "s": 5082, "text": "A dataset that stores the data retrieved from the database." }, { "code": null, "e": 5202, "s": 5142, "text": "A dataset that stores the data retrieved from the database." }, { "code": null, "e": 5298, "s": 5202, "text": "The data provider, which retrieves data from the database by using a command over a connection." }, { "code": null, "e": 5394, "s": 5298, "text": "The data provider, which retrieves data from the database by using a command over a connection." }, { "code": null, "e": 5576, "s": 5394, "text": "The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements." }, { "code": null, "e": 5758, "s": 5576, "text": "The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements." }, { "code": null, "e": 5801, "s": 5758, "text": "Relation between the data binding objects:" }, { "code": null, "e": 5834, "s": 5801, "text": "Let us take the following steps:" }, { "code": null, "e": 6044, "s": 5834, "text": "Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as booklist.cs." }, { "code": null, "e": 6967, "s": 6044, "text": "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\n\nusing System.Xml.Linq;\n\nnamespace databinding\n{\n public class booklist\n {\n protected String bookname;\n protected String authorname;\n public booklist(String bname, String aname)\n {\n this.bookname = bname;\n this.authorname = aname;\n\n }\n \n public String Book\n {\n get\n {\n return this.bookname;\n }\n set\n {\n this.bookname = value;\n }\n }\n \n public String Author\n {\n get\n {\n return this.authorname;\n }\n set\n {\n this.authorname = value;\n }\n }\n }\n}" }, { "code": null, "e": 7188, "s": 6967, "text": "Step (2) : Add four list controls on the page a list box control, a radio button list, a check box list, and a drop down list and four labels along with these list controls. The page should look like this in design view:" }, { "code": null, "e": 7234, "s": 7188, "text": "The source file should look as the following:" }, { "code": null, "e": 9330, "s": 7234, "text": "<form id=\"form1\" runat=\"server\">\n <div>\n \n <table style=\"width: 559px\">\n <tr>\n <td style=\"width: 228px; height: 157px;\">\n <asp:ListBox ID=\"ListBox1\" runat=\"server\" AutoPostBack=\"True\" \n OnSelectedIndexChanged=\"ListBox1_SelectedIndexChanged\">\n </asp:ListBox>\n </td>\n\n <td style=\"height: 157px\">\n <asp:DropDownList ID=\"DropDownList1\" runat=\"server\" \n AutoPostBack=\"True\" OnSelectedIndexChanged=\"DropDownList1_SelectedIndexChanged\">\n </asp:DropDownList>\n </td> \n </tr>\n\n <tr>\n <td style=\"width: 228px; height: 40px;\">\n <asp:Label ID=\"lbllistbox\" runat=\"server\"></asp:Label>\n </td>\n\n <td style=\"height: 40px\">\n <asp:Label ID=\"lbldrpdown\" runat=\"server\">\n </asp:Label>\n </td>\n </tr>\n\n <tr>\n <td style=\"width: 228px; height: 21px\">\n </td>\n\n <td style=\"height: 21px\">\n </td> \n </tr>\n\n <tr>\n <td style=\"width: 228px; height: 21px\">\n <asp:RadioButtonList ID=\"RadioButtonList1\" runat=\"server\"\n AutoPostBack=\"True\" OnSelectedIndexChanged=\"RadioButtonList1_SelectedIndexChanged\">\n </asp:RadioButtonList>\n </td>\n\n <td style=\"height: 21px\">\n <asp:CheckBoxList ID=\"CheckBoxList1\" runat=\"server\" \n AutoPostBack=\"True\" OnSelectedIndexChanged=\"CheckBoxList1_SelectedIndexChanged\">\n </asp:CheckBoxList>\n </td> \n </tr>\n\n <tr>\n <td style=\"width: 228px; height: 21px\">\n <asp:Label ID=\"lblrdlist\" runat=\"server\">\n </asp:Label>\n </td>\n\n <td style=\"height: 21px\">\n <asp:Label ID=\"lblchklist\" runat=\"server\">\n </asp:Label>\n </td> \n </tr>\n </table> \n \n </div>\n</form>" }, { "code": null, "e": 9411, "s": 9330, "text": "Step (3) : Finally, write the following code behind routines of the application:" }, { "code": null, "e": 11625, "s": 9411, "text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n IList bklist = createbooklist();\n \n if (!this.IsPostBack)\n {\n this.ListBox1.DataSource = bklist;\n this.ListBox1.DataTextField = \"Book\";\n this.ListBox1.DataValueField = \"Author\";\n \n this.DropDownList1.DataSource = bklist;\n this.DropDownList1.DataTextField = \"Book\";\n this.DropDownList1.DataValueField = \"Author\";\n \n this.RadioButtonList1.DataSource = bklist;\n this.RadioButtonList1.DataTextField = \"Book\";\n this.RadioButtonList1.DataValueField = \"Author\";\n \n this.CheckBoxList1.DataSource = bklist;\n this.CheckBoxList1.DataTextField = \"Book\";\n this.CheckBoxList1.DataValueField = \"Author\";\n \n this.DataBind();\n }\n }\n \n protected IList createbooklist()\n {\n ArrayList allbooks = new ArrayList();\n booklist bl;\n \n bl = new booklist(\"UNIX CONCEPTS\", \"SUMITABHA DAS\");\n allbooks.Add(bl);\n \n bl = new booklist(\"PROGRAMMING IN C\", \"RICHI KERNIGHAN\");\n allbooks.Add(bl);\n \n bl = new booklist(\"DATA STRUCTURE\", \"TANENBAUM\");\n allbooks.Add(bl);\n \n bl = new booklist(\"NETWORKING CONCEPTS\", \"FOROUZAN\");\n allbooks.Add(bl);\n \n bl = new booklist(\"PROGRAMMING IN C++\", \"B. STROUSTROUP\");\n allbooks.Add(bl);\n \n bl = new booklist(\"ADVANCED JAVA\", \"SUMITABHA DAS\");\n allbooks.Add(bl);\n \n return allbooks;\n }\n \n protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)\n {\n this.lbllistbox.Text = this.ListBox1.SelectedValue;\n }\n \n protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n {\n this.lbldrpdown.Text = this.DropDownList1.SelectedValue;\n }\n \n protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)\n {\n this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;\n }\n \n protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)\n {\n this.lblchklist.Text = this.CheckBoxList1.SelectedValue;\n }\n}" }, { "code": null, "e": 11648, "s": 11625, "text": "Observe the following:" }, { "code": null, "e": 11712, "s": 11648, "text": "The booklist class has two properties: bookname and authorname." }, { "code": null, "e": 11776, "s": 11712, "text": "The booklist class has two properties: bookname and authorname." }, { "code": null, "e": 11885, "s": 11776, "text": "The createbooklist method is a user defined method that creates an array of booklist objects named allbooks." }, { "code": null, "e": 11994, "s": 11885, "text": "The createbooklist method is a user defined method that creates an array of booklist objects named allbooks." }, { "code": null, "e": 12363, "s": 11994, "text": "The Page_Load event handler ensures that a list of books is created. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list controls. The page load event handler binds the IList object 'bklist' with the list controls. The bookname property is to be displayed and the authorname property is considered as the value." }, { "code": null, "e": 12732, "s": 12363, "text": "The Page_Load event handler ensures that a list of books is created. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list controls. The page load event handler binds the IList object 'bklist' with the list controls. The bookname property is to be displayed and the authorname property is considered as the value." }, { "code": null, "e": 12973, "s": 12732, "text": "When the page is run, if the user selects a book, its name is selected and displayed by the list controls whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list control." }, { "code": null, "e": 13214, "s": 12973, "text": "When the page is run, if the user selects a book, its name is selected and displayed by the list controls whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list control." }, { "code": null, "e": 13249, "s": 13214, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 13263, "s": 13249, "text": " Anadi Sharma" }, { "code": null, "e": 13298, "s": 13263, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13321, "s": 13298, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 13355, "s": 13321, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 13375, "s": 13355, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 13410, "s": 13375, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 13427, "s": 13410, "text": " University Code" }, { "code": null, "e": 13462, "s": 13427, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13479, "s": 13462, "text": " University Code" }, { "code": null, "e": 13513, "s": 13479, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 13528, "s": 13513, "text": " Bhrugen Patel" }, { "code": null, "e": 13535, "s": 13528, "text": " Print" }, { "code": null, "e": 13546, "s": 13535, "text": " Add Notes" } ]
CSS Preprocessor SASS - GeeksforGeeks
03 Nov, 2021 The SASS is the abbreviation of Syntactically Awesome Style Sheets. It is a CSS pre-processor with syntax advancements. The style sheets in the advanced syntax are processed by the program and compiled into regular CSS style sheets, which can be used in the website. It is a CSS extension that allows to use feature like variables, nesting, imports, mixins, inheritance, etc, all in a CSS-compatible syntax ie., it is compatible with all the CSS versions. Note: Please refer to the https://sass-lang.com/install link for the detailed installation process of SASS. There are two types of syntax available for SASS: SCSS(Sassy CSS): The files using this syntax use .scss extension. Indented syntax (referred to as just “sass”): older syntax, Files using this syntax use .sass extension. Note: This example use .scss extension. Working Steps: Write the SCSS code. Compile the SCSS code into CSS code using the command sass input.scss output.css. The first filename (input.scss) is the scss file that is to be compiled and the second file name (output.css) is the processed CSS file, to be included/attached in the Html document. Include the compiled CSS file in the Html file. Now see how to make effective use of the important features of SCSS like variables, nesting, mixins, and operators. The main HTML file is named index.html SCSS file is styling.scss and the CSS file is style.css Command to compile the SCSS file: sass styling.scss style.css Example: File name index.html HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>SASS</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="style.css"></head> <body> <div id="d1">Welcome to GeeksforGeeks. <ul> <li>Algo</li> <li>DS</li> <li>Languages</li> <li>Interviews</li> <li>CS subjects</li> </ul> </div></body> </html> Variables: Variables can be used to store CSS values that may be reused. To declare a variable in SASS, the ‘$’ character is used. For eg, $v_name. $fs: 30px; $bgcolor: #00ff40; $pd: 100px 350px; #dl { font-size: $fs; color: $bgcolor; padding: $pd; } This fig. shows the same code: After compiling the CSS code, save it in file by style.css. #dl { font-size: 30px; color: #00ff40; padding: 100px 350px; } Nesting: SASS allows CSS rules to be nested within each other, which follows the same visual hierarchy of HTML. For eg. CSS property can be used to the <li> tag nested inside the div tag. $fs: 30px; $bgcolor: #00ff40; #col2: #ff0066e1; $pd: 100px 350px; #dl { font-size: $fs; color: $bgcolor; padding: $pd; li { color: $col2; } } After compiling the CSS code save it file by style.css. #dl { font-size: 30px; color: #00ff40; padding: 100px 350px; } #dl li { color: #ff0066e1; } Output: Mixins: Mixins helps to make a set of CSS properties reusable i.e. it saves one code and use it again and again. It can be included in other CSS rules by using the @include directive. Example: This example describes the use of @mixin & @include. $fs: 30px; $bgcolor: #00ff40; #col2: #ff0066e1; $pd: 100px 350px; @mixin font_style() { font-family: sans-serif; font-size: $fs; color: blue; } #dl { @include font_style(); padding: $pd; } After compiling the CSS code becomes: #dl { font-family: sans-serif; font-size: 30px; color: blue; padding: 100px 350px; } The output of the web page: Example: Mixins can also take variables as arguments. The values are passed while including them in the CSS rules. $fs: 30px; #col2: #ff0066e1; $pd: 100px 350px; @mixin font_style() { font-family: sans-serif; font-size: $fs; color: blue; } @mixin list_style($size, $color) { font-size: $size; color: $color; } #dl { @include font_style(); padding: $pd; li { @include list_style(20px, red); } } The compiled CSS code: #dl { font-family: sans-serif; font-size: 30px; color: blue; padding: 100px 350px; } #dl li { font-size: 20px; color: red; } Final Output: bhaskargeeksforgeeks CSS-Misc CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Build a Survey Form using HTML and CSS Primer CSS Flexbox Flex Direction How to Upload Image into Database and Display it using PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27681, "s": 27653, "text": "\n03 Nov, 2021" }, { "code": null, "e": 28138, "s": 27681, "text": "The SASS is the abbreviation of Syntactically Awesome Style Sheets. It is a CSS pre-processor with syntax advancements. The style sheets in the advanced syntax are processed by the program and compiled into regular CSS style sheets, which can be used in the website. It is a CSS extension that allows to use feature like variables, nesting, imports, mixins, inheritance, etc, all in a CSS-compatible syntax ie., it is compatible with all the CSS versions. " }, { "code": null, "e": 28246, "s": 28138, "text": "Note: Please refer to the https://sass-lang.com/install link for the detailed installation process of SASS." }, { "code": null, "e": 28296, "s": 28246, "text": "There are two types of syntax available for SASS:" }, { "code": null, "e": 28362, "s": 28296, "text": "SCSS(Sassy CSS): The files using this syntax use .scss extension." }, { "code": null, "e": 28467, "s": 28362, "text": "Indented syntax (referred to as just “sass”): older syntax, Files using this syntax use .sass extension." }, { "code": null, "e": 28507, "s": 28467, "text": "Note: This example use .scss extension." }, { "code": null, "e": 28522, "s": 28507, "text": "Working Steps:" }, { "code": null, "e": 28543, "s": 28522, "text": "Write the SCSS code." }, { "code": null, "e": 28808, "s": 28543, "text": "Compile the SCSS code into CSS code using the command sass input.scss output.css. The first filename (input.scss) is the scss file that is to be compiled and the second file name (output.css) is the processed CSS file, to be included/attached in the Html document." }, { "code": null, "e": 28856, "s": 28808, "text": "Include the compiled CSS file in the Html file." }, { "code": null, "e": 28972, "s": 28856, "text": "Now see how to make effective use of the important features of SCSS like variables, nesting, mixins, and operators." }, { "code": null, "e": 29011, "s": 28972, "text": "The main HTML file is named index.html" }, { "code": null, "e": 29067, "s": 29011, "text": "SCSS file is styling.scss and the CSS file is style.css" }, { "code": null, "e": 29129, "s": 29067, "text": "Command to compile the SCSS file: sass styling.scss style.css" }, { "code": null, "e": 29159, "s": 29129, "text": "Example: File name index.html" }, { "code": null, "e": 29164, "s": 29159, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title>SASS</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div id=\"d1\">Welcome to GeeksforGeeks. <ul> <li>Algo</li> <li>DS</li> <li>Languages</li> <li>Interviews</li> <li>CS subjects</li> </ul> </div></body> </html>", "e": 29607, "s": 29164, "text": null }, { "code": null, "e": 29755, "s": 29607, "text": "Variables: Variables can be used to store CSS values that may be reused. To declare a variable in SASS, the ‘$’ character is used. For eg, $v_name." }, { "code": null, "e": 29861, "s": 29755, "text": "$fs: 30px;\n$bgcolor: #00ff40;\n$pd: 100px 350px;\n#dl {\n font-size: $fs;\n color: $bgcolor;\n padding: $pd;\n}" }, { "code": null, "e": 29892, "s": 29861, "text": "This fig. shows the same code:" }, { "code": null, "e": 29952, "s": 29892, "text": "After compiling the CSS code, save it in file by style.css." }, { "code": null, "e": 30018, "s": 29952, "text": "#dl {\n font-size: 30px;\n color: #00ff40;\n padding: 100px 350px;\n}" }, { "code": null, "e": 30206, "s": 30018, "text": "Nesting: SASS allows CSS rules to be nested within each other, which follows the same visual hierarchy of HTML. For eg. CSS property can be used to the <li> tag nested inside the div tag." }, { "code": null, "e": 30356, "s": 30206, "text": "$fs: 30px;\n$bgcolor: #00ff40;\n#col2: #ff0066e1;\n$pd: 100px 350px;\n#dl {\n font-size: $fs;\n color: $bgcolor;\n padding: $pd;\n li {\n color: $col2;\n }\n}" }, { "code": null, "e": 30412, "s": 30356, "text": "After compiling the CSS code save it file by style.css." }, { "code": null, "e": 30508, "s": 30412, "text": "#dl {\n font-size: 30px;\n color: #00ff40;\n padding: 100px 350px;\n}\n#dl li {\n color: #ff0066e1;\n}" }, { "code": null, "e": 30516, "s": 30508, "text": "Output:" }, { "code": null, "e": 30700, "s": 30516, "text": "Mixins: Mixins helps to make a set of CSS properties reusable i.e. it saves one code and use it again and again. It can be included in other CSS rules by using the @include directive." }, { "code": null, "e": 30762, "s": 30700, "text": "Example: This example describes the use of @mixin & @include." }, { "code": null, "e": 30956, "s": 30762, "text": "$fs: 30px;\n$bgcolor: #00ff40;\n#col2: #ff0066e1;\n$pd: 100px 350px;\n@mixin font_style() {\n font-family: sans-serif;\n font-size: $fs;\n color: blue;\n}\n#dl {\n @include font_style();\n padding: $pd;\n}" }, { "code": null, "e": 30994, "s": 30956, "text": "After compiling the CSS code becomes:" }, { "code": null, "e": 31083, "s": 30994, "text": "#dl {\n font-family: sans-serif;\n font-size: 30px;\n color: blue;\n padding: 100px 350px;\n}" }, { "code": null, "e": 31111, "s": 31083, "text": "The output of the web page:" }, { "code": null, "e": 31226, "s": 31111, "text": "Example: Mixins can also take variables as arguments. The values are passed while including them in the CSS rules." }, { "code": null, "e": 31517, "s": 31226, "text": "$fs: 30px;\n#col2: #ff0066e1;\n$pd: 100px 350px;\n@mixin font_style() {\n font-family: sans-serif;\n font-size: $fs;\n color: blue;\n}\n@mixin list_style($size, $color) {\n font-size: $size;\n color: $color;\n}\n#dl {\n @include font_style();\n padding: $pd;\n li {\n @include list_style(20px, red);\n }\n}" }, { "code": null, "e": 31540, "s": 31517, "text": "The compiled CSS code:" }, { "code": null, "e": 31671, "s": 31540, "text": "#dl {\n font-family: sans-serif;\n font-size: 30px;\n color: blue;\n padding: 100px 350px;\n}\n#dl li {\n font-size: 20px;\n color: red;\n}" }, { "code": null, "e": 31685, "s": 31671, "text": "Final Output:" }, { "code": null, "e": 31706, "s": 31685, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31715, "s": 31706, "text": "CSS-Misc" }, { "code": null, "e": 31719, "s": 31715, "text": "CSS" }, { "code": null, "e": 31736, "s": 31719, "text": "Web Technologies" }, { "code": null, "e": 31834, "s": 31736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31843, "s": 31834, "text": "Comments" }, { "code": null, "e": 31856, "s": 31843, "text": "Old Comments" }, { "code": null, "e": 31906, "s": 31856, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31968, "s": 31906, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32007, "s": 31968, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 32041, "s": 32007, "text": "Primer CSS Flexbox Flex Direction" }, { "code": null, "e": 32102, "s": 32041, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 32158, "s": 32102, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 32191, "s": 32158, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32253, "s": 32191, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32296, "s": 32253, "text": "How to fetch data from an API in ReactJS ?" } ]
How to create an unordered list with square bullets in HTML?
To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles. For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add square bullets to an unordered list. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to create an unordered list with square bullets in HTML − Live Demo <!DOCTYPE html> <html> <head> <title>HTML Unordred List</title> </head> <body> <h1>Developed Countries</h1> <p>The list of developed countries :</p> <ul style="list-style-type:square"> <li>US</li> <li>Australia</li> <li>New Zealand</li> </ul> </body> </html>
[ { "code": null, "e": 1301, "s": 1062, "text": "To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles." }, { "code": null, "e": 1616, "s": 1301, "text": "For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add square bullets to an unordered list. " }, { "code": null, "e": 1778, "s": 1616, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1874, "s": 1778, "text": "You can try to run the following code to create an unordered list with square bullets in HTML −" }, { "code": null, "e": 1884, "s": 1874, "text": "Live Demo" }, { "code": null, "e": 2212, "s": 1884, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Unordred List</title>\n </head>\n <body>\n <h1>Developed Countries</h1>\n <p>The list of developed countries :</p>\n <ul style=\"list-style-type:square\">\n <li>US</li>\n <li>Australia</li>\n <li>New Zealand</li>\n </ul>\n </body>\n</html>" } ]
PyQtGraph – X Change Signal for Bar Graph - GeeksforGeeks
29 Nov, 2021 In this article we will see how we can get the x-change signal for the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. X change signal is emitted when the X value of the bar graph is changed by default it is 0.We can create a plot window and bar graph with the help of commands given below # creating a pyqtgraph plot window window = pg.plot() # creating a bar graph of green color bargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g') In order to do this we use xChanged.connect method with the bar graph objectSyntax : bargraph.xChanged.connect(method)Argument : It takes method as argumentReturn : It returns None Below is the implementation Python3 # importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting X value (from origin) self.setX(200) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks") # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # signal emitted when x is changed bargraph.xChanged.connect(lambda: do_action()) # do action method called by bar graph def do_action(): # setting text to the label label.setText("X value of bar graph is Changed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sweetyty Python-gui Python-PyQt Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 25018, "s": 24990, "text": "\n29 Nov, 2021" }, { "code": null, "e": 25952, "s": 25018, "text": "In this article we will see how we can get the x-change signal for the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. X change signal is emitted when the X value of the bar graph is changed by default it is 0.We can create a plot window and bar graph with the help of commands given below " }, { "code": null, "e": 26110, "s": 25952, "text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n\n# creating a bar graph of green color\nbargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g')" }, { "code": null, "e": 26293, "s": 26110, "text": "In order to do this we use xChanged.connect method with the bar graph objectSyntax : bargraph.xChanged.connect(method)Argument : It takes method as argumentReturn : It returns None " }, { "code": null, "e": 26322, "s": 26293, "text": "Below is the implementation " }, { "code": null, "e": 26330, "s": 26322, "text": "Python3" }, { "code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting X value (from origin) self.setX(200) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel(\"Geeksforgeeks\") # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # signal emitted when x is changed bargraph.xChanged.connect(lambda: do_action()) # do action method called by bar graph def do_action(): # setting text to the label label.setText(\"X value of bar graph is Changed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28774, "s": 26330, "text": null }, { "code": null, "e": 28784, "s": 28774, "text": "Output : " }, { "code": null, "e": 28793, "s": 28784, "text": "sweetyty" }, { "code": null, "e": 28804, "s": 28793, "text": "Python-gui" }, { "code": null, "e": 28816, "s": 28804, "text": "Python-PyQt" }, { "code": null, "e": 28833, "s": 28816, "text": "Python-PyQtGraph" }, { "code": null, "e": 28840, "s": 28833, "text": "Python" }, { "code": null, "e": 28938, "s": 28840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28947, "s": 28938, "text": "Comments" }, { "code": null, "e": 28960, "s": 28947, "text": "Old Comments" }, { "code": null, "e": 28978, "s": 28960, "text": "Python Dictionary" }, { "code": null, "e": 29010, "s": 28978, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29045, "s": 29010, "text": "Read a file line by line in Python" }, { "code": null, "e": 29067, "s": 29045, "text": "Enumerate() in Python" }, { "code": null, "e": 29097, "s": 29067, "text": "Iterate over a list in Python" }, { "code": null, "e": 29139, "s": 29097, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29182, "s": 29139, "text": "Python program to convert a list to string" }, { "code": null, "e": 29219, "s": 29182, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29245, "s": 29219, "text": "Python String | replace()" } ]