title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to access and convert time using the time library in Python
The time library in Python is used to obtain time in the real world and perform various tasks related to it. You can even manipulate execution time using this module. The time module comes packaged with Python. This means you do not have to install it separately using the PIP package manager. In order to use its various functions and methods, you must first import it. import time In order to print the current local time, we will be using the ctime() function. But firstly, we must obtain the number of seconds since epoch. That is, the number of seconds since January 1st of 1970, 00:00:00. import time seconds = time.time() local_time = time.ctime(seconds) print("Local time:", local_time) Local time: Sun Jan 31 23:50:16 2021 In the above program, we first obtain the time since epoch and then provide that as an argument to the ctime function which returns the current local time. Sometimes you might want to slow down or delay the execution of the Python script. For example, you might want to print the numbers slowly while iterating through a for loop. You can do this using the sleep function in the time module. import time for i in range (1,6): print(i) time.sleep(1) The above program prints from 1 to 5 and waits 1 second before printing the next number. This way, you can avoid printing the entire content at once on the output screen. While working on the time module you will notice that you come across the sturct_time object a lot. In order to create your own object, follow the syntax below − time.struct_time(tm_year=2021, tm_mon=1, tm_mday=31, tm_hour=9, tm_min=28, tm_sec=56, tm_wday=6, tm_yday=31, tm_isdst=0) Now that you know what the struct_time object is, let us start working on printing the local time. import time seconds = time.time() curr_time = time.localtime(seconds) print(curr_time) print(“Current year −> “, curr_time.tm_year) In the above example, we obtained the object and accessed its various arguments. You can access all the different arguments following the syntax of struct_time mentioned above to get a better idea of how things work. Sometimes you might want to convert time in strings into a struct_time object. import time example = “17 July 2001” ans = time.strptime(example, “%d %B %Y”) print(ans) time.struct_time(tm_year=2001, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=198, tm_isdst=−1) You now understand the different uses and functionalities of the time module present in Python. You’ve learnt about the struct_time object and how to use and manipulate it. And also to convert string data into struct_time object. For more information on the time module and about its various other features, read through its official documentation at − https://docs.python.org/3/library/time.html.
[ { "code": null, "e": 1229, "s": 1062, "text": "The time library in Python is used to obtain time in the real world and perform various tasks related to it. You can even manipulate execution time using this module." }, { "code": null, "e": 1356, "s": 1229, "text": "The time module comes packaged with Python. This means you do not have to install it separately using the PIP package manager." }, { "code": null, "e": 1433, "s": 1356, "text": "In order to use its various functions and methods, you must first import it." }, { "code": null, "e": 1445, "s": 1433, "text": "import time" }, { "code": null, "e": 1526, "s": 1445, "text": "In order to print the current local time, we will be using the ctime() function." }, { "code": null, "e": 1657, "s": 1526, "text": "But firstly, we must obtain the number of seconds since epoch. That is, the number of seconds since January 1st of 1970, 00:00:00." }, { "code": null, "e": 1757, "s": 1657, "text": "import time\nseconds = time.time()\nlocal_time = time.ctime(seconds)\nprint(\"Local time:\", local_time)" }, { "code": null, "e": 1794, "s": 1757, "text": "Local time: Sun Jan 31 23:50:16 2021" }, { "code": null, "e": 1950, "s": 1794, "text": "In the above program, we first obtain the time since epoch and then provide that as an argument to the ctime function which returns the current local time." }, { "code": null, "e": 2125, "s": 1950, "text": "Sometimes you might want to slow down or delay the execution of the Python script. For example, you might want to print the numbers slowly while iterating through a for loop." }, { "code": null, "e": 2186, "s": 2125, "text": "You can do this using the sleep function in the time module." }, { "code": null, "e": 2249, "s": 2186, "text": "import time\nfor i in range (1,6):\n print(i)\n time.sleep(1)" }, { "code": null, "e": 2338, "s": 2249, "text": "The above program prints from 1 to 5 and waits 1 second before printing the next number." }, { "code": null, "e": 2420, "s": 2338, "text": "This way, you can avoid printing the entire content at once on the output screen." }, { "code": null, "e": 2520, "s": 2420, "text": "While working on the time module you will notice that you come across the sturct_time object a lot." }, { "code": null, "e": 2582, "s": 2520, "text": "In order to create your own object, follow the syntax below −" }, { "code": null, "e": 2709, "s": 2582, "text": "time.struct_time(tm_year=2021, tm_mon=1, tm_mday=31,\n tm_hour=9, tm_min=28, tm_sec=56,\n tm_wday=6, tm_yday=31, tm_isdst=0)" }, { "code": null, "e": 2808, "s": 2709, "text": "Now that you know what the struct_time object is, let us start working on printing the local time." }, { "code": null, "e": 2940, "s": 2808, "text": "import time\nseconds = time.time()\ncurr_time = time.localtime(seconds)\nprint(curr_time)\nprint(“Current year −> “, curr_time.tm_year)" }, { "code": null, "e": 3157, "s": 2940, "text": "In the above example, we obtained the object and accessed its various arguments. You can access all the different arguments following the syntax of struct_time mentioned above to get a better idea of how things work." }, { "code": null, "e": 3236, "s": 3157, "text": "Sometimes you might want to convert time in strings into a struct_time object." }, { "code": null, "e": 3325, "s": 3236, "text": "import time\nexample = “17 July 2001”\nans = time.strptime(example, “%d %B %Y”)\nprint(ans)" }, { "code": null, "e": 3446, "s": 3325, "text": "time.struct_time(tm_year=2001, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=198, tm_isdst=−1)" }, { "code": null, "e": 3542, "s": 3446, "text": "You now understand the different uses and functionalities of the time module present in Python." }, { "code": null, "e": 3676, "s": 3542, "text": "You’ve learnt about the struct_time object and how to use and manipulate it. And also to convert string data into struct_time object." }, { "code": null, "e": 3844, "s": 3676, "text": "For more information on the time module and about its various other features, read through its official documentation at − https://docs.python.org/3/library/time.html." } ]
Using Matplotlib for Animations
04 May, 2022 Matplotlib library of Python is a plotting tool used to plot graphs of functions or figures. It can also be used as an animation tool too. The plotted graphs when added with animations gives a more powerful visualization and helps the presenter to catch a larger number of audience. Matplotlib can also easily connect with Pandas to create even more sophisticated animations. Animations in Matplotlib can be made by using the Animation class in two ways: By calling a function over and over: It uses a predefined function which when ran again and again creates an animation. By using fixed objects: Some animated artistic objects when combined with others yield an animation scene. It is important to note that we must at all points keep a reference to the animated object or else the animation will stop. This is because the Animation class holds a single pointer reference to the animation object and as the time advances to run the animation this pointer reference must be kept otherwise it will be collected as a garbage value. Though there are two ways, the first way is more common and convenient and here, we will make use of that only. However, you can read the documentation of the other as well, here . Let’s dive into Matplotlib animations. Installations required: 1. Numpy and Matplotlib2. ffmpeg Download ffmpeg for Python from here. Let’s check an example. Here we will try and make a continuous sine wave using animations and plotting tools. We will make use of numpy and pyplot from matplotlib for this. As already said, we will be using the function method as opposed to the artistic objects. Note: To save an animation to your computer, use anim.save(filename) or Animation.to_html5_video. from matplotlib import pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimation # initializing a figure in # which the graph will be plottedfig = plt.figure() # marking the x-axis and y-axisaxis = plt.axes(xlim =(0, 4), ylim =(-2, 2)) # initializing a line variableline, = axis.plot([], [], lw = 3) # data which the line will # contain (x, y)def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 4, 1000) # plots a sine graph y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, anim = FuncAnimation(fig, animate, init_func = init, frames = 200, interval = 20, blit = True) anim.save('continuousSineWave.mp4', writer = 'ffmpeg', fps = 30) At first, after importing the necessities, we set a blank figure or a blank window on which the entire animation will be drawn. Next we initialize a variable line which will contain the x and y co-ordinates of the plot. These are kept empty at first as the data in it will continuously keep changing because of the animation. Finally, we state the animation function animate(i) which takes an argument i, where i is called the frame number and using this we create the sine wave(or any other figure) which will continuously vary depending upon the value of i. In the last line anim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) we use the FuncAnimation function to create an animation which will display 200 frames per second and in an interval of 20 micro secs. Output : Now that’s a very powerful visualization. One thing to note is that when we view our saved gif, it will be a continuous clip unlike the video in our output which gets terminated in a few seconds. Let’s look at one more example. Try to guess the output as we code the program as it will clear our concept. import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np # creating a blank window# for the animation fig = plt.figure() axis = plt.axes(xlim =(-50, 50), ylim =(-50, 50)) line, = axis.plot([], [], lw = 2) # what will our line dataset# contain?def init(): line.set_data([], []) return line, # initializing empty values# for x and y co-ordinatesxdata, ydata = [], [] # animation function def animate(i): # t is a parameter which varies # with the frame number t = 0.1 * i # x, y values to be plotted x = t * np.sin(t) y = t * np.cos(t) # appending values to the previously # empty x and y data holders xdata.append(x) ydata.append(y) line.set_data(xdata, ydata) return line, # calling the animation function anim = animation.FuncAnimation(fig, animate, init_func = init, frames = 500, interval = 20, blit = True) # saves the animation in our desktopanim.save('growingCoil.mp4', writer = 'ffmpeg', fps = 30) As we might already have guessed and as obvious as the saved file name suggests, it’s an animation of a continuously growing coil. Just as before, we first import all the modules. But this time, we import the matplotlib.animation library completely import matplotlib.animation as animation however, in the previous example, we imported just the FuncAnimation function from it from matplotlib.animation import FuncAnimation However, this does not really make any changes and one can choose any way of importing. Then we create a figure on which the animation will be placed. The animate function varies with the frame number i. One thing to know is that a coil is nothing but a composite function of sine and cos. We take the sine function in x-axis and cos in y-axis and the resultant figure gives a coil. Output: Hence, we conclude that many interesting animations can be made by using some basic knowledge of matplotlib. This really comes in handy when one needs to present some visualizations with additional power of animation without using higher level animation tools such as Blender. redvimo Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 May, 2022" }, { "code": null, "e": 430, "s": 54, "text": "Matplotlib library of Python is a plotting tool used to plot graphs of functions or figures. It can also be used as an animation tool too. The plotted graphs when added with animations gives a more powerful visualization and helps the presenter to catch a larger number of audience. Matplotlib can also easily connect with Pandas to create even more sophisticated animations." }, { "code": null, "e": 509, "s": 430, "text": "Animations in Matplotlib can be made by using the Animation class in two ways:" }, { "code": null, "e": 629, "s": 509, "text": "By calling a function over and over: It uses a predefined function which when ran again and again creates an animation." }, { "code": null, "e": 736, "s": 629, "text": "By using fixed objects: Some animated artistic objects when combined with others yield an animation scene." }, { "code": null, "e": 1086, "s": 736, "text": "It is important to note that we must at all points keep a reference to the animated object or else the animation will stop. This is because the Animation class holds a single pointer reference to the animation object and as the time advances to run the animation this pointer reference must be kept otherwise it will be collected as a garbage value." }, { "code": null, "e": 1267, "s": 1086, "text": "Though there are two ways, the first way is more common and convenient and here, we will make use of that only. However, you can read the documentation of the other as well, here ." }, { "code": null, "e": 1306, "s": 1267, "text": "Let’s dive into Matplotlib animations." }, { "code": null, "e": 1330, "s": 1306, "text": "Installations required:" }, { "code": null, "e": 1363, "s": 1330, "text": "1. Numpy and Matplotlib2. ffmpeg" }, { "code": null, "e": 1401, "s": 1363, "text": "Download ffmpeg for Python from here." }, { "code": null, "e": 1664, "s": 1401, "text": "Let’s check an example. Here we will try and make a continuous sine wave using animations and plotting tools. We will make use of numpy and pyplot from matplotlib for this. As already said, we will be using the function method as opposed to the artistic objects." }, { "code": null, "e": 1762, "s": 1664, "text": "Note: To save an animation to your computer, use anim.save(filename) or Animation.to_html5_video." }, { "code": "from matplotlib import pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimation # initializing a figure in # which the graph will be plottedfig = plt.figure() # marking the x-axis and y-axisaxis = plt.axes(xlim =(0, 4), ylim =(-2, 2)) # initializing a line variableline, = axis.plot([], [], lw = 3) # data which the line will # contain (x, y)def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 4, 1000) # plots a sine graph y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, anim = FuncAnimation(fig, animate, init_func = init, frames = 200, interval = 20, blit = True) anim.save('continuousSineWave.mp4', writer = 'ffmpeg', fps = 30)", "e": 2565, "s": 1762, "text": null }, { "code": null, "e": 3364, "s": 2565, "text": "At first, after importing the necessities, we set a blank figure or a blank window on which the entire animation will be drawn. Next we initialize a variable line which will contain the x and y co-ordinates of the plot. These are kept empty at first as the data in it will continuously keep changing because of the animation. Finally, we state the animation function animate(i) which takes an argument i, where i is called the frame number and using this we create the sine wave(or any other figure) which will continuously vary depending upon the value of i. In the last line anim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) we use the FuncAnimation function to create an animation which will display 200 frames per second and in an interval of 20 micro secs." }, { "code": null, "e": 3373, "s": 3364, "text": "Output :" }, { "code": null, "e": 3678, "s": 3373, "text": "Now that’s a very powerful visualization. One thing to note is that when we view our saved gif, it will be a continuous clip unlike the video in our output which gets terminated in a few seconds. Let’s look at one more example. Try to guess the output as we code the program as it will clear our concept." }, { "code": "import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np # creating a blank window# for the animation fig = plt.figure() axis = plt.axes(xlim =(-50, 50), ylim =(-50, 50)) line, = axis.plot([], [], lw = 2) # what will our line dataset# contain?def init(): line.set_data([], []) return line, # initializing empty values# for x and y co-ordinatesxdata, ydata = [], [] # animation function def animate(i): # t is a parameter which varies # with the frame number t = 0.1 * i # x, y values to be plotted x = t * np.sin(t) y = t * np.cos(t) # appending values to the previously # empty x and y data holders xdata.append(x) ydata.append(y) line.set_data(xdata, ydata) return line, # calling the animation function anim = animation.FuncAnimation(fig, animate, init_func = init, frames = 500, interval = 20, blit = True) # saves the animation in our desktopanim.save('growingCoil.mp4', writer = 'ffmpeg', fps = 30)", "e": 4763, "s": 3678, "text": null }, { "code": null, "e": 5012, "s": 4763, "text": "As we might already have guessed and as obvious as the saved file name suggests, it’s an animation of a continuously growing coil. Just as before, we first import all the modules. But this time, we import the matplotlib.animation library completely" }, { "code": null, "e": 5053, "s": 5012, "text": "import matplotlib.animation as animation" }, { "code": null, "e": 5139, "s": 5053, "text": "however, in the previous example, we imported just the FuncAnimation function from it" }, { "code": null, "e": 5186, "s": 5139, "text": "from matplotlib.animation import FuncAnimation" }, { "code": null, "e": 5569, "s": 5186, "text": "However, this does not really make any changes and one can choose any way of importing. Then we create a figure on which the animation will be placed. The animate function varies with the frame number i. One thing to know is that a coil is nothing but a composite function of sine and cos. We take the sine function in x-axis and cos in y-axis and the resultant figure gives a coil." }, { "code": null, "e": 5577, "s": 5569, "text": "Output:" }, { "code": null, "e": 5854, "s": 5577, "text": "Hence, we conclude that many interesting animations can be made by using some basic knowledge of matplotlib. This really comes in handy when one needs to present some visualizations with additional power of animation without using higher level animation tools such as Blender." }, { "code": null, "e": 5862, "s": 5854, "text": "redvimo" }, { "code": null, "e": 5880, "s": 5862, "text": "Python-matplotlib" }, { "code": null, "e": 5887, "s": 5880, "text": "Python" } ]
ML | Cancer cell classification using Scikit-learn
21 Oct, 2021 Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let’s classify cancer cells based on their features, and identifying them if they are ‘malignant’ or ‘benign’. We will be using scikit-learn for a machine learning problem. Scikit-learn is an open-source machine learning, data mining and data analysis library for Python programming language.The dataset: Scikit-learn comes with a few small standard datasets that do not require downloading any file from any external website. The dataset that we will be using for our machine learning problem is the Breast cancer wisconsin (diagnostic) dataset. The dataset includes several data about the breast cancer tumors along with the classifications labels, viz., malignant or benign. It can be loaded using the following function: load_breast_cancer([return_X_y]) The data set has 569 instances or data of 569 tumors and includes data on 30 attributes or features like the radius, texture, perimeter, area, etc. of a tumor. We will be using these features to train our model.Installing the necessary modules: For this machine learning project, we will be needing the ‘Scikit-learn’ Python module. If you don’t have it installed on your machine, download and install it by running the following command in the command prompt: pip install scikit-learn Note: You can use any IDE for this project, by it is highly recommended Jupyter notebook for the project. This is because, since Python is an interpreted language, so, one can take its full advantage by running a few lines of code and see and understand what’s happening, step by step, instead of writing the whole script and once and then running it. Install it by running the following command in the command prompt: pip install jupyter Step #1: Importing the necessary module and dataset.We will be needing the ‘Scikit-learn’ module and the Breast cancer wisconsin (diagnostic) dataset. Python3 # importing the Python moduleimport sklearn # importing the datasetfrom sklearn.datasets import load_breast_cancer Step #2: Loading the dataset to a variable. Python3 # loading the datasetdata = load_breast_cancer() The important attributes that we must consider from that dataset are ‘target-names'(the meaning of the labels), ‘target'(the classification labels), ‘feature_names'(the meaning of the features) and ‘data'(the data to learn).Step #3: Organizing the data and looking at it. To get a better understanding of what the dataset contains and how we can use the data to train our model, let us first organize the data and then see what it contains by using the print() function. Python3 # Organize our datalabel_names = data['target_names']labels = data['target']feature_names = data['feature_names']features = data['data'] Then, using the print() function, let us examine the data. Python3 # looking at the dataprint(label_names) Output: ['malignant' 'benign'] So, we see that each dataset of a tumor is labelled as either ‘malignant’ or ‘benign’. Python3 print(labels) Output: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 1 0 0 1 1 1 1 0 1 0 0 1 1 1 1 0 1 0 0 1 0 1 0 0 1 1 1 0 0 1 0 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 1 1 0 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 0 1 0 1 0 1 1 1 0 1 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 1 0 1 0 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 1 1 0 0 1 0 1 1 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1] From here, we see that each label is linked to binary values of 0 and 1, where 0 represents malignant tumors and 1 represents benign tumors. Python3 print(feature_names) Output: ['mean radius' 'mean texture' 'mean perimeter' 'mean area' 'mean smoothness' 'mean compactness' 'mean concavity' 'mean concave points' 'mean symmetry' 'mean fractal dimension' 'radius error' 'texture error' 'perimeter error' 'area error' 'smoothness error' 'compactness error' 'concavity error' 'concave points error' 'symmetry error' 'fractal dimension error' 'worst radius' 'worst texture' 'worst perimeter' 'worst area' 'worst smoothness' 'worst compactness' 'worst concavity' 'worst concave points' 'worst symmetry' 'worst fractal dimension'] Here, we see all the 30 features or attributes that each dataset of the tumor has. We will be using the numerical values of these features in training our model and make the correct prediction, whether or not a tumor is malignant or benign, based on these features. Python3 print(features) Output: [[1.799e+01 1.038e+01 1.228e+02 ... 2.654e-01 4.601e-01 1.189e-01] [2.057e+01 1.777e+01 1.329e+02 ... 1.860e-01 2.750e-01 8.902e-02] [1.969e+01 2.125e+01 1.300e+02 ... 2.430e-01 3.613e-01 8.758e-02] ... [1.660e+01 2.808e+01 1.083e+02 ... 1.418e-01 2.218e-01 7.820e-02] [2.060e+01 2.933e+01 1.401e+02 ... 2.650e-01 4.087e-01 1.240e-01] [7.760e+00 2.454e+01 4.792e+01 ... 0.000e+00 2.871e-01 7.039e-02]] This is a huge dataset containing the numerical values of the 30 attributes of all the 569 instances of tumor data.So, from the above data, we can conclude that the first instance of tumor is malignant and it has a mean radius of value 1.79900000e+01. Step #4: Organizing the data into Sets.For testing the accuracy of our classifier, we must test the model on unseen data. So, before building the model, we will split our data into two sets, viz., training set and test set. We will be using the training set to train and evaluate the model and then use the trained model to make predictions on the unseen test set. The sklearn module has a built-in function called the train_test_split(), which automatically divides the data into these sets. We will be using this function two split the data. Python3 # importing the functionfrom sklearn.model_selection import train_test_split # splitting the datatrain, test, train_labels, test_labels = train_test_split(features, labels, test_size = 0.33, random_state = 42) The train_test_split() function randomly splits the data using the parameter test_size. What we have done here is that we have split 33% of the original data into test data (test). The remaining data (train) is the training data. Also, we have respective labels for both the train variables and test variables, i.e. train_labels and test_labels.To learn more about how to use the train_test_split() function, you can refer to the official documentation. Step #5: Building the Model.There are many machine learning models to choose from. All of them have their own advantages and disadvantages. For this model, we will be using the Naive Bayes algorithm that usually performs well in binary classification tasks. Firstly, import the GaussianNB module and initialize it using the GaussianNB() function. Then train the model by fitting it to the data in the dataset using the fit() method. Python3 # importing the module of the machine learning modelfrom sklearn.naive_bayes import GaussianNB # initializing the classifiergnb = GaussianNB() # training the classifiermodel = gnb.fit(train, train_labels) After the training is complete, we can use the trained model to make predictions on our test set that we have prepared before. To do that, we will use the built-in predict() function which returns an array of prediction values for data instance in the test set. We will then print our predictions using the print() function. Python3 # making the predictionspredictions = gnb.predict(test) # printing the predictionsprint(predictions) Output: [1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1] From the output above, we see that the predict() function returned an array of 0s and 1s. These values represent the predicted values of the test set for the tumor class (malignant or benign). Step #6: Evaluating the trained model’s accuracy.As we have predicted values now, we can evaluate our model’s accuracy by comparing it with the actual labels of the test set, i.e., comparing predictions with test_labels. For this purpose, we will be using the built-in accuracy_score() function in the sklearn module. Python3 # importing the accuracy measuring functionfrom sklearn.metrics import accuracy_score # evaluating the accuracyprint(accuracy_score(test_labels, predictions)) Output: 0.9414893617021277 So, we find out that this machine learning classifier based on the Naive Bayes algorithm is 94.15% accurate in predicting whether a tumor is malignant or benign. rajeev0719singh sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g Advanced Computer Subject Machine Learning Project Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Oct, 2021" }, { "code": null, "e": 1001, "s": 52, "text": "Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let’s classify cancer cells based on their features, and identifying them if they are ‘malignant’ or ‘benign’. We will be using scikit-learn for a machine learning problem. Scikit-learn is an open-source machine learning, data mining and data analysis library for Python programming language.The dataset: Scikit-learn comes with a few small standard datasets that do not require downloading any file from any external website. The dataset that we will be using for our machine learning problem is the Breast cancer wisconsin (diagnostic) dataset. The dataset includes several data about the breast cancer tumors along with the classifications labels, viz., malignant or benign. It can be loaded using the following function: " }, { "code": null, "e": 1034, "s": 1001, "text": "load_breast_cancer([return_X_y])" }, { "code": null, "e": 1497, "s": 1034, "text": "The data set has 569 instances or data of 569 tumors and includes data on 30 attributes or features like the radius, texture, perimeter, area, etc. of a tumor. We will be using these features to train our model.Installing the necessary modules: For this machine learning project, we will be needing the ‘Scikit-learn’ Python module. If you don’t have it installed on your machine, download and install it by running the following command in the command prompt: " }, { "code": null, "e": 1522, "s": 1497, "text": "pip install scikit-learn" }, { "code": null, "e": 1943, "s": 1522, "text": "Note: You can use any IDE for this project, by it is highly recommended Jupyter notebook for the project. This is because, since Python is an interpreted language, so, one can take its full advantage by running a few lines of code and see and understand what’s happening, step by step, instead of writing the whole script and once and then running it. Install it by running the following command in the command prompt: " }, { "code": null, "e": 1963, "s": 1943, "text": "pip install jupyter" }, { "code": null, "e": 2118, "s": 1965, "text": "Step #1: Importing the necessary module and dataset.We will be needing the ‘Scikit-learn’ module and the Breast cancer wisconsin (diagnostic) dataset. " }, { "code": null, "e": 2126, "s": 2118, "text": "Python3" }, { "code": "# importing the Python moduleimport sklearn # importing the datasetfrom sklearn.datasets import load_breast_cancer", "e": 2241, "s": 2126, "text": null }, { "code": null, "e": 2289, "s": 2241, "text": " Step #2: Loading the dataset to a variable. " }, { "code": null, "e": 2297, "s": 2289, "text": "Python3" }, { "code": "# loading the datasetdata = load_breast_cancer()", "e": 2346, "s": 2297, "text": null }, { "code": null, "e": 2819, "s": 2346, "text": "The important attributes that we must consider from that dataset are ‘target-names'(the meaning of the labels), ‘target'(the classification labels), ‘feature_names'(the meaning of the features) and ‘data'(the data to learn).Step #3: Organizing the data and looking at it. To get a better understanding of what the dataset contains and how we can use the data to train our model, let us first organize the data and then see what it contains by using the print() function. " }, { "code": null, "e": 2827, "s": 2819, "text": "Python3" }, { "code": "# Organize our datalabel_names = data['target_names']labels = data['target']feature_names = data['feature_names']features = data['data']", "e": 2964, "s": 2827, "text": null }, { "code": null, "e": 3025, "s": 2964, "text": "Then, using the print() function, let us examine the data. " }, { "code": null, "e": 3033, "s": 3025, "text": "Python3" }, { "code": "# looking at the dataprint(label_names)", "e": 3073, "s": 3033, "text": null }, { "code": null, "e": 3083, "s": 3073, "text": "Output: " }, { "code": null, "e": 3106, "s": 3083, "text": "['malignant' 'benign']" }, { "code": null, "e": 3195, "s": 3106, "text": "So, we see that each dataset of a tumor is labelled as either ‘malignant’ or ‘benign’. " }, { "code": null, "e": 3203, "s": 3195, "text": "Python3" }, { "code": "print(labels)", "e": 3217, "s": 3203, "text": null }, { "code": null, "e": 3227, "s": 3217, "text": "Output: " }, { "code": null, "e": 4382, "s": 3227, "text": "[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 1 0 0 1 1 1 1 0 1 0 0 1 1 1 1 0 1 0 0\n 1 0 1 0 0 1 1 1 0 0 1 0 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 0 1 1\n 1 1 1 1 1 1 0 0 0 1 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 1 1 0 1 1 0 1 1 1 1 0 1\n 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 0 1 0\n 1 0 1 1 1 0 1 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 1 0 1 0 0 0 0 1 1 0 0 1 1\n 1 0 1 1 1 1 1 0 0 1 1 0 1 1 0 0 1 0 1 1 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1\n 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1\n 1 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0\n 0 1 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1\n 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 0 1 1\n 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1\n 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 0 0\n 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 0 0 0 0 0 0 1]" }, { "code": null, "e": 4525, "s": 4382, "text": "From here, we see that each label is linked to binary values of 0 and 1, where 0 represents malignant tumors and 1 represents benign tumors. " }, { "code": null, "e": 4533, "s": 4525, "text": "Python3" }, { "code": "print(feature_names)", "e": 4554, "s": 4533, "text": null }, { "code": null, "e": 4564, "s": 4554, "text": "Output: " }, { "code": null, "e": 5119, "s": 4564, "text": "['mean radius' 'mean texture' 'mean perimeter' 'mean area'\n 'mean smoothness' 'mean compactness' 'mean concavity'\n 'mean concave points' 'mean symmetry' 'mean fractal dimension'\n 'radius error' 'texture error' 'perimeter error' 'area error'\n 'smoothness error' 'compactness error' 'concavity error'\n 'concave points error' 'symmetry error' 'fractal dimension error'\n 'worst radius' 'worst texture' 'worst perimeter' 'worst area'\n 'worst smoothness' 'worst compactness' 'worst concavity'\n 'worst concave points' 'worst symmetry' 'worst fractal dimension']" }, { "code": null, "e": 5387, "s": 5119, "text": "Here, we see all the 30 features or attributes that each dataset of the tumor has. We will be using the numerical values of these features in training our model and make the correct prediction, whether or not a tumor is malignant or benign, based on these features. " }, { "code": null, "e": 5395, "s": 5387, "text": "Python3" }, { "code": "print(features)", "e": 5411, "s": 5395, "text": null }, { "code": null, "e": 5421, "s": 5411, "text": "Output: " }, { "code": null, "e": 5829, "s": 5421, "text": "[[1.799e+01 1.038e+01 1.228e+02 ... 2.654e-01 4.601e-01 1.189e-01]\n [2.057e+01 1.777e+01 1.329e+02 ... 1.860e-01 2.750e-01 8.902e-02]\n [1.969e+01 2.125e+01 1.300e+02 ... 2.430e-01 3.613e-01 8.758e-02]\n ...\n [1.660e+01 2.808e+01 1.083e+02 ... 1.418e-01 2.218e-01 7.820e-02]\n [2.060e+01 2.933e+01 1.401e+02 ... 2.650e-01 4.087e-01 1.240e-01]\n [7.760e+00 2.454e+01 4.792e+01 ... 0.000e+00 2.871e-01 7.039e-02]]" }, { "code": null, "e": 6629, "s": 5829, "text": "This is a huge dataset containing the numerical values of the 30 attributes of all the 569 instances of tumor data.So, from the above data, we can conclude that the first instance of tumor is malignant and it has a mean radius of value 1.79900000e+01. Step #4: Organizing the data into Sets.For testing the accuracy of our classifier, we must test the model on unseen data. So, before building the model, we will split our data into two sets, viz., training set and test set. We will be using the training set to train and evaluate the model and then use the trained model to make predictions on the unseen test set. The sklearn module has a built-in function called the train_test_split(), which automatically divides the data into these sets. We will be using this function two split the data. " }, { "code": null, "e": 6637, "s": 6629, "text": "Python3" }, { "code": "# importing the functionfrom sklearn.model_selection import train_test_split # splitting the datatrain, test, train_labels, test_labels = train_test_split(features, labels, test_size = 0.33, random_state = 42)", "e": 6885, "s": 6637, "text": null }, { "code": null, "e": 7775, "s": 6885, "text": "The train_test_split() function randomly splits the data using the parameter test_size. What we have done here is that we have split 33% of the original data into test data (test). The remaining data (train) is the training data. Also, we have respective labels for both the train variables and test variables, i.e. train_labels and test_labels.To learn more about how to use the train_test_split() function, you can refer to the official documentation. Step #5: Building the Model.There are many machine learning models to choose from. All of them have their own advantages and disadvantages. For this model, we will be using the Naive Bayes algorithm that usually performs well in binary classification tasks. Firstly, import the GaussianNB module and initialize it using the GaussianNB() function. Then train the model by fitting it to the data in the dataset using the fit() method. " }, { "code": null, "e": 7783, "s": 7775, "text": "Python3" }, { "code": "# importing the module of the machine learning modelfrom sklearn.naive_bayes import GaussianNB # initializing the classifiergnb = GaussianNB() # training the classifiermodel = gnb.fit(train, train_labels)", "e": 7988, "s": 7783, "text": null }, { "code": null, "e": 8315, "s": 7988, "text": "After the training is complete, we can use the trained model to make predictions on our test set that we have prepared before. To do that, we will use the built-in predict() function which returns an array of prediction values for data instance in the test set. We will then print our predictions using the print() function. " }, { "code": null, "e": 8323, "s": 8315, "text": "Python3" }, { "code": "# making the predictionspredictions = gnb.predict(test) # printing the predictionsprint(predictions)", "e": 8424, "s": 8323, "text": null }, { "code": null, "e": 8434, "s": 8424, "text": "Output: " }, { "code": null, "e": 8817, "s": 8434, "text": "[1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 0\n 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0\n 1 1 1 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0\n 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 1 0 0\n 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 0\n 0 1 1]" }, { "code": null, "e": 9332, "s": 8817, "text": "From the output above, we see that the predict() function returned an array of 0s and 1s. These values represent the predicted values of the test set for the tumor class (malignant or benign). Step #6: Evaluating the trained model’s accuracy.As we have predicted values now, we can evaluate our model’s accuracy by comparing it with the actual labels of the test set, i.e., comparing predictions with test_labels. For this purpose, we will be using the built-in accuracy_score() function in the sklearn module. " }, { "code": null, "e": 9340, "s": 9332, "text": "Python3" }, { "code": "# importing the accuracy measuring functionfrom sklearn.metrics import accuracy_score # evaluating the accuracyprint(accuracy_score(test_labels, predictions))", "e": 9499, "s": 9340, "text": null }, { "code": null, "e": 9509, "s": 9499, "text": "Output: " }, { "code": null, "e": 9528, "s": 9509, "text": "0.9414893617021277" }, { "code": null, "e": 9691, "s": 9528, "text": "So, we find out that this machine learning classifier based on the Naive Bayes algorithm is 94.15% accurate in predicting whether a tumor is malignant or benign. " }, { "code": null, "e": 9707, "s": 9691, "text": "rajeev0719singh" }, { "code": null, "e": 9748, "s": 9707, "text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g" }, { "code": null, "e": 9774, "s": 9748, "text": "Advanced Computer Subject" }, { "code": null, "e": 9791, "s": 9774, "text": "Machine Learning" }, { "code": null, "e": 9799, "s": 9791, "text": "Project" }, { "code": null, "e": 9806, "s": 9799, "text": "Python" }, { "code": null, "e": 9825, "s": 9806, "text": "Technical Scripter" }, { "code": null, "e": 9842, "s": 9825, "text": "Machine Learning" } ]
Comparing float value in PHP
11 May, 2021 In PHP, the size of a floating values is platform-dependent. Due to internal representation of floating point numbers, there might be unexpected output while performing or testing floating point values for equality. For example, see the following program. PHP <?php // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Compare the valuesif($value1 == $value2) { echo 'True';}else { echo 'False';} ?> False Explanation: The output of this code is False which is very unpredictable but in PHP the value1 is not exactly 1.6 i.e it is coming from the difference between 8 and 6.4 which actually turned out to be 1.599999 that is why this statement turned out to be false. How to resolve above problem? Method 1 : For equality testing in floating point values, use the machine epsilon or we can call it smallest difference in calculation in computer systems. Program 1: PHP <?php// PHP program to compare floating values // Declare variable and initializing// it by floating value$value1 = 1.23456789;$value2 = 1.23456780;$epsilon = 0.00001; // Use absolute difference and compare valuesif(abs($value1 - $value2) < $epsilon) { echo "True";}else { echo "False";} ?> True Explanation: In this code use two floating point numbers value1 and value2 along with epsilon. Now take the absolute difference of values (value1 and value2) by using the predefined function named as abs(). This code will give the absolute value but the question is why we are taking the absolute values. You can see that both the values having same digits after decimal upto precision value 7. Which is very difficult for the system to analyze the comparison. Method 2 : We can use round function in PHP. PHP <?php// PHP program to compare floating values // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Use round function to round off the// floating value upto two decimal place// and then compare it.var_dump(round($value1, 2) == round($value2, 2)); ?> bool(true) surinderdawra388 PHP-basics Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2021" }, { "code": null, "e": 284, "s": 28, "text": "In PHP, the size of a floating values is platform-dependent. Due to internal representation of floating point numbers, there might be unexpected output while performing or testing floating point values for equality. For example, see the following program." }, { "code": null, "e": 288, "s": 284, "text": "PHP" }, { "code": "<?php // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Compare the valuesif($value1 == $value2) { echo 'True';}else { echo 'False';} ?>", "e": 454, "s": 288, "text": null }, { "code": null, "e": 460, "s": 454, "text": "False" }, { "code": null, "e": 724, "s": 462, "text": "Explanation: The output of this code is False which is very unpredictable but in PHP the value1 is not exactly 1.6 i.e it is coming from the difference between 8 and 6.4 which actually turned out to be 1.599999 that is why this statement turned out to be false." }, { "code": null, "e": 910, "s": 724, "text": "How to resolve above problem? Method 1 : For equality testing in floating point values, use the machine epsilon or we can call it smallest difference in calculation in computer systems." }, { "code": null, "e": 923, "s": 910, "text": "Program 1: " }, { "code": null, "e": 927, "s": 923, "text": "PHP" }, { "code": "<?php// PHP program to compare floating values // Declare variable and initializing// it by floating value$value1 = 1.23456789;$value2 = 1.23456780;$epsilon = 0.00001; // Use absolute difference and compare valuesif(abs($value1 - $value2) < $epsilon) { echo \"True\";}else { echo \"False\";} ?>", "e": 1224, "s": 927, "text": null }, { "code": null, "e": 1229, "s": 1224, "text": "True" }, { "code": null, "e": 1693, "s": 1231, "text": "Explanation: In this code use two floating point numbers value1 and value2 along with epsilon. Now take the absolute difference of values (value1 and value2) by using the predefined function named as abs(). This code will give the absolute value but the question is why we are taking the absolute values. You can see that both the values having same digits after decimal upto precision value 7. Which is very difficult for the system to analyze the comparison. " }, { "code": null, "e": 1740, "s": 1693, "text": "Method 2 : We can use round function in PHP. " }, { "code": null, "e": 1744, "s": 1740, "text": "PHP" }, { "code": "<?php// PHP program to compare floating values // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Use round function to round off the// floating value upto two decimal place// and then compare it.var_dump(round($value1, 2) == round($value2, 2)); ?>", "e": 2015, "s": 1744, "text": null }, { "code": null, "e": 2026, "s": 2015, "text": "bool(true)" }, { "code": null, "e": 2045, "s": 2028, "text": "surinderdawra388" }, { "code": null, "e": 2056, "s": 2045, "text": "PHP-basics" }, { "code": null, "e": 2063, "s": 2056, "text": "Picked" }, { "code": null, "e": 2067, "s": 2063, "text": "PHP" }, { "code": null, "e": 2080, "s": 2067, "text": "PHP Programs" }, { "code": null, "e": 2097, "s": 2080, "text": "Web Technologies" }, { "code": null, "e": 2101, "s": 2097, "text": "PHP" } ]
When to use useCallback, useMemo and useEffect ?
26 Jul, 2021 The useCallback, useMemo, and useEffect are a way to optimize the performance of React-based applications between rerendering of components. These functions provide some of the features of the class-based components like persistence of dedicated states through render calls as well as the lifecycle functions to control how the components look over various stages of their lifecycle. To answer when to use useCallBack, useMemo, and useEffect, we should know what exactly they do and how they are different. useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed.useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change.useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function. useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed. useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed. useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change. useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change. useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function. useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function. Creating a react application for understanding all the three hooks: Step 1: Create a React application using the following command:npx create-react-app usecallbackdemo Step 1: Create a React application using the following command: npx create-react-app usecallbackdemo Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd usecallbackdemo Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd usecallbackdemo Project Structure: It will look like the following. The project structure Now let’s understand the working of all three hooks. 1. usecallback: It depends on referential equality. In javascript, functions are first-class citizens, meaning that a function is a regular object. Hence, two function objects even when they share the same code are two different objects. Just remember that a function object is referentially equal only to itself. Let’s see this in the following code, doubleFactory creates and returns a function: Javascript function doubleFactory(){ return (a) => 2*a;} const double1 = doubleFactory();const double2 = doubleFactory(); double1(8); // gives 16double2(8); // gives 16 double1 === double2; // falsedouble1 === double1; // true doube1 and double2 doubles the value passed to them and are created by the same factory function. The two functions even when they share the same code, are not equal, here (double1 === double2) evaluates to false. When to use useCallback: In React, a component usually has some callback function created within it. Javascript function MyComponent(){ // HandleChange is created on every render const handleChange = () => {...}; return <> ... </>;} Here handleChange function objects are different on every rendering of MyComponent. And there are several cases when we may want the same function object between multiple renderings. For example when it’s a dependency for some other hooks (useEffect( ..., callbackfunc)) or when the function object itself has some internal state that we need to maintain. In such a case, useCallback hook comes handy. In simple words, useCallback( callBackFun, deps ) returns a memorized callback when the dependency values deps do not change between renderings. (memoized here refers to caching the object for future use). Let’s see a use case using a project: The application consists of an input field, a button, and a list. The list is a component that consists of two numbers, the first is input plus 10 and the second is input + 100. The button changes the components from dark mode to light mode and vice versa. There’s going to be two components App and List, App is our main component where we add input field, button, and List. The list component is used to print the list of items depending on the input field. App.jsx import React, { useState} from "react"import List from "./List" function App(){ {/* Initial states */} const [input, setInput] = useState(1); const [light, setLight] = useState(true); {/* getItems() returns a list of number which is number+10 and number + 100 */} const getItems = () => { return [input + 10, input + 100]; } {/* Style for changing the theme */} const theme = { backgroundColor: light ? "White": "grey", color: light ? "grey" : "white" } return <> {/* set the theme in the parent div */} <div style={theme}> <input type="number" value={input} {/* When we input a number it is stored in our stateful variable */} onChange={event => setInput(parseInt(event.target.value))} /> {/* on click the button the theme is set to the opposite mode, light to dark and vice versa*/} <button onClick={() => setLight(prevLight => !prevLight)}> {light ? "dark mode":"light mode"} </button> <List getItems={getItems} /> </div> </>;} export default App; List.jsx import React, { useEffect, useState } from "react" function List({ getItems }){ /* Initial state of the items */ const [items, setItems] = useState([]); /* This hook sets the value of items if getItems object changes */ useEffect(() => { console.log("Fetching items"); setItems(getItems()); }, [getItems]); /* Maps the items to a list */ return <div> {items.map(item => <div key={item}>{item}</div>)} </div>}export default List; Explanation: The list component gets the getItems function as a property. Every time the getItems function object changes useEffect will call setItems to set the list returned from the function object to stateful variable items and then we map those items into a list of div.Every time items are fetch using getItems in useEffect, we print “Fetching items” to see how often the items are fetched. Step to run the application: npm start Output: Explanation: The following will be the output when a user enters a number into the input field. It can be seen from the console log that when the app is rendered for the first time, items are fetched, and “fetching items” are printed. Now if we input some different numbers, we see that items are fetched once again. Now the weird thing is, when we press the button to change the theme, we see that the items are still being fetched even when the input field is not modified. The reason behind this behavior is that when we press the button, the app component is rerendered, and hence the function getItems() inside App is again created and we know that two objects are referentially different. Hence, inside the List component, useEffect hook calls the setItems and prints “Fetching items” as its dependency has changed. The solution to the above problem: Here we can use the useCallback function to memoise the getItems() function depending upon the input number. We don’t want to recreate the function unless the input changes, and hence, on pressing the button (changing the theme) items will not be fetched. App.jsx import React, { useCallback, useState} from "react"import List from "./List" function App(){ {/* Initial states */} const [input, setInput] = useState(1); const [light, setLight] = useState(true); {/* useCallback memoizes the getItems() which returns a list of number which is number+10 and number + 100 */} const getItems = useCallback(() => { return [input + 10, input + 100]; }, [input]); {/* style for changing the theme */} const theme = { backgroundColor: light ? "White": "grey", color: light ? "grey" : "white" } return <> {/* set the theme in the parent div */} <div style={theme}> <input type="number" value={input} {/* When we input a number it is stored in our stateful variable */} onChange={event => setInput(parseInt(event.target.value)) } /> {/* on click the button the theme is set to the opposite mode, light to dark and vice versa*/} <button onClick={() => setLight(prevLight => !prevLight)}>{light ? "dark mode":"light mode"} </button> <List getItems={getItems} /> </div> </>;} export default App; Now we use the useCallback hook to memoize the getitems function which takes the function and a dependency list. The dependency list in our case includes only the input. Output: Explanation: It can be seen from the output that the items are fetched only once when the app is rendered but not when we change the theme by pressing the button. It does not matter how many times we flip the theme, useEffect will not call the setItems until the input field has a new number. 2. useMemo: The useMemo hook returns a memoised value after taking a function and a list of dependencies. It returns the cached value if the dependencies do not change. Otherwise, it will recompute the value using the passed function. When to use useMemo: There are two cases where using useMemo can be helpful: When a component uses a value computed using a time-consuming function.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering.Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance.Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes.MyComponent.jsxMyComponent.jsxfunction MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);}In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change.Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);}Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed. When a component uses a value computed using a time-consuming function.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering.Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance. When a component uses a value computed using a time-consuming function. MyComponent.jsx function MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;} Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering. Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause. MyComponent.jsx function MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;} here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance. Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes.MyComponent.jsxMyComponent.jsxfunction MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);}In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change.Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);}Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed. Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes. MyComponent.jsx function MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);} In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change. Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body. MyComponent.jsx function MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);} Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed. 3. useEffect: In react, side effects of some state changes are not allowed in functional components. To perform a task once the rendering is complete and some state changes, we can use useEffect. This hook takes a function to be executed and a list of dependencies, changing which will cause the execution of the hook’s body. To understand its proper use. let’s see a simple example: Example: Consider a scenario where we have to fetch some data from some API once the components are mounted. In the example code, we simulate the server with our data object with values of different colours and fruits. We want to print the list of items depending on the button being pressed. Hence we have two state variables currentChoice and items which are modified by pressing the buttons. When a button is pressed it changes the currentChoice and the body of useEffect is called and current choice’s items are printed using a map. Now if we don’t use useEffect, every time a button is pressed data will be fetched from the server even if the choice does not change. In such a condition this hook helps us to not call the fetching logic unless our choice changes. App.jsx import React, { useEffect, useState} from "react" function App(){ /* Some data */ const data = { Colors: ["red", "green", "yellow"], Fruits: ["Apple", "mango", "Banana"] } /* Initial states */ const [currentChoice, setCurrentChoice] = useState("Colors"); const [items, setItems] = useState([]); /* Using useEffect to set the data of currentchoice to items and console log the fetching... */ useEffect(() => { setItems(data[currentChoice]); console.log("Data is fetched!"); }, [currentChoice]); return <> <button onClick={() => setCurrentChoice("Colors")}>Colors</button> <button onClick={() => setCurrentChoice("Fruits")}>Fruits</button> {items.map(item => {return <div key={item}>{item}</div>})} </>;} export default App; Output: Explanation: When the application loads for the first time, data is fetched from our fake server. This can be seen in the console in the image below. And when we press the Fruits button, appropriate data is again fetched from the server and we can see that “Data is fetched” is again printed in the console. But if we press the Fruits button again, we don’t have to get the data from the server again as our choice state does not change. Conclusion: Hence, a useCallback hook should be used when we want to memoize a callback, and to memoize the result of a function to avoid expensive computation we can use useMemo. useEffect is used to produce side effects to some state changes.One thing to remember is that one should not overuse hooks. Picked React-Hooks React-Questions ReactJS 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": "\n26 Jul, 2021" }, { "code": null, "e": 438, "s": 54, "text": "The useCallback, useMemo, and useEffect are a way to optimize the performance of React-based applications between rerendering of components. These functions provide some of the features of the class-based components like persistence of dedicated states through render calls as well as the lifecycle functions to control how the components look over various stages of their lifecycle." }, { "code": null, "e": 561, "s": 438, "text": "To answer when to use useCallBack, useMemo, and useEffect, we should know what exactly they do and how they are different." }, { "code": null, "e": 1555, "s": 561, "text": "useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed.useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change.useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function." }, { "code": null, "e": 1898, "s": 1555, "text": "useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed." }, { "code": null, "e": 2241, "s": 1898, "text": "useCallback: The useCallback is a react hook that returns a memoized callback when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed." }, { "code": null, "e": 2589, "s": 2241, "text": "useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change." }, { "code": null, "e": 2937, "s": 2589, "text": "useMemo: The useMemo is similar to useCallback hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function. It recalculated the value only when one of its dependencies change. It is useful to avoid expensive calculations on every render when the returned value is not going to change." }, { "code": null, "e": 3242, "s": 2937, "text": "useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function." }, { "code": null, "e": 3547, "s": 3242, "text": "useEffect: A hook that helps us to perform mutations, subscriptions, timers, logging, and other side effects after all the components has been rendered. The useEffect accepts a function that is imperative in nature and a list of dependencies. When its dependencies change it executes the passed function." }, { "code": null, "e": 3615, "s": 3547, "text": "Creating a react application for understanding all the three hooks:" }, { "code": null, "e": 3715, "s": 3615, "text": "Step 1: Create a React application using the following command:npx create-react-app usecallbackdemo" }, { "code": null, "e": 3779, "s": 3715, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 3816, "s": 3779, "text": "npx create-react-app usecallbackdemo" }, { "code": null, "e": 3934, "s": 3816, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd usecallbackdemo" }, { "code": null, "e": 4034, "s": 3934, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 4053, "s": 4034, "text": "cd usecallbackdemo" }, { "code": null, "e": 4105, "s": 4053, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 4127, "s": 4105, "text": "The project structure" }, { "code": null, "e": 4180, "s": 4127, "text": "Now let’s understand the working of all three hooks." }, { "code": null, "e": 4494, "s": 4180, "text": "1. usecallback: It depends on referential equality. In javascript, functions are first-class citizens, meaning that a function is a regular object. Hence, two function objects even when they share the same code are two different objects. Just remember that a function object is referentially equal only to itself." }, { "code": null, "e": 4580, "s": 4496, "text": "Let’s see this in the following code, doubleFactory creates and returns a function:" }, { "code": null, "e": 4591, "s": 4580, "text": "Javascript" }, { "code": "function doubleFactory(){ return (a) => 2*a;} const double1 = doubleFactory();const double2 = doubleFactory(); double1(8); // gives 16double2(8); // gives 16 double1 === double2; // falsedouble1 === double1; // true", "e": 4815, "s": 4591, "text": null }, { "code": null, "e": 5030, "s": 4815, "text": "doube1 and double2 doubles the value passed to them and are created by the same factory function. The two functions even when they share the same code, are not equal, here (double1 === double2) evaluates to false. " }, { "code": null, "e": 5131, "s": 5030, "text": "When to use useCallback: In React, a component usually has some callback function created within it." }, { "code": null, "e": 5142, "s": 5131, "text": "Javascript" }, { "code": "function MyComponent(){ // HandleChange is created on every render const handleChange = () => {...}; return <> ... </>;}", "e": 5296, "s": 5142, "text": null }, { "code": null, "e": 5904, "s": 5296, "text": "Here handleChange function objects are different on every rendering of MyComponent. And there are several cases when we may want the same function object between multiple renderings. For example when it’s a dependency for some other hooks (useEffect( ..., callbackfunc)) or when the function object itself has some internal state that we need to maintain. In such a case, useCallback hook comes handy. In simple words, useCallback( callBackFun, deps ) returns a memorized callback when the dependency values deps do not change between renderings. (memoized here refers to caching the object for future use)." }, { "code": null, "e": 6199, "s": 5904, "text": "Let’s see a use case using a project: The application consists of an input field, a button, and a list. The list is a component that consists of two numbers, the first is input plus 10 and the second is input + 100. The button changes the components from dark mode to light mode and vice versa." }, { "code": null, "e": 6402, "s": 6199, "text": "There’s going to be two components App and List, App is our main component where we add input field, button, and List. The list component is used to print the list of items depending on the input field." }, { "code": null, "e": 6410, "s": 6402, "text": "App.jsx" }, { "code": "import React, { useState} from \"react\"import List from \"./List\" function App(){ {/* Initial states */} const [input, setInput] = useState(1); const [light, setLight] = useState(true); {/* getItems() returns a list of number which is number+10 and number + 100 */} const getItems = () => { return [input + 10, input + 100]; } {/* Style for changing the theme */} const theme = { backgroundColor: light ? \"White\": \"grey\", color: light ? \"grey\" : \"white\" } return <> {/* set the theme in the parent div */} <div style={theme}> <input type=\"number\" value={input} {/* When we input a number it is stored in our stateful variable */} onChange={event => setInput(parseInt(event.target.value))} /> {/* on click the button the theme is set to the opposite mode, light to dark and vice versa*/} <button onClick={() => setLight(prevLight => !prevLight)}> {light ? \"dark mode\":\"light mode\"} </button> <List getItems={getItems} /> </div> </>;} export default App;", "e": 7579, "s": 6410, "text": null }, { "code": null, "e": 7590, "s": 7581, "text": "List.jsx" }, { "code": "import React, { useEffect, useState } from \"react\" function List({ getItems }){ /* Initial state of the items */ const [items, setItems] = useState([]); /* This hook sets the value of items if getItems object changes */ useEffect(() => { console.log(\"Fetching items\"); setItems(getItems()); }, [getItems]); /* Maps the items to a list */ return <div> {items.map(item => <div key={item}>{item}</div>)} </div>}export default List;", "e": 8078, "s": 7590, "text": null }, { "code": null, "e": 8475, "s": 8078, "text": "Explanation: The list component gets the getItems function as a property. Every time the getItems function object changes useEffect will call setItems to set the list returned from the function object to stateful variable items and then we map those items into a list of div.Every time items are fetch using getItems in useEffect, we print “Fetching items” to see how often the items are fetched." }, { "code": null, "e": 8504, "s": 8475, "text": "Step to run the application:" }, { "code": null, "e": 8514, "s": 8504, "text": "npm start" }, { "code": null, "e": 8522, "s": 8514, "text": "Output:" }, { "code": null, "e": 8839, "s": 8522, "text": "Explanation: The following will be the output when a user enters a number into the input field. It can be seen from the console log that when the app is rendered for the first time, items are fetched, and “fetching items” are printed. Now if we input some different numbers, we see that items are fetched once again." }, { "code": null, "e": 8998, "s": 8839, "text": "Now the weird thing is, when we press the button to change the theme, we see that the items are still being fetched even when the input field is not modified." }, { "code": null, "e": 9344, "s": 8998, "text": "The reason behind this behavior is that when we press the button, the app component is rerendered, and hence the function getItems() inside App is again created and we know that two objects are referentially different. Hence, inside the List component, useEffect hook calls the setItems and prints “Fetching items” as its dependency has changed." }, { "code": null, "e": 9637, "s": 9346, "text": "The solution to the above problem: Here we can use the useCallback function to memoise the getItems() function depending upon the input number. We don’t want to recreate the function unless the input changes, and hence, on pressing the button (changing the theme) items will not be fetched." }, { "code": null, "e": 9645, "s": 9637, "text": "App.jsx" }, { "code": "import React, { useCallback, useState} from \"react\"import List from \"./List\" function App(){ {/* Initial states */} const [input, setInput] = useState(1); const [light, setLight] = useState(true); {/* useCallback memoizes the getItems() which returns a list of number which is number+10 and number + 100 */} const getItems = useCallback(() => { return [input + 10, input + 100]; }, [input]); {/* style for changing the theme */} const theme = { backgroundColor: light ? \"White\": \"grey\", color: light ? \"grey\" : \"white\" } return <> {/* set the theme in the parent div */} <div style={theme}> <input type=\"number\" value={input} {/* When we input a number it is stored in our stateful variable */} onChange={event => setInput(parseInt(event.target.value)) } /> {/* on click the button the theme is set to the opposite mode, light to dark and vice versa*/} <button onClick={() => setLight(prevLight => !prevLight)}>{light ? \"dark mode\":\"light mode\"} </button> <List getItems={getItems} /> </div> </>;} export default App;", "e": 10930, "s": 9645, "text": null }, { "code": null, "e": 11100, "s": 10930, "text": "Now we use the useCallback hook to memoize the getitems function which takes the function and a dependency list. The dependency list in our case includes only the input." }, { "code": null, "e": 11108, "s": 11100, "text": "Output:" }, { "code": null, "e": 11401, "s": 11108, "text": "Explanation: It can be seen from the output that the items are fetched only once when the app is rendered but not when we change the theme by pressing the button. It does not matter how many times we flip the theme, useEffect will not call the setItems until the input field has a new number." }, { "code": null, "e": 11636, "s": 11401, "text": "2. useMemo: The useMemo hook returns a memoised value after taking a function and a list of dependencies. It returns the cached value if the dependencies do not change. Otherwise, it will recompute the value using the passed function." }, { "code": null, "e": 11657, "s": 11636, "text": "When to use useMemo:" }, { "code": null, "e": 11713, "s": 11657, "text": "There are two cases where using useMemo can be helpful:" }, { "code": null, "e": 14305, "s": 11713, "text": "When a component uses a value computed using a time-consuming function.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering.Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance.Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes.MyComponent.jsxMyComponent.jsxfunction MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);}In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change.Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);}Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed." }, { "code": null, "e": 15519, "s": 14305, "text": "When a component uses a value computed using a time-consuming function.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering.Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance." }, { "code": null, "e": 15591, "s": 15519, "text": "When a component uses a value computed using a time-consuming function." }, { "code": null, "e": 15607, "s": 15591, "text": "MyComponent.jsx" }, { "code": "function MyComponent(){ const [data, setData] = useState(0); const number = verySlowFunction(data); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}", "e": 15825, "s": 15607, "text": null }, { "code": null, "e": 15990, "s": 15825, "text": "Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering." }, { "code": null, "e": 16127, "s": 15990, "text": "Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause." }, { "code": null, "e": 16143, "s": 16127, "text": "MyComponent.jsx" }, { "code": "function MyComponent(){ const [data, setData] = useState(0); const number = useMemo(() => { return verySlowFunction(data)}, [data]); return <div>{number}</div>;} function verySlowFunction(input){ ...heavy work done here return value;}", "e": 16407, "s": 16143, "text": null }, { "code": null, "e": 16710, "s": 16407, "text": "here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance." }, { "code": null, "e": 18089, "s": 16710, "text": "Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes.MyComponent.jsxMyComponent.jsxfunction MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);}In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change.Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body.MyComponent.jsxMyComponent.jsxfunction MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);}Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed." }, { "code": null, "e": 18272, "s": 18089, "text": "Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes." }, { "code": null, "e": 18288, "s": 18272, "text": "MyComponent.jsx" }, { "code": "function MyComponent() { const [number, setNumber] = useState(0); const data = { key: value }; useEffect(() => { console.log('Hello world'); }, [data]);}", "e": 18481, "s": 18288, "text": null }, { "code": null, "e": 18883, "s": 18481, "text": "In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change." }, { "code": null, "e": 19057, "s": 18883, "text": "Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body." }, { "code": null, "e": 19073, "s": 19057, "text": "MyComponent.jsx" }, { "code": "function MyComponent(){ const [number, setNumber] = useState(0); const data = useMemo( () => { return { key: value }}, number); useEffect(() => { console.log('Hello world'); }, [data]);}", "e": 19306, "s": 19073, "text": null }, { "code": null, "e": 19445, "s": 19306, "text": "Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed." }, { "code": null, "e": 19771, "s": 19445, "text": "3. useEffect: In react, side effects of some state changes are not allowed in functional components. To perform a task once the rendering is complete and some state changes, we can use useEffect. This hook takes a function to be executed and a list of dependencies, changing which will cause the execution of the hook’s body." }, { "code": null, "e": 19829, "s": 19771, "text": "To understand its proper use. let’s see a simple example:" }, { "code": null, "e": 20598, "s": 19829, "text": "Example: Consider a scenario where we have to fetch some data from some API once the components are mounted. In the example code, we simulate the server with our data object with values of different colours and fruits. We want to print the list of items depending on the button being pressed. Hence we have two state variables currentChoice and items which are modified by pressing the buttons. When a button is pressed it changes the currentChoice and the body of useEffect is called and current choice’s items are printed using a map. Now if we don’t use useEffect, every time a button is pressed data will be fetched from the server even if the choice does not change. In such a condition this hook helps us to not call the fetching logic unless our choice changes." }, { "code": null, "e": 20606, "s": 20598, "text": "App.jsx" }, { "code": "import React, { useEffect, useState} from \"react\" function App(){ /* Some data */ const data = { Colors: [\"red\", \"green\", \"yellow\"], Fruits: [\"Apple\", \"mango\", \"Banana\"] } /* Initial states */ const [currentChoice, setCurrentChoice] = useState(\"Colors\"); const [items, setItems] = useState([]); /* Using useEffect to set the data of currentchoice to items and console log the fetching... */ useEffect(() => { setItems(data[currentChoice]); console.log(\"Data is fetched!\"); }, [currentChoice]); return <> <button onClick={() => setCurrentChoice(\"Colors\")}>Colors</button> <button onClick={() => setCurrentChoice(\"Fruits\")}>Fruits</button> {items.map(item => {return <div key={item}>{item}</div>})} </>;} export default App;", "e": 21429, "s": 20606, "text": null }, { "code": null, "e": 21437, "s": 21429, "text": "Output:" }, { "code": null, "e": 21876, "s": 21437, "text": "Explanation: When the application loads for the first time, data is fetched from our fake server. This can be seen in the console in the image below. And when we press the Fruits button, appropriate data is again fetched from the server and we can see that “Data is fetched” is again printed in the console. But if we press the Fruits button again, we don’t have to get the data from the server again as our choice state does not change." }, { "code": null, "e": 21888, "s": 21876, "text": "Conclusion:" }, { "code": null, "e": 22181, "s": 21888, "text": "Hence, a useCallback hook should be used when we want to memoize a callback, and to memoize the result of a function to avoid expensive computation we can use useMemo. useEffect is used to produce side effects to some state changes.One thing to remember is that one should not overuse hooks. " }, { "code": null, "e": 22188, "s": 22181, "text": "Picked" }, { "code": null, "e": 22200, "s": 22188, "text": "React-Hooks" }, { "code": null, "e": 22216, "s": 22200, "text": "React-Questions" }, { "code": null, "e": 22224, "s": 22216, "text": "ReactJS" }, { "code": null, "e": 22241, "s": 22224, "text": "Web Technologies" } ]
Google STEP Intern Interview Experience
03 Dec, 2020 The shortlisting was done through our university based on our resume and academic performance. I was shortlisted and had two interviews of 45 minutes, each with a break of fifteen minutes in between. Both of them were technical rounds involving hands-on coding in a shared google doc while I was on a video call through Hangouts with the interviewer from Google. Round 1: Question: A boolean expression is given in the form of a string. It contains one variable x; logical operators – ‘and’, ‘or’ and relational operators – ‘>’, ‘<‘ (there is no >= or <=). Find if the expression always evaluates to False. If yes, output False, otherwise if there exists at least one x such that the given expression can be true, output true. Example: 1. “x<0 and x>5” Output – False Explanation – This can never be true as there is no ‘x’ such as x<0 and x>5. So, the given boolean expression always evaluates to false. 2. “x>0 or x<-1” Output – True Explanation – We have at least one ‘x’ for which given boolean expression evaluates to true. For example, put x=2 in the given expression, and it evaluates to true. Hint: Whenever there is only ‘or’ in the boolean expression, the result is always true. (Eg: x>0 or x<0 – There exists some x such that this is true and whatever be the latter part of the expression, it evaluates to true as only ‘or’ is present. If there is no ‘or’ present (only ‘and’ is there), then we check for the expressions – if you find at least two contradicting expressions as in example 1 (that is their solution sets are disjoint), then the output is False (as we have only ‘and’ logical operation which evaluates to False unless all the expressions are True), otherwise it is True. I have no idea how to approach the problem when both ‘and, ‘ ‘or’ are present in the expression, and I could not find such a problem anywhere on the internet. I request someone who read this article to contribute the code to this problem kindly. (preferably in C++) //Write Java code here public class BooleanExp { public static void main(String[] args) { String exp1 = "x<0 and x<-5 and x>100"; String exp2 = "x<0 and x<5"; String exp3 = "x>5 and x<0"; String exp4 = "x<0 or x>5"; String exp5 = "x>5 and x<0 and x<100"; String exp6 = "x<-100 and x>100"; GetDomain(exp1); GetDomain(exp2); GetDomain(exp3); GetDomain(exp4); GetDomain(exp5); GetDomain(exp6); } public static void GetDomain(String exp) { if (exp.contains("or")) { System.out.println("true"); return; } String subExp[] = exp.split(" "); int domain[] = new int[10]; String strDomain = ""; Boolean flag = true; int value; for (int i = 0; i < subExp.length; i++) { if (!subExp[i].equals("and")) { if (subExp[i].charAt(1) == '<') { if (subExp[i].charAt(0) == 'x') { if (strDomain.isEmpty()) strDomain = "<" + subExp[i].substring(2); else if (strDomain.charAt(0) == '>' && Integer.parseInt(subExp[i].substring(2)) < Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } else { if (strDomain.isEmpty()) strDomain = ">" + subExp[i].substring(2); else if (strDomain.charAt(0) == '<' && Integer.parseInt(subExp[i].substring(2)) > Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } } else if (subExp[i].charAt(1) == '>') { if (subExp[i].charAt(2) == 'x') { if (strDomain.isEmpty()) strDomain = "<" + subExp[i].substring(2); else if (strDomain.charAt(0) == '>' && Integer.parseInt(subExp[i].substring(2)) < Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } else { if (strDomain.isEmpty()) strDomain = ">" + subExp[i].substring(2); else if (strDomain.charAt(0) == '<' && Integer.parseInt(subExp[i].substring(2)) > Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } } } } System.out.println(flag); } } // This code is contributed by Arsalaan Javed Output:falsetruefalsetruefalsefalse Round 2: Question: Given a string, find the minimum number of cuts to split the string so that all the resulting substrings are palindromes. Example: “google” Output: 2 Explanation: Minimum number of cuts to partition “google” into palindromes = 2 that is – goog|l|e – where ‘|’ refers to a cut, the three resulting palindromes are “goog”, “l”, “e”. Therefore, the minimum number of cuts required = 2. Hint: Refer to this article. Google Marketing Internship Interview Experiences Google Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Dec, 2020" }, { "code": null, "e": 415, "s": 52, "text": "The shortlisting was done through our university based on our resume and academic performance. I was shortlisted and had two interviews of 45 minutes, each with a break of fifteen minutes in between. Both of them were technical rounds involving hands-on coding in a shared google doc while I was on a video call through Hangouts with the interviewer from Google." }, { "code": null, "e": 425, "s": 415, "text": "Round 1: " }, { "code": null, "e": 780, "s": 425, "text": "Question: A boolean expression is given in the form of a string. It contains one variable x; logical operators – ‘and’, ‘or’ and relational operators – ‘>’, ‘<‘ (there is no >= or <=). Find if the expression always evaluates to False. If yes, output False, otherwise if there exists at least one x such that the given expression can be true, output true." }, { "code": null, "e": 789, "s": 780, "text": "Example:" }, { "code": null, "e": 806, "s": 789, "text": "1. “x<0 and x>5”" }, { "code": null, "e": 821, "s": 806, "text": "Output – False" }, { "code": null, "e": 958, "s": 821, "text": "Explanation – This can never be true as there is no ‘x’ such as x<0 and x>5. So, the given boolean expression always evaluates to false." }, { "code": null, "e": 975, "s": 958, "text": "2. “x>0 or x<-1”" }, { "code": null, "e": 989, "s": 975, "text": "Output – True" }, { "code": null, "e": 1154, "s": 989, "text": "Explanation – We have at least one ‘x’ for which given boolean expression evaluates to true. For example, put x=2 in the given expression, and it evaluates to true." }, { "code": null, "e": 1749, "s": 1154, "text": "Hint: Whenever there is only ‘or’ in the boolean expression, the result is always true. (Eg: x>0 or x<0 – There exists some x such that this is true and whatever be the latter part of the expression, it evaluates to true as only ‘or’ is present. If there is no ‘or’ present (only ‘and’ is there), then we check for the expressions – if you find at least two contradicting expressions as in example 1 (that is their solution sets are disjoint), then the output is False (as we have only ‘and’ logical operation which evaluates to False unless all the expressions are True), otherwise it is True." }, { "code": null, "e": 1908, "s": 1749, "text": "I have no idea how to approach the problem when both ‘and, ‘ ‘or’ are present in the expression, and I could not find such a problem anywhere on the internet." }, { "code": null, "e": 2015, "s": 1908, "text": "I request someone who read this article to contribute the code to this problem kindly. (preferably in C++)" }, { "code": "//Write Java code here public class BooleanExp { public static void main(String[] args) { String exp1 = \"x<0 and x<-5 and x>100\"; String exp2 = \"x<0 and x<5\"; String exp3 = \"x>5 and x<0\"; String exp4 = \"x<0 or x>5\"; String exp5 = \"x>5 and x<0 and x<100\"; String exp6 = \"x<-100 and x>100\"; GetDomain(exp1); GetDomain(exp2); GetDomain(exp3); GetDomain(exp4); GetDomain(exp5); GetDomain(exp6); } public static void GetDomain(String exp) { if (exp.contains(\"or\")) { System.out.println(\"true\"); return; } String subExp[] = exp.split(\" \"); int domain[] = new int[10]; String strDomain = \"\"; Boolean flag = true; int value; for (int i = 0; i < subExp.length; i++) { if (!subExp[i].equals(\"and\")) { if (subExp[i].charAt(1) == '<') { if (subExp[i].charAt(0) == 'x') { if (strDomain.isEmpty()) strDomain = \"<\" + subExp[i].substring(2); else if (strDomain.charAt(0) == '>' && Integer.parseInt(subExp[i].substring(2)) < Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } else { if (strDomain.isEmpty()) strDomain = \">\" + subExp[i].substring(2); else if (strDomain.charAt(0) == '<' && Integer.parseInt(subExp[i].substring(2)) > Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } } else if (subExp[i].charAt(1) == '>') { if (subExp[i].charAt(2) == 'x') { if (strDomain.isEmpty()) strDomain = \"<\" + subExp[i].substring(2); else if (strDomain.charAt(0) == '>' && Integer.parseInt(subExp[i].substring(2)) < Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } else { if (strDomain.isEmpty()) strDomain = \">\" + subExp[i].substring(2); else if (strDomain.charAt(0) == '<' && Integer.parseInt(subExp[i].substring(2)) > Integer .parseInt(strDomain.substring(1))) { flag = false; break; } } } } } System.out.println(flag); } } // This code is contributed by Arsalaan Javed", "e": 4931, "s": 2015, "text": null }, { "code": null, "e": 4967, "s": 4931, "text": "Output:falsetruefalsetruefalsefalse" }, { "code": null, "e": 4977, "s": 4967, "text": "Round 2: " }, { "code": null, "e": 5109, "s": 4977, "text": "Question: Given a string, find the minimum number of cuts to split the string so that all the resulting substrings are palindromes." }, { "code": null, "e": 5127, "s": 5109, "text": "Example: “google”" }, { "code": null, "e": 5137, "s": 5127, "text": "Output: 2" }, { "code": null, "e": 5226, "s": 5137, "text": "Explanation: Minimum number of cuts to partition “google” into palindromes = 2 that is –" }, { "code": null, "e": 5370, "s": 5226, "text": "goog|l|e – where ‘|’ refers to a cut, the three resulting palindromes are “goog”, “l”, “e”. Therefore, the minimum number of cuts required = 2." }, { "code": null, "e": 5399, "s": 5370, "text": "Hint: Refer to this article." }, { "code": null, "e": 5406, "s": 5399, "text": "Google" }, { "code": null, "e": 5416, "s": 5406, "text": "Marketing" }, { "code": null, "e": 5427, "s": 5416, "text": "Internship" }, { "code": null, "e": 5449, "s": 5427, "text": "Interview Experiences" }, { "code": null, "e": 5456, "s": 5449, "text": "Google" } ]
Deep, Shallow and Lazy Copy with Java Examples
13 Jun, 2022 In object-oriented programming, object copying is creating a copy of an existing object, the resulting object is called an object copy or simply copy of the original object.There are several ways to copy an object, most commonly by a copy constructor or cloning.We can define Cloning as “create a copy of object”. Shallow, deep and lazy copy is related to cloning process. These are actually three ways for creating copy object.Shallow Copy Whenever we use default implementation of clone method we get shallow copy of object means it creates new instance and copies all the field of object to that new instance and returns it as object type, we need to explicitly cast it back to our original object. This is shallow copy of the object. clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java. Java //code illustrating shallow copypublic class Ex { private int[] data; // makes a shallow copy of values public Ex(int[] values) { data = values; } public void showData() { System.out.println( Arrays.toString(data) ); }} The above code shows shallow copying. data simply refers to the same array as vals. This can lead to unpleasant side effects if the elements of values are changed via some other reference. Java public class UsesEx{ public static void main(String[] args) { int[] vals = {3, 7, 9}; Ex e = new Ex(vals); e.showData(); // prints out [3, 7, 9] vals[0] = 13; e.showData(); // prints out [13, 7, 9] // Very confusing, because we didn't // intentionally change anything about // the object e refers to. }} Output 1 : [3, 7, 9] Output 2 : [13, 7, 9] Deep Copy Whenever we need own copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need. So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class. A deep copy means actually creating a new array and copying over the values. Java // Code explaining deep copypublic class Ex { private int[] data; // altered to make a deep copy of values public Ex(int[] values) { data = new int[values.length]; for (int i = 0; i < data.length; i++) { data[i] = values[i]; } } public void showData() { System.out.println(Arrays.toString(data)); }} Java public class UsesEx{ public static void main(String[] args) { int[] vals = {3, 7, 9}; Ex e = new Ex(vals); e.showData(); // prints out [3, 7, 9] vals[0] = 13; e.showData(); // prints out [3, 7, 9] // changes in array values will not be // shown in data values. }} Output 1 : [3, 7, 9] Output 2 : [3, 7, 9] Changes to the array vals will not result in changes to the array data.when to use what There is no hard and fast rule defined for selecting between shallow copy and deep copy but normally we should keep in mind that if an object has only primitive fields, then obviously we should go for shallow copy, but if the object has references to other objects, then based on the requirement, shallow copy or deep copy should be done. If the references are not updated then there is no point to initiate a deep copy.Lazy Copy A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach – at the initial state, shallow copy approach is used. A counter is also used to keep a track on how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.Summary In shallow copy, only fields of primitive data type are copied while the objects references are not copied. Deep copy involves the copy of primitive data type as well as object references. There is no hard and fast rule as to when to do shallow copy and when to do a deep copy. Lazy copy is a combination of both of these approaches gabaa406 pratyaksh16 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 497, "s": 54, "text": "In object-oriented programming, object copying is creating a copy of an existing object, the resulting object is called an object copy or simply copy of the original object.There are several ways to copy an object, most commonly by a copy constructor or cloning.We can define Cloning as “create a copy of object”. Shallow, deep and lazy copy is related to cloning process. These are actually three ways for creating copy object.Shallow Copy " }, { "code": null, "e": 794, "s": 497, "text": "Whenever we use default implementation of clone method we get shallow copy of object means it creates new instance and copies all the field of object to that new instance and returns it as object type, we need to explicitly cast it back to our original object. This is shallow copy of the object." }, { "code": null, "e": 1135, "s": 794, "text": "clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves." }, { "code": null, "e": 1324, "s": 1135, "text": "That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java." }, { "code": null, "e": 1331, "s": 1326, "text": "Java" }, { "code": "//code illustrating shallow copypublic class Ex { private int[] data; // makes a shallow copy of values public Ex(int[] values) { data = values; } public void showData() { System.out.println( Arrays.toString(data) ); }}", "e": 1589, "s": 1331, "text": null }, { "code": null, "e": 1674, "s": 1589, "text": "The above code shows shallow copying. data simply refers to the same array as vals. " }, { "code": null, "e": 1780, "s": 1674, "text": "This can lead to unpleasant side effects if the elements of values are changed via some other reference. " }, { "code": null, "e": 1785, "s": 1780, "text": "Java" }, { "code": "public class UsesEx{ public static void main(String[] args) { int[] vals = {3, 7, 9}; Ex e = new Ex(vals); e.showData(); // prints out [3, 7, 9] vals[0] = 13; e.showData(); // prints out [13, 7, 9] // Very confusing, because we didn't // intentionally change anything about // the object e refers to. }}", "e": 2156, "s": 1785, "text": null }, { "code": null, "e": 2199, "s": 2156, "text": "Output 1 : [3, 7, 9]\nOutput 2 : [13, 7, 9]" }, { "code": null, "e": 2211, "s": 2199, "text": "Deep Copy " }, { "code": null, "e": 2381, "s": 2211, "text": "Whenever we need own copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need." }, { "code": null, "e": 2529, "s": 2381, "text": "So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class." }, { "code": null, "e": 2607, "s": 2529, "text": "A deep copy means actually creating a new array and copying over the values. " }, { "code": null, "e": 2612, "s": 2607, "text": "Java" }, { "code": "// Code explaining deep copypublic class Ex { private int[] data; // altered to make a deep copy of values public Ex(int[] values) { data = new int[values.length]; for (int i = 0; i < data.length; i++) { data[i] = values[i]; } } public void showData() { System.out.println(Arrays.toString(data)); }}", "e": 2979, "s": 2612, "text": null }, { "code": null, "e": 2984, "s": 2979, "text": "Java" }, { "code": "public class UsesEx{ public static void main(String[] args) { int[] vals = {3, 7, 9}; Ex e = new Ex(vals); e.showData(); // prints out [3, 7, 9] vals[0] = 13; e.showData(); // prints out [3, 7, 9] // changes in array values will not be // shown in data values. }}", "e": 3307, "s": 2984, "text": null }, { "code": null, "e": 3349, "s": 3307, "text": "Output 1 : [3, 7, 9]\nOutput 2 : [3, 7, 9]" }, { "code": null, "e": 4626, "s": 3349, "text": "Changes to the array vals will not result in changes to the array data.when to use what There is no hard and fast rule defined for selecting between shallow copy and deep copy but normally we should keep in mind that if an object has only primitive fields, then obviously we should go for shallow copy, but if the object has references to other objects, then based on the requirement, shallow copy or deep copy should be done. If the references are not updated then there is no point to initiate a deep copy.Lazy Copy A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach – at the initial state, shallow copy approach is used. A counter is also used to keep a track on how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.Summary In shallow copy, only fields of primitive data type are copied while the objects references are not copied. Deep copy involves the copy of primitive data type as well as object references. There is no hard and fast rule as to when to do shallow copy and when to do a deep copy. Lazy copy is a combination of both of these approaches" }, { "code": null, "e": 4635, "s": 4626, "text": "gabaa406" }, { "code": null, "e": 4647, "s": 4635, "text": "pratyaksh16" }, { "code": null, "e": 4652, "s": 4647, "text": "Java" }, { "code": null, "e": 4657, "s": 4652, "text": "Java" } ]
Python Program for Check if count of divisors is even or odd
30 Nov, 2018 Given a number “n”, find its total number of divisors are even or odd. Examples : Input : n = 10 Output : Even Input: n = 100 Output: Odd Input: n = 125 Output: Even A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd. Time complexity for such a solution would be O(sqrt(n)) # Naive Solution to # find if count of # divisors is even# or oddimport math # Function to count # the divisorsdef countDivisors(n) : # Initialize count # of divisors count = 0 # Note that this loop # runs till square # root for i in range(1, (int)(math.sqrt(n)) + 2) : if (n % i == 0) : # If divisors are # equal,increment # count by one # Otherwise increment # count by 2 if( n // i == i) : count = count + 1 else : count = count + 2 if (count % 2 == 0) : print("Even") else : print("Odd") # Driver program to test above function */print("The count of divisor: ")countDivisors(10) #This code is contributed by Nikita Tiwari.*/ Output : The count of divisor: Even Efficient Solution:We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it\’s a perfect square, then the number of divisors would be odd, else it\’d be even. # Python program for# Efficient Solution to find# find if count of divisors# is even or odd # Python program for# Efficient Solution to find# find if count of divisors# is even or odd def NumOfDivisor(n): if n < 1: return root_n = n**0.5 # If n is a perfect square, # then it has odd divisors if root_n**2 == n: print("Odd") else: print("Even") # Driver code if __name__ == '__main__': print("The count of divisor"+ "of 10 is: ") NumOfDivisor(10) # This code is contributed by Yt R Output : The count of divisorof 10 is: Even Please refer complete article on Check if count of divisors is even or odd for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2018" }, { "code": null, "e": 99, "s": 28, "text": "Given a number “n”, find its total number of divisors are even or odd." }, { "code": null, "e": 110, "s": 99, "text": "Examples :" }, { "code": null, "e": 205, "s": 110, "text": "Input : n = 10 \nOutput : Even\n\nInput: n = 100\nOutput: Odd\n\nInput: n = 125\nOutput: Even" }, { "code": null, "e": 317, "s": 205, "text": "A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd." }, { "code": null, "e": 373, "s": 317, "text": "Time complexity for such a solution would be O(sqrt(n))" }, { "code": "# Naive Solution to # find if count of # divisors is even# or oddimport math # Function to count # the divisorsdef countDivisors(n) : # Initialize count # of divisors count = 0 # Note that this loop # runs till square # root for i in range(1, (int)(math.sqrt(n)) + 2) : if (n % i == 0) : # If divisors are # equal,increment # count by one # Otherwise increment # count by 2 if( n // i == i) : count = count + 1 else : count = count + 2 if (count % 2 == 0) : print(\"Even\") else : print(\"Odd\") # Driver program to test above function */print(\"The count of divisor: \")countDivisors(10) #This code is contributed by Nikita Tiwari.*/", "e": 1189, "s": 373, "text": null }, { "code": null, "e": 1198, "s": 1189, "text": "Output :" }, { "code": null, "e": 1226, "s": 1198, "text": "The count of divisor: Even " }, { "code": null, "e": 1505, "s": 1226, "text": "Efficient Solution:We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it\\’s a perfect square, then the number of divisors would be odd, else it\\’d be even." }, { "code": "# Python program for# Efficient Solution to find# find if count of divisors# is even or odd # Python program for# Efficient Solution to find# find if count of divisors# is even or odd def NumOfDivisor(n): if n < 1: return root_n = n**0.5 # If n is a perfect square, # then it has odd divisors if root_n**2 == n: print(\"Odd\") else: print(\"Even\") # Driver code if __name__ == '__main__': print(\"The count of divisor\"+ \"of 10 is: \") NumOfDivisor(10) # This code is contributed by Yt R ", "e": 2069, "s": 1505, "text": null }, { "code": null, "e": 2078, "s": 2069, "text": "Output :" }, { "code": null, "e": 2115, "s": 2078, "text": "The count of divisorof 10 is: \nEven " }, { "code": null, "e": 2208, "s": 2115, "text": "Please refer complete article on Check if count of divisors is even or odd for more details!" }, { "code": null, "e": 2224, "s": 2208, "text": "Python Programs" } ]
Pre-increment (or pre-decrement) With Reference to L-value in C++
22 Jun, 2022 Prerequisite: Pre-increment and post-increment in C/C++ In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement) can not be used as l-value. For example, following program prints a = 20 (++a is used as l-value) l-value is simply nothing but the memory location, which has an address. CPP // CPP program to illustrate// Pre-increment (or pre-decrement)#include <cstdio> int main(){ int a = 10; ++a = 20; // works printf("a = %d", a); printf("\n"); --a = 10; printf("a = %d", a); return 0;} Output: a = 20 a = 10 Time Complexity: O(1) The above program works whereas the following program fails in compilation with error “non-lvalue in assignment” (a++ is used as l-value) CPP // CPP program to illustrate// Post-increment (or post-decrement)#include <cstdio> int main(){ int a = 10; a++ = 20; // error printf("a = %d", a); return 0;} Error: prog.cpp: In function 'int main()': prog.cpp:6:5: error: lvalue required as left operand of assignment a++ = 20; // error ^ It is because ++a returns an lvalue, which is basically a reference to the variable to which we can further assign — just like an ordinary variable. It could also be assigned to a reference as follows: int &ref = ++a; // valid int &ref = a++; // invalid Whereas if you recall how a++ works, it doesn’t immediately increment the value it holds. For clarity, you can think of it as getting incremented in the next statement. So what basically happens is that, a++ returns an rvalue, which is basically just a value like the value of an expression that is not stored. You can think of a++ = 20; as follows after being processed: int a = 10; // On compilation, a++ is replaced by the value of a which is an rvalue: 10 = 20; // Invalid // Value of a is incremented a = a + 1; That should help to understand why a++ = 20; won’t work. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SangeethSudheer sackshamsharmaintern kanheremahesh1729 C-Operators C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 110, "s": 54, "text": "Prerequisite: Pre-increment and post-increment in C/C++" }, { "code": null, "e": 314, "s": 110, "text": "In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement) can not be used as l-value. For example, following program prints a = 20 (++a is used as l-value) " }, { "code": null, "e": 387, "s": 314, "text": "l-value is simply nothing but the memory location, which has an address." }, { "code": null, "e": 391, "s": 387, "text": "CPP" }, { "code": "// CPP program to illustrate// Pre-increment (or pre-decrement)#include <cstdio> int main(){ int a = 10; ++a = 20; // works printf(\"a = %d\", a); printf(\"\\n\"); --a = 10; printf(\"a = %d\", a); return 0;}", "e": 614, "s": 391, "text": null }, { "code": null, "e": 622, "s": 614, "text": "Output:" }, { "code": null, "e": 636, "s": 622, "text": "a = 20\na = 10" }, { "code": null, "e": 658, "s": 636, "text": "Time Complexity: O(1)" }, { "code": null, "e": 797, "s": 658, "text": "The above program works whereas the following program fails in compilation with error “non-lvalue in assignment” (a++ is used as l-value) " }, { "code": null, "e": 801, "s": 797, "text": "CPP" }, { "code": "// CPP program to illustrate// Post-increment (or post-decrement)#include <cstdio> int main(){ int a = 10; a++ = 20; // error printf(\"a = %d\", a); return 0;}", "e": 971, "s": 801, "text": null }, { "code": null, "e": 978, "s": 971, "text": "Error:" }, { "code": null, "e": 1109, "s": 978, "text": "prog.cpp: In function 'int main()':\nprog.cpp:6:5: error: lvalue required as left operand of assignment\n a++ = 20; // error \n ^" }, { "code": null, "e": 1311, "s": 1109, "text": "It is because ++a returns an lvalue, which is basically a reference to the variable to which we can further assign — just like an ordinary variable. It could also be assigned to a reference as follows:" }, { "code": null, "e": 1363, "s": 1311, "text": "int &ref = ++a; // valid\nint &ref = a++; // invalid" }, { "code": null, "e": 1735, "s": 1363, "text": "Whereas if you recall how a++ works, it doesn’t immediately increment the value it holds. For clarity, you can think of it as getting incremented in the next statement. So what basically happens is that, a++ returns an rvalue, which is basically just a value like the value of an expression that is not stored. You can think of a++ = 20; as follows after being processed:" }, { "code": null, "e": 1882, "s": 1735, "text": "int a = 10;\n\n// On compilation, a++ is replaced by the value of a which is an rvalue:\n10 = 20; // Invalid\n\n// Value of a is incremented\na = a + 1;" }, { "code": null, "e": 2064, "s": 1882, "text": "That should help to understand why a++ = 20; won’t work. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2080, "s": 2064, "text": "SangeethSudheer" }, { "code": null, "e": 2101, "s": 2080, "text": "sackshamsharmaintern" }, { "code": null, "e": 2119, "s": 2101, "text": "kanheremahesh1729" }, { "code": null, "e": 2131, "s": 2119, "text": "C-Operators" }, { "code": null, "e": 2142, "s": 2131, "text": "C Language" }, { "code": null, "e": 2146, "s": 2142, "text": "C++" }, { "code": null, "e": 2150, "s": 2146, "text": "CPP" } ]
more command in Linux with Examples
14 Oct, 2019 more command is used to view the text files in the command prompt, displaying one screen at a time in case the file is large (For example log files). The more command also allows the user do scroll up and down through the page. The syntax along with options and command is as follows. Another application of more is to use it with some other command after a pipe. When the output is large, we can use more command to see output one by one. Syntax: more [-options] [-num] [+/pattern] [+linenum] [file_name] [-options]: any option that you want to use in order to change the way the file is displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, -s, -u) [-num]: type the number of lines that you want to display per screen. [+/pattern]: replace the pattern with any string that you want to find in the text file. [+linenum]: use the line number from where you want to start displaying the text content. [file_name]: name of the file containing the text that you want to display on the screen. While viewing the text file use these controls: Enter key: to scroll down line by line.Space bar: To go to the next page.b key: To go to back one page. Options: -d : Use this command in order to help the user to navigate. It displays “[Press space to continue, ‘q’ to quit.]” and displays “[Press ‘h’ for instructions.]” when wrong key is pressed.Example:more -d sample.txt Example: more -d sample.txt -f : This option does not wrap the long lines and displays them as such.Example:more -f sample.txt Example: more -f sample.txt -p : This option clears the screen and then displays the text.Example:more -p sample.txt Example: more -p sample.txt -c : This command is used to display the pages on the same area by overlapping the previously displayed text.Example:more -c sample.txt Example: more -c sample.txt -s : This option squeezes multiple blank lines into one single blank line.Example:more -s sample.txt Example: more -s sample.txt -u : This option omits the underlines.Example:more -u sample.txt Example: more -u sample.txt +/pattern : This option is used to search the string inside your text document. You can view all the instances by navigating through the result.Example:more +/reset sample.txt Example: more +/reset sample.txt +num : This option displays the text after the specified number of lines of the document.Example:more +30 sample.txt Example: more +30 sample.txt Using more to Read Long Outputs: We use more command after a pipe to see long outputs. For example, seeing log files, etc. cat a.txt | more Akanksha_Rai linux-command Linux-text-processing-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Oct, 2019" }, { "code": null, "e": 493, "s": 53, "text": "more command is used to view the text files in the command prompt, displaying one screen at a time in case the file is large (For example log files). The more command also allows the user do scroll up and down through the page. The syntax along with options and command is as follows. Another application of more is to use it with some other command after a pipe. When the output is large, we can use more command to see output one by one." }, { "code": null, "e": 501, "s": 493, "text": "Syntax:" }, { "code": null, "e": 559, "s": 501, "text": "more [-options] [-num] [+/pattern] [+linenum] [file_name]" }, { "code": null, "e": 718, "s": 559, "text": "[-options]: any option that you want to use in order to change the way the file is displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, -s, -u)" }, { "code": null, "e": 788, "s": 718, "text": "[-num]: type the number of lines that you want to display per screen." }, { "code": null, "e": 877, "s": 788, "text": "[+/pattern]: replace the pattern with any string that you want to find in the text file." }, { "code": null, "e": 967, "s": 877, "text": "[+linenum]: use the line number from where you want to start displaying the text content." }, { "code": null, "e": 1057, "s": 967, "text": "[file_name]: name of the file containing the text that you want to display on the screen." }, { "code": null, "e": 1105, "s": 1057, "text": "While viewing the text file use these controls:" }, { "code": null, "e": 1209, "s": 1105, "text": "Enter key: to scroll down line by line.Space bar: To go to the next page.b key: To go to back one page." }, { "code": null, "e": 1218, "s": 1209, "text": "Options:" }, { "code": null, "e": 1431, "s": 1218, "text": "-d : Use this command in order to help the user to navigate. It displays “[Press space to continue, ‘q’ to quit.]” and displays “[Press ‘h’ for instructions.]” when wrong key is pressed.Example:more -d sample.txt" }, { "code": null, "e": 1440, "s": 1431, "text": "Example:" }, { "code": null, "e": 1459, "s": 1440, "text": "more -d sample.txt" }, { "code": null, "e": 1558, "s": 1459, "text": "-f : This option does not wrap the long lines and displays them as such.Example:more -f sample.txt" }, { "code": null, "e": 1567, "s": 1558, "text": "Example:" }, { "code": null, "e": 1586, "s": 1567, "text": "more -f sample.txt" }, { "code": null, "e": 1675, "s": 1586, "text": "-p : This option clears the screen and then displays the text.Example:more -p sample.txt" }, { "code": null, "e": 1684, "s": 1675, "text": "Example:" }, { "code": null, "e": 1703, "s": 1684, "text": "more -p sample.txt" }, { "code": null, "e": 1839, "s": 1703, "text": "-c : This command is used to display the pages on the same area by overlapping the previously displayed text.Example:more -c sample.txt" }, { "code": null, "e": 1848, "s": 1839, "text": "Example:" }, { "code": null, "e": 1867, "s": 1848, "text": "more -c sample.txt" }, { "code": null, "e": 1968, "s": 1867, "text": "-s : This option squeezes multiple blank lines into one single blank line.Example:more -s sample.txt" }, { "code": null, "e": 1977, "s": 1968, "text": "Example:" }, { "code": null, "e": 1996, "s": 1977, "text": "more -s sample.txt" }, { "code": null, "e": 2061, "s": 1996, "text": "-u : This option omits the underlines.Example:more -u sample.txt" }, { "code": null, "e": 2070, "s": 2061, "text": "Example:" }, { "code": null, "e": 2089, "s": 2070, "text": "more -u sample.txt" }, { "code": null, "e": 2265, "s": 2089, "text": "+/pattern : This option is used to search the string inside your text document. You can view all the instances by navigating through the result.Example:more +/reset sample.txt" }, { "code": null, "e": 2274, "s": 2265, "text": "Example:" }, { "code": null, "e": 2298, "s": 2274, "text": "more +/reset sample.txt" }, { "code": null, "e": 2415, "s": 2298, "text": "+num : This option displays the text after the specified number of lines of the document.Example:more +30 sample.txt" }, { "code": null, "e": 2424, "s": 2415, "text": "Example:" }, { "code": null, "e": 2444, "s": 2424, "text": "more +30 sample.txt" }, { "code": null, "e": 2567, "s": 2444, "text": "Using more to Read Long Outputs: We use more command after a pipe to see long outputs. For example, seeing log files, etc." }, { "code": null, "e": 2585, "s": 2567, "text": "cat a.txt | more\n" }, { "code": null, "e": 2598, "s": 2585, "text": "Akanksha_Rai" }, { "code": null, "e": 2612, "s": 2598, "text": "linux-command" }, { "code": null, "e": 2643, "s": 2612, "text": "Linux-text-processing-commands" }, { "code": null, "e": 2650, "s": 2643, "text": "Picked" }, { "code": null, "e": 2661, "s": 2650, "text": "Linux-Unix" } ]
Number of subarrays having sum in a given range
22 Apr, 2021 Given an array arr[] of positive integers and a range (L, R). Find the number of subarrays having sum in the range L to R.Examples: Input : arr[] = {1, 4, 6}, L = 3, R = 8 Output : 3 The subarrays are {1, 4}, {4}, {6}. Input : arr[] = {2, 3, 5, 8}, L = 4, R = 13 Output : 6 The subarrays are {2, 3}, {2, 3, 5}, {3, 5}, {5}, {5, 8}, {8}. A simple solution is to one by one consider each subarray and find its sum. If the sum lies in the range [L, R], then increment the count. The time complexity of this solution is O(n^2).An efficient solution is to first find the number of subarrays having sum less than or equal to R. From this count, subtract the number of subarrays having sum less than or equal to L-1. To find the number of subarrays having sum less than or equal to the given value, the linear time method using the sliding window discussed in the following post is used: Number of subarrays having sum less than or equal to k.Below is the implementation of above approach: C++ Java C# Python 3 PHP Javascript // CPP program to find number of subarrays having// sum in the range L to R.#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays having// sum less than or equal to x.int countSub(int arr[], int n, int x){ // Starting index of sliding window. int st = 0; // Ending index of sliding window. int end = 0; // Sum of elements currently present // in sliding window. int sum = 0; // To store required number of subarrays. int cnt = 0; // Increment ending index of sliding // window one step at a time. while (end < n) { // Update sum of sliding window on // adding a new element. sum += arr[end]; // Increment starting index of sliding // window until sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of number of subarrays. cnt += (end - st + 1); end++; } return cnt;} // Function to find number of subarrays having// sum in the range L to R.int findSubSumLtoR(int arr[], int n, int L, int R){ // Number of subarrays having sum less // than or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays having sum less // than or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt;} // Driver code.int main(){ int arr[] = { 1, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 3; int R = 8; cout << findSubSumLtoR(arr, n, L, R); return 0;} // Java program to find number// of subarrays having sum in// the range L to R.import java.io.*; class GFG{ // Function to find number // of subarrays having sum // less than or equal to x. static int countSub(int arr[], int n, int x) { // Starting index of // sliding window. int st = 0; // Ending index of // sliding window. int end = 0; // Sum of elements currently // present in sliding window. int sum = 0; // To store required // number of subarrays. int cnt = 0; // Increment ending index // of sliding window one // step at a time. while (end < n) { // Update sum of sliding // window on adding a // new element. sum += arr[end]; // Increment starting index // of sliding window until // sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of // number of subarrays. cnt += (end - st + 1); end++; } return cnt; } // Function to find number // of subarrays having sum // in the range L to R. static int findSubSumLtoR(int arr[], int n, int L, int R) { // Number of subarrays // having sum less than // or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays // having sum less than // or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt; } // Driver code public static void main (String[] args) { int arr[] = { 1, 4, 6 }; int n = arr.length; int L = 3; int R = 8; System.out.println(findSubSumLtoR(arr, n, L, R)); }} // This code is contributed// by Mahadev99 // C# program to find number// of subarrays having sum in// the range L to R.using System; class GFG{ // Function to find number // of subarrays having sum // less than or equal to x. static int countSub(int[] arr, int n, int x) { // Starting index of // sliding window. int st = 0; // Ending index of // sliding window. int end = 0; // Sum of elements currently // present in sliding window. int sum = 0; // To store required // number of subarrays. int cnt = 0; // Increment ending index // of sliding window one // step at a time. while (end < n) { // Update sum of sliding // window on adding a // new element. sum += arr[end]; // Increment starting index // of sliding window until // sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of // number of subarrays. cnt += (end - st + 1); end++; } return cnt; } // Function to find number // of subarrays having sum // in the range L to R. static int findSubSumLtoR(int[] arr, int n, int L, int R) { // Number of subarrays // having sum less than // or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays // having sum less than // or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt; } // Driver code public static void Main () { int[] arr = { 1, 4, 6 }; int n = arr.Length; int L = 3; int R = 8; Console.Write(findSubSumLtoR(arr, n, L, R)); }} // This code is contributed// by ChitraNayal # Python 3 program to find# number of subarrays having# sum in the range L to R. # Function to find number# of subarrays having sum# less than or equal to x.def countSub(arr, n, x): # Starting index of # sliding window. st = 0 # Ending index of # sliding window. end = 0 # Sum of elements currently # present in sliding window. sum = 0 # To store required # number of subarrays. cnt = 0 # Increment ending index # of sliding window one # step at a time. while end < n : # Update sum of sliding # window on adding a # new element. sum += arr[end] # Increment starting index # of sliding window until # sum is greater than x. while (st <= end and sum > x) : sum -= arr[st] st += 1 # Update count of # number of subarrays. cnt += (end - st + 1) end += 1 return cnt # Function to find number# of subarrays having sum# in the range L to R.def findSubSumLtoR(arr, n, L, R): # Number of subarrays # having sum less # than or equal to R. Rcnt = countSub(arr, n, R) # Number of subarrays # having sum less than # or equal to L-1. Lcnt = countSub(arr, n, L - 1) return Rcnt - Lcnt # Driver codearr = [ 1, 4, 6 ]n = len(arr)L = 3R = 8print(findSubSumLtoR(arr, n, L, R)) # This code is contributed# by ChitraNayal <?php// PHP program to find number// of subarrays having sum// in the range L to R. // Function to find number// of subarrays having sum// less than or equal to x.function countSub(&$arr, $n, $x){ // Starting index of // sliding window. $st = 0; // Ending index of // sliding window. $end = 0; // Sum of elements currently // present in sliding window. $sum = 0; // To store required // number of subarrays. $cnt = 0; // Increment ending index // of sliding window one // step at a time. while ($end < $n) { // Update sum of sliding window // on adding a new element. $sum += $arr[$end]; // Increment starting index // of sliding window until // sum is greater than x. while ($st <= $end && $sum > $x) { $sum -= $arr[$st]; $st++; } // Update count of // number of subarrays. $cnt += ($end - $st + 1); $end++; } return $cnt;} // Function to find number// of subarrays having sum// in the range L to R.function findSubSumLtoR(&$arr, $n, $L, $R){ // Number of subarrays // having sum less // than or equal to R. $Rcnt = countSub($arr, $n, $R); // Number of subarrays // having sum less // than or equal to L-1. $Lcnt = countSub($arr, $n, $L - 1); return $Rcnt - $Lcnt;} // Driver code.$arr = array( 1, 4, 6 );$n = sizeof($arr);$L = 3;$R = 8;echo findSubSumLtoR($arr, $n, $L, $R); // This code is contributed// by ChitraNayal?> <script> // Javascript program to find number of subarrays having// sum in the range L to R. // Function to find number of subarrays having// sum less than or equal to x.function countSub(arr, n, x){ // Starting index of sliding window. var st = 0; // Ending index of sliding window. var end = 0; // Sum of elements currently present // in sliding window. var sum = 0; // To store required number of subarrays. var cnt = 0; // Increment ending index of sliding // window one step at a time. while (end < n) { // Update sum of sliding window on // adding a new element. sum += arr[end]; // Increment starting index of sliding // window until sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of number of subarrays. cnt += (end - st + 1); end++; } return cnt;} // Function to find number of subarrays having// sum in the range L to R.function findSubSumLtoR(arr, n, L, R){ // Number of subarrays having sum less // than or equal to R. var Rcnt = countSub(arr, n, R); // Number of subarrays having sum less // than or equal to L-1. var Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt;} // Driver code.var arr = [ 1, 4, 6 ];var n = arr.length;var L = 3;var R = 8;document.write( findSubSumLtoR(arr, n, L, R)); </script> Output: 3 Time Complexity: O(n) Auxiliary Space: O(1) Mahadev99 ukasp noob2000 sliding-window subarray subarray-sum Arrays sliding-window Arrays 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, 2021" }, { "code": null, "e": 186, "s": 52, "text": "Given an array arr[] of positive integers and a range (L, R). Find the number of subarrays having sum in the range L to R.Examples: " }, { "code": null, "e": 392, "s": 186, "text": "Input : arr[] = {1, 4, 6}, L = 3, R = 8\nOutput : 3\nThe subarrays are {1, 4}, {4}, {6}.\n\nInput : arr[] = {2, 3, 5, 8}, L = 4, R = 13\nOutput : 6\nThe subarrays are {2, 3}, {2, 3, 5}, {3, 5},\n{5}, {5, 8}, {8}." }, { "code": null, "e": 1041, "s": 394, "text": "A simple solution is to one by one consider each subarray and find its sum. If the sum lies in the range [L, R], then increment the count. The time complexity of this solution is O(n^2).An efficient solution is to first find the number of subarrays having sum less than or equal to R. From this count, subtract the number of subarrays having sum less than or equal to L-1. To find the number of subarrays having sum less than or equal to the given value, the linear time method using the sliding window discussed in the following post is used: Number of subarrays having sum less than or equal to k.Below is the implementation of above approach: " }, { "code": null, "e": 1045, "s": 1041, "text": "C++" }, { "code": null, "e": 1050, "s": 1045, "text": "Java" }, { "code": null, "e": 1053, "s": 1050, "text": "C#" }, { "code": null, "e": 1062, "s": 1053, "text": "Python 3" }, { "code": null, "e": 1066, "s": 1062, "text": "PHP" }, { "code": null, "e": 1077, "s": 1066, "text": "Javascript" }, { "code": "// CPP program to find number of subarrays having// sum in the range L to R.#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays having// sum less than or equal to x.int countSub(int arr[], int n, int x){ // Starting index of sliding window. int st = 0; // Ending index of sliding window. int end = 0; // Sum of elements currently present // in sliding window. int sum = 0; // To store required number of subarrays. int cnt = 0; // Increment ending index of sliding // window one step at a time. while (end < n) { // Update sum of sliding window on // adding a new element. sum += arr[end]; // Increment starting index of sliding // window until sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of number of subarrays. cnt += (end - st + 1); end++; } return cnt;} // Function to find number of subarrays having// sum in the range L to R.int findSubSumLtoR(int arr[], int n, int L, int R){ // Number of subarrays having sum less // than or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays having sum less // than or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt;} // Driver code.int main(){ int arr[] = { 1, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int L = 3; int R = 8; cout << findSubSumLtoR(arr, n, L, R); return 0;}", "e": 2606, "s": 1077, "text": null }, { "code": "// Java program to find number// of subarrays having sum in// the range L to R.import java.io.*; class GFG{ // Function to find number // of subarrays having sum // less than or equal to x. static int countSub(int arr[], int n, int x) { // Starting index of // sliding window. int st = 0; // Ending index of // sliding window. int end = 0; // Sum of elements currently // present in sliding window. int sum = 0; // To store required // number of subarrays. int cnt = 0; // Increment ending index // of sliding window one // step at a time. while (end < n) { // Update sum of sliding // window on adding a // new element. sum += arr[end]; // Increment starting index // of sliding window until // sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of // number of subarrays. cnt += (end - st + 1); end++; } return cnt; } // Function to find number // of subarrays having sum // in the range L to R. static int findSubSumLtoR(int arr[], int n, int L, int R) { // Number of subarrays // having sum less than // or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays // having sum less than // or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt; } // Driver code public static void main (String[] args) { int arr[] = { 1, 4, 6 }; int n = arr.length; int L = 3; int R = 8; System.out.println(findSubSumLtoR(arr, n, L, R)); }} // This code is contributed// by Mahadev99", "e": 4649, "s": 2606, "text": null }, { "code": "// C# program to find number// of subarrays having sum in// the range L to R.using System; class GFG{ // Function to find number // of subarrays having sum // less than or equal to x. static int countSub(int[] arr, int n, int x) { // Starting index of // sliding window. int st = 0; // Ending index of // sliding window. int end = 0; // Sum of elements currently // present in sliding window. int sum = 0; // To store required // number of subarrays. int cnt = 0; // Increment ending index // of sliding window one // step at a time. while (end < n) { // Update sum of sliding // window on adding a // new element. sum += arr[end]; // Increment starting index // of sliding window until // sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of // number of subarrays. cnt += (end - st + 1); end++; } return cnt; } // Function to find number // of subarrays having sum // in the range L to R. static int findSubSumLtoR(int[] arr, int n, int L, int R) { // Number of subarrays // having sum less than // or equal to R. int Rcnt = countSub(arr, n, R); // Number of subarrays // having sum less than // or equal to L-1. int Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt; } // Driver code public static void Main () { int[] arr = { 1, 4, 6 }; int n = arr.Length; int L = 3; int R = 8; Console.Write(findSubSumLtoR(arr, n, L, R)); }} // This code is contributed// by ChitraNayal", "e": 6670, "s": 4649, "text": null }, { "code": "# Python 3 program to find# number of subarrays having# sum in the range L to R. # Function to find number# of subarrays having sum# less than or equal to x.def countSub(arr, n, x): # Starting index of # sliding window. st = 0 # Ending index of # sliding window. end = 0 # Sum of elements currently # present in sliding window. sum = 0 # To store required # number of subarrays. cnt = 0 # Increment ending index # of sliding window one # step at a time. while end < n : # Update sum of sliding # window on adding a # new element. sum += arr[end] # Increment starting index # of sliding window until # sum is greater than x. while (st <= end and sum > x) : sum -= arr[st] st += 1 # Update count of # number of subarrays. cnt += (end - st + 1) end += 1 return cnt # Function to find number# of subarrays having sum# in the range L to R.def findSubSumLtoR(arr, n, L, R): # Number of subarrays # having sum less # than or equal to R. Rcnt = countSub(arr, n, R) # Number of subarrays # having sum less than # or equal to L-1. Lcnt = countSub(arr, n, L - 1) return Rcnt - Lcnt # Driver codearr = [ 1, 4, 6 ]n = len(arr)L = 3R = 8print(findSubSumLtoR(arr, n, L, R)) # This code is contributed# by ChitraNayal", "e": 8084, "s": 6670, "text": null }, { "code": "<?php// PHP program to find number// of subarrays having sum// in the range L to R. // Function to find number// of subarrays having sum// less than or equal to x.function countSub(&$arr, $n, $x){ // Starting index of // sliding window. $st = 0; // Ending index of // sliding window. $end = 0; // Sum of elements currently // present in sliding window. $sum = 0; // To store required // number of subarrays. $cnt = 0; // Increment ending index // of sliding window one // step at a time. while ($end < $n) { // Update sum of sliding window // on adding a new element. $sum += $arr[$end]; // Increment starting index // of sliding window until // sum is greater than x. while ($st <= $end && $sum > $x) { $sum -= $arr[$st]; $st++; } // Update count of // number of subarrays. $cnt += ($end - $st + 1); $end++; } return $cnt;} // Function to find number// of subarrays having sum// in the range L to R.function findSubSumLtoR(&$arr, $n, $L, $R){ // Number of subarrays // having sum less // than or equal to R. $Rcnt = countSub($arr, $n, $R); // Number of subarrays // having sum less // than or equal to L-1. $Lcnt = countSub($arr, $n, $L - 1); return $Rcnt - $Lcnt;} // Driver code.$arr = array( 1, 4, 6 );$n = sizeof($arr);$L = 3;$R = 8;echo findSubSumLtoR($arr, $n, $L, $R); // This code is contributed// by ChitraNayal?>", "e": 9614, "s": 8084, "text": null }, { "code": "<script> // Javascript program to find number of subarrays having// sum in the range L to R. // Function to find number of subarrays having// sum less than or equal to x.function countSub(arr, n, x){ // Starting index of sliding window. var st = 0; // Ending index of sliding window. var end = 0; // Sum of elements currently present // in sliding window. var sum = 0; // To store required number of subarrays. var cnt = 0; // Increment ending index of sliding // window one step at a time. while (end < n) { // Update sum of sliding window on // adding a new element. sum += arr[end]; // Increment starting index of sliding // window until sum is greater than x. while (st <= end && sum > x) { sum -= arr[st]; st++; } // Update count of number of subarrays. cnt += (end - st + 1); end++; } return cnt;} // Function to find number of subarrays having// sum in the range L to R.function findSubSumLtoR(arr, n, L, R){ // Number of subarrays having sum less // than or equal to R. var Rcnt = countSub(arr, n, R); // Number of subarrays having sum less // than or equal to L-1. var Lcnt = countSub(arr, n, L - 1); return Rcnt - Lcnt;} // Driver code.var arr = [ 1, 4, 6 ];var n = arr.length;var L = 3;var R = 8;document.write( findSubSumLtoR(arr, n, L, R)); </script>", "e": 11045, "s": 9614, "text": null }, { "code": null, "e": 11055, "s": 11045, "text": "Output: " }, { "code": null, "e": 11058, "s": 11055, "text": " 3" }, { "code": null, "e": 11103, "s": 11058, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 11113, "s": 11103, "text": "Mahadev99" }, { "code": null, "e": 11119, "s": 11113, "text": "ukasp" }, { "code": null, "e": 11128, "s": 11119, "text": "noob2000" }, { "code": null, "e": 11143, "s": 11128, "text": "sliding-window" }, { "code": null, "e": 11152, "s": 11143, "text": "subarray" }, { "code": null, "e": 11165, "s": 11152, "text": "subarray-sum" }, { "code": null, "e": 11172, "s": 11165, "text": "Arrays" }, { "code": null, "e": 11187, "s": 11172, "text": "sliding-window" }, { "code": null, "e": 11194, "s": 11187, "text": "Arrays" } ]
Solve Linear Algebraic Equation in R Programming – solve() Function
25 Jun, 2020 solve() function in R Language is used to solve linear algebraic equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated. Syntax: solve(a, b) Parameters:a: coefficients of the equationb: vector or matrix of the equation Example 1: # R program to illustrate# solve function # Calling solve() function to# calculate value of x in# ax = b, where a and b is # taken as the argumentssolve(5, 10)solve(2, 6)solve(3, 12) Output: [1] 2 [1] 3 [1] 4 Example 2: # R program to illustrate# solve function # Create 3 different vectors # using combine method. a1 <- c(3, 2, 5) a2 <- c(2, 3, 2) a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically # row-wise bindingA <- rbind(a1, a2, a3) # print the original matrix print(A) # Use the solve() function # to calculate the inverseT1 <- solve(A) # print the inverse of the matrixprint(T1) Output: [, 1] [, 2] [, 3] a1 3 2 5 a2 2 3 2 a3 5 2 4 a1 a2 a3 [1, ] -0.29629630 -0.07407407 0.4074074 [2, ] -0.07407407 0.48148148 -0.1481481 [3, ] 0.40740741 -0.14814815 -0.1851852 R Math-Function 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": "\n25 Jun, 2020" }, { "code": null, "e": 223, "s": 28, "text": "solve() function in R Language is used to solve linear algebraic equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated." }, { "code": null, "e": 243, "s": 223, "text": "Syntax: solve(a, b)" }, { "code": null, "e": 321, "s": 243, "text": "Parameters:a: coefficients of the equationb: vector or matrix of the equation" }, { "code": null, "e": 332, "s": 321, "text": "Example 1:" }, { "code": "# R program to illustrate# solve function # Calling solve() function to# calculate value of x in# ax = b, where a and b is # taken as the argumentssolve(5, 10)solve(2, 6)solve(3, 12)", "e": 516, "s": 332, "text": null }, { "code": null, "e": 524, "s": 516, "text": "Output:" }, { "code": null, "e": 543, "s": 524, "text": "[1] 2\n[1] 3\n[1] 4\n" }, { "code": null, "e": 554, "s": 543, "text": "Example 2:" }, { "code": "# R program to illustrate# solve function # Create 3 different vectors # using combine method. a1 <- c(3, 2, 5) a2 <- c(2, 3, 2) a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically # row-wise bindingA <- rbind(a1, a2, a3) # print the original matrix print(A) # Use the solve() function # to calculate the inverseT1 <- solve(A) # print the inverse of the matrixprint(T1) ", "e": 983, "s": 554, "text": null }, { "code": null, "e": 991, "s": 983, "text": "Output:" }, { "code": null, "e": 1230, "s": 991, "text": " [, 1] [, 2] [, 3]\na1 3 2 5\na2 2 3 2\na3 5 2 4\n a1 a2 a3\n[1, ] -0.29629630 -0.07407407 0.4074074\n[2, ] -0.07407407 0.48148148 -0.1481481\n[3, ] 0.40740741 -0.14814815 -0.1851852\n" }, { "code": null, "e": 1246, "s": 1230, "text": "R Math-Function" }, { "code": null, "e": 1257, "s": 1246, "text": "R Language" } ]
Making an Autoencoder. Using Keras and training on MNIST | by Arvin Singh Kushwaha | Towards Data Science
Autoencoders are a class of Unsupervised Networks that consist of two major networks: Encoders and Decoders. An Unsupervised Network is a network that learns patterns from data without any training labels. The network finds its patterns in the data without being told what the patterns should be. In contrast, there are Supervised Networks wherein the network is trained to return specific outputs when given specific inputs. The Encoder generally uses a series of Dense and/or Convolutional layers to encode an image into a fixed length vector that represents the image a compact form, while the Decoder uses Dense and/or Convolutional layers to convert the latent representation vector back into that same image or another modified image. The image above shows an example of a simple autoencoder. In this autoencoder, you can see that the input of size X is compressed into a latent vector of size Z and then decompressed into the same image of size X. To generate an image, a random input vector is given to the Decoder network. The Decoder network will convert the input vector into a full image. I recommend using Google Colab to run and train the Autoencoder model. #If you have a GPU that supports CUDA$ pip3 install tensorflow-gpu==2.0.0b1#Otherwise$ pip3 install tensorflow==2.0.0b1 Tensorflow 2.0 has Keras built-in as its high-level API. Keras is accessible through this import: import tensorflow.keras as keras from tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Input, Flatten,\ Reshape, LeakyReLU as LR,\ Activation, Dropoutfrom tensorflow.keras.models import Model, Sequentialfrom matplotlib import pyplot as pltfrom IPython import display # If using IPython, Colab or Jupyterimport numpy as np (x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train/255.0x_test = x_test/255.0 The MNIST dataset is comprised of 70000 28 pixels by 28 pixels images of handwritten digits and 70000 vectors containing information on which digit each one is. The image training data is scaled from [0, 255] to [0,1] to allow for use of the sigmoid activation function. To check our data, we’ll plot the first image in the training dataset. # Plot image data from x_trainplt.imshow(x_train[0], cmap = "gray")plt.show() Latent size is the size of the latent space: the vector holding the information after compression. This value is a crucial hyperparameter. If this value is too small, there won’t be enough data for reconstruction and if the value is too large, overfitting can occur. I found that a nice, successful latent size was 32 values long. LATENT_SIZE = 32 encoder = Sequential([ Flatten(input_shape = (28, 28)), Dense(512), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(64), LR(), Dropout(0.5), Dense(LATENT_SIZE), LR()]) The encoder consists of a series of Dense layers with interstitial Dropout and LeakyReLU layers. The Dense Layers allow for the compression of the 28x28 input tensor down to the latent vector of size 32. The Dropout layers help prevent overfitting and LeakyReLU, being the activation layer, introduces non-linearity into the mix. Dense(LATENT_SIZE) creates the final vector of size 32. decoder = Sequential([ Dense(64, input_shape = (LATENT_SIZE,)), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(512), LR(), Dropout(0.5), Dense(784), Activation("sigmoid"), Reshape((28, 28))]) The decoder is essentially the same as the encoder but in reverse. The final activation layer is sigmoid, however. The sigmoid activation function output values in the range [0, 1] which fits perfectly with our scaled image data. To create the full model, the Keras Functional API must be used. The Functional API allows us to string together multiple models. img = Input(shape = (28, 28)) This will create a placeholder tensor which we can feed into each network to get the output of the whole model. latent_vector = encoder(img)output = decoder(latent_vector) The best part about the Keras Functional API is how readable it is. The Keras Functional API allows you to call models directly onto tensors and get the output from that tensor. By calling the encoder model onto the img tensor, I get the latent_vector. The same can be done with the decoder model onto the latent_vector which gives us the output. model = Model(inputs = img, outputs = output)model.compile("nadam", loss = "binary_crossentropy") To create the model itself, you use the Model class and define what the inputs and outputs of the model are. To train a model, you must compile it. To compile a model, you have to choose an optimizer and a loss function. For the optimizer, I chose Nadam, which is Nesterov Accelerated Gradient applied to Adaptive Moment Estimation. It is a modified Adam optimizer. For the loss, I chose binary cross-entropy. Binary Cross-Entropy is very commonly used with Autoencoders. Usually, however, binary cross-entropy is used with Binary Classifiers. Additionally, binary cross-entropy can only be used between output values in the range [0, 1]. EPOCHS = 60 The value EPOCHS is a hyperparameter set to 60. Generally, the more epochs the better, at least until the model plateaus out. #Only do plotting if you have IPython, Jupyter, or using Colab Repeatedly plotting is really only recommended if you are using IPython, Jupyter, or Colab so that the matplotlib plots are inline and not repeatedly creating individual plots. for epoch in range(EPOCHS): fig, axs = plt.subplots(4, 4) rand = x_test[np.random.randint(0, 10000, 16)].reshape((4, 4, 1, 28, 28)) display.clear_output() # If you imported display from IPython for i in range(4): for j in range(4): axs[i, j].imshow(model.predict(rand[i, j])[0], cmap = "gray") axs[i, j].axis("off") plt.subplots_adjust(wspace = 0, hspace = 0) plt.show() print("-----------", "EPOCH", epoch, "-----------") model.fit(x_train, x_train) First, we create plots with 4 rows and 4 columns of subplots and choose 16 random testing data images to check how well the network performs. Next, we clear the screen (only works on IPython, Jupyter, and Colab) and plot the predictions by the model on the random testing images. Finally, we train the model. To train the model we simply call model.fit on the training image data. Remember how the autoencoder’s goal is to take the input data, compress it, decompress it, and then output a copy of the input data? Well, that means that the input and the target output are both the training image data. As you can see, these generated images are pretty good. The biggest problem with the images, however, is with the blurriness. Many of these problems can be fixed with other types of Generative Networks or even other types of Autoencoders. from tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Input, Flatten,\ Reshape, LeakyReLU as LR,\ Activation, Dropoutfrom tensorflow.keras.models import Model, Sequentialfrom matplotlib import pyplot as pltfrom IPython import display # If using IPython, Colab or Jupyterimport numpy as np(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train/255.0x_test = x_test/255.0# Plot image data from x_trainplt.imshow(x_train[0], cmap = "gray")plt.show()LATENT_SIZE = 32encoder = Sequential([ Flatten(input_shape = (28, 28)), Dense(512), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(64), LR(), Dropout(0.5), Dense(LATENT_SIZE), LR()])decoder = Sequential([ Dense(64, input_shape = (LATENT_SIZE,)), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(512), LR(), Dropout(0.5), Dense(784), Activation("sigmoid"), Reshape((28, 28))])img = Input(shape = (28, 28))latent_vector = encoder(img)output = decoder(latent_vector)model = Model(inputs = img, outputs = output)model.compile("nadam", loss = "binary_crossentropy")EPOCHS = 60#Only do plotting if you have IPython, Jupyter, or using Colabfor epoch in range(EPOCHS): fig, axs = plt.subplots(4, 4) rand = x_test[np.random.randint(0, 10000, 16)].reshape((4, 4, 1, 28, 28)) display.clear_output() # If you imported display from IPython for i in range(4): for j in range(4): axs[i, j].imshow(model.predict(rand[i, j])[0], cmap = "gray") axs[i, j].axis("off") plt.subplots_adjust(wspace = 0, hspace = 0) plt.show() print("-----------", "EPOCH", epoch, "-----------") model.fit(x_train, x_train) A Google Colab for this Code can be found here. After training for 60 epochs, I got this image: As you can see, the results are pretty good. The autoencoder successfully encodes and decodes the latent space vectors with pretty good quality. This autoencoder is the “vanilla” variety, but other types like Variational Autoencoders have even better quality images. Also, by increasing the number of epochs, results can be improved further. Autoencoders, put simply, learn how to compress and decompress data efficiently without supervision. This means Autoencoders can be used for dimensionality reduction. The Decoder sections of an Autoencoder can also be used to generate images from a noise vector. Practical applications of an Autoencoder network include: Denoising Image Reconstruction Image Generation Data Compression & Decompression Some rights reserved
[ { "code": null, "e": 280, "s": 171, "text": "Autoencoders are a class of Unsupervised Networks that consist of two major networks: Encoders and Decoders." }, { "code": null, "e": 468, "s": 280, "text": "An Unsupervised Network is a network that learns patterns from data without any training labels. The network finds its patterns in the data without being told what the patterns should be." }, { "code": null, "e": 597, "s": 468, "text": "In contrast, there are Supervised Networks wherein the network is trained to return specific outputs when given specific inputs." }, { "code": null, "e": 912, "s": 597, "text": "The Encoder generally uses a series of Dense and/or Convolutional layers to encode an image into a fixed length vector that represents the image a compact form, while the Decoder uses Dense and/or Convolutional layers to convert the latent representation vector back into that same image or another modified image." }, { "code": null, "e": 1126, "s": 912, "text": "The image above shows an example of a simple autoencoder. In this autoencoder, you can see that the input of size X is compressed into a latent vector of size Z and then decompressed into the same image of size X." }, { "code": null, "e": 1272, "s": 1126, "text": "To generate an image, a random input vector is given to the Decoder network. The Decoder network will convert the input vector into a full image." }, { "code": null, "e": 1343, "s": 1272, "text": "I recommend using Google Colab to run and train the Autoencoder model." }, { "code": null, "e": 1463, "s": 1343, "text": "#If you have a GPU that supports CUDA$ pip3 install tensorflow-gpu==2.0.0b1#Otherwise$ pip3 install tensorflow==2.0.0b1" }, { "code": null, "e": 1561, "s": 1463, "text": "Tensorflow 2.0 has Keras built-in as its high-level API. Keras is accessible through this import:" }, { "code": null, "e": 1594, "s": 1561, "text": "import tensorflow.keras as keras" }, { "code": null, "e": 1985, "s": 1594, "text": "from tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Input, Flatten,\\ Reshape, LeakyReLU as LR,\\ Activation, Dropoutfrom tensorflow.keras.models import Model, Sequentialfrom matplotlib import pyplot as pltfrom IPython import display # If using IPython, Colab or Jupyterimport numpy as np" }, { "code": null, "e": 2086, "s": 1985, "text": "(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train/255.0x_test = x_test/255.0" }, { "code": null, "e": 2247, "s": 2086, "text": "The MNIST dataset is comprised of 70000 28 pixels by 28 pixels images of handwritten digits and 70000 vectors containing information on which digit each one is." }, { "code": null, "e": 2357, "s": 2247, "text": "The image training data is scaled from [0, 255] to [0,1] to allow for use of the sigmoid activation function." }, { "code": null, "e": 2428, "s": 2357, "text": "To check our data, we’ll plot the first image in the training dataset." }, { "code": null, "e": 2506, "s": 2428, "text": "# Plot image data from x_trainplt.imshow(x_train[0], cmap = \"gray\")plt.show()" }, { "code": null, "e": 2773, "s": 2506, "text": "Latent size is the size of the latent space: the vector holding the information after compression. This value is a crucial hyperparameter. If this value is too small, there won’t be enough data for reconstruction and if the value is too large, overfitting can occur." }, { "code": null, "e": 2837, "s": 2773, "text": "I found that a nice, successful latent size was 32 values long." }, { "code": null, "e": 2854, "s": 2837, "text": "LATENT_SIZE = 32" }, { "code": null, "e": 3109, "s": 2854, "text": "encoder = Sequential([ Flatten(input_shape = (28, 28)), Dense(512), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(64), LR(), Dropout(0.5), Dense(LATENT_SIZE), LR()])" }, { "code": null, "e": 3495, "s": 3109, "text": "The encoder consists of a series of Dense layers with interstitial Dropout and LeakyReLU layers. The Dense Layers allow for the compression of the 28x28 input tensor down to the latent vector of size 32. The Dropout layers help prevent overfitting and LeakyReLU, being the activation layer, introduces non-linearity into the mix. Dense(LATENT_SIZE) creates the final vector of size 32." }, { "code": null, "e": 3775, "s": 3495, "text": "decoder = Sequential([ Dense(64, input_shape = (LATENT_SIZE,)), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(512), LR(), Dropout(0.5), Dense(784), Activation(\"sigmoid\"), Reshape((28, 28))])" }, { "code": null, "e": 4005, "s": 3775, "text": "The decoder is essentially the same as the encoder but in reverse. The final activation layer is sigmoid, however. The sigmoid activation function output values in the range [0, 1] which fits perfectly with our scaled image data." }, { "code": null, "e": 4135, "s": 4005, "text": "To create the full model, the Keras Functional API must be used. The Functional API allows us to string together multiple models." }, { "code": null, "e": 4165, "s": 4135, "text": "img = Input(shape = (28, 28))" }, { "code": null, "e": 4277, "s": 4165, "text": "This will create a placeholder tensor which we can feed into each network to get the output of the whole model." }, { "code": null, "e": 4337, "s": 4277, "text": "latent_vector = encoder(img)output = decoder(latent_vector)" }, { "code": null, "e": 4684, "s": 4337, "text": "The best part about the Keras Functional API is how readable it is. The Keras Functional API allows you to call models directly onto tensors and get the output from that tensor. By calling the encoder model onto the img tensor, I get the latent_vector. The same can be done with the decoder model onto the latent_vector which gives us the output." }, { "code": null, "e": 4782, "s": 4684, "text": "model = Model(inputs = img, outputs = output)model.compile(\"nadam\", loss = \"binary_crossentropy\")" }, { "code": null, "e": 4891, "s": 4782, "text": "To create the model itself, you use the Model class and define what the inputs and outputs of the model are." }, { "code": null, "e": 5421, "s": 4891, "text": "To train a model, you must compile it. To compile a model, you have to choose an optimizer and a loss function. For the optimizer, I chose Nadam, which is Nesterov Accelerated Gradient applied to Adaptive Moment Estimation. It is a modified Adam optimizer. For the loss, I chose binary cross-entropy. Binary Cross-Entropy is very commonly used with Autoencoders. Usually, however, binary cross-entropy is used with Binary Classifiers. Additionally, binary cross-entropy can only be used between output values in the range [0, 1]." }, { "code": null, "e": 5433, "s": 5421, "text": "EPOCHS = 60" }, { "code": null, "e": 5559, "s": 5433, "text": "The value EPOCHS is a hyperparameter set to 60. Generally, the more epochs the better, at least until the model plateaus out." }, { "code": null, "e": 5622, "s": 5559, "text": "#Only do plotting if you have IPython, Jupyter, or using Colab" }, { "code": null, "e": 5799, "s": 5622, "text": "Repeatedly plotting is really only recommended if you are using IPython, Jupyter, or Colab so that the matplotlib plots are inline and not repeatedly creating individual plots." }, { "code": null, "e": 6315, "s": 5799, "text": "for epoch in range(EPOCHS): fig, axs = plt.subplots(4, 4) rand = x_test[np.random.randint(0, 10000, 16)].reshape((4, 4, 1, 28, 28)) display.clear_output() # If you imported display from IPython for i in range(4): for j in range(4): axs[i, j].imshow(model.predict(rand[i, j])[0], cmap = \"gray\") axs[i, j].axis(\"off\") plt.subplots_adjust(wspace = 0, hspace = 0) plt.show() print(\"-----------\", \"EPOCH\", epoch, \"-----------\") model.fit(x_train, x_train)" }, { "code": null, "e": 6457, "s": 6315, "text": "First, we create plots with 4 rows and 4 columns of subplots and choose 16 random testing data images to check how well the network performs." }, { "code": null, "e": 6595, "s": 6457, "text": "Next, we clear the screen (only works on IPython, Jupyter, and Colab) and plot the predictions by the model on the random testing images." }, { "code": null, "e": 6917, "s": 6595, "text": "Finally, we train the model. To train the model we simply call model.fit on the training image data. Remember how the autoencoder’s goal is to take the input data, compress it, decompress it, and then output a copy of the input data? Well, that means that the input and the target output are both the training image data." }, { "code": null, "e": 7156, "s": 6917, "text": "As you can see, these generated images are pretty good. The biggest problem with the images, however, is with the blurriness. Many of these problems can be fixed with other types of Generative Networks or even other types of Autoencoders." }, { "code": null, "e": 9046, "s": 7156, "text": "from tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Input, Flatten,\\ Reshape, LeakyReLU as LR,\\ Activation, Dropoutfrom tensorflow.keras.models import Model, Sequentialfrom matplotlib import pyplot as pltfrom IPython import display # If using IPython, Colab or Jupyterimport numpy as np(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train/255.0x_test = x_test/255.0# Plot image data from x_trainplt.imshow(x_train[0], cmap = \"gray\")plt.show()LATENT_SIZE = 32encoder = Sequential([ Flatten(input_shape = (28, 28)), Dense(512), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(64), LR(), Dropout(0.5), Dense(LATENT_SIZE), LR()])decoder = Sequential([ Dense(64, input_shape = (LATENT_SIZE,)), LR(), Dropout(0.5), Dense(128), LR(), Dropout(0.5), Dense(256), LR(), Dropout(0.5), Dense(512), LR(), Dropout(0.5), Dense(784), Activation(\"sigmoid\"), Reshape((28, 28))])img = Input(shape = (28, 28))latent_vector = encoder(img)output = decoder(latent_vector)model = Model(inputs = img, outputs = output)model.compile(\"nadam\", loss = \"binary_crossentropy\")EPOCHS = 60#Only do plotting if you have IPython, Jupyter, or using Colabfor epoch in range(EPOCHS): fig, axs = plt.subplots(4, 4) rand = x_test[np.random.randint(0, 10000, 16)].reshape((4, 4, 1, 28, 28)) display.clear_output() # If you imported display from IPython for i in range(4): for j in range(4): axs[i, j].imshow(model.predict(rand[i, j])[0], cmap = \"gray\") axs[i, j].axis(\"off\") plt.subplots_adjust(wspace = 0, hspace = 0) plt.show() print(\"-----------\", \"EPOCH\", epoch, \"-----------\") model.fit(x_train, x_train)" }, { "code": null, "e": 9094, "s": 9046, "text": "A Google Colab for this Code can be found here." }, { "code": null, "e": 9142, "s": 9094, "text": "After training for 60 epochs, I got this image:" }, { "code": null, "e": 9484, "s": 9142, "text": "As you can see, the results are pretty good. The autoencoder successfully encodes and decodes the latent space vectors with pretty good quality. This autoencoder is the “vanilla” variety, but other types like Variational Autoencoders have even better quality images. Also, by increasing the number of epochs, results can be improved further." }, { "code": null, "e": 9747, "s": 9484, "text": "Autoencoders, put simply, learn how to compress and decompress data efficiently without supervision. This means Autoencoders can be used for dimensionality reduction. The Decoder sections of an Autoencoder can also be used to generate images from a noise vector." }, { "code": null, "e": 9805, "s": 9747, "text": "Practical applications of an Autoencoder network include:" }, { "code": null, "e": 9815, "s": 9805, "text": "Denoising" }, { "code": null, "e": 9836, "s": 9815, "text": "Image Reconstruction" }, { "code": null, "e": 9853, "s": 9836, "text": "Image Generation" }, { "code": null, "e": 9886, "s": 9853, "text": "Data Compression & Decompression" } ]
ADDTIME() function in MySQL - GeeksforGeeks
16 Nov, 2020 ADDTIME() function in MySQL is used to add the specified time intervals to the given date and time. It returns the date or DateTime after adding the time interval. Syntax : ADDTIME(expr1, expr2) Parameter : This method accepts two parameter. expr1 : The given datetime or time which we want to modify. expr2 : The time interval which we want to add to given datetime. It can be both positive and negative. Returns : It returns the date or DateTime after adding the given time interval. Example-1 :Adding 15 seconds with the specified time using ADDTIME Function. SELECT ADDTIME("11:34:21", "15") as Updated_time ; Output : Example-2 :Adding 10 minutes with the specified time using ADDTIME Function. SELECT ADDTIME("10:54:21", "00:10:00") as Updated_time ; Output : Example-3 :Adding 12 hours with the specified datetime using ADDTIME Function. SELECT ADDTIME("2009-02-20 18:04:22.333444", "12:00:00") as Updated_time ; Output : Example-4 :Adding 10 hours 30 minute 25 second and 100000 Microseconds with the specified datetime using ADDTIME Function. SELECT ADDTIME("2020-09-20 17:04:22.222333", "10:30:25.100000") as Updated_time ; Output : Example-5 :The ADDTIME function can be used to set value of columns. To demonstrate create a table named ScheduleDetails CREATE TABLE ScheduleDetails( TrainId INT NOT NULL, StationName VARCHAR(20) NOT NULL, TrainName VARCHAR(20) NOT NULL, ScheduledlArrivalTime TIME NOT NULL, PRIMARY KEY(TrainId ) ); Now inserting values in ScheduleDetails table. We will use ADDTIME function which will denote delay in arrival timing. The value in ExpectedArrivalTime column will be the value given by ADDTIME Function. INSERT INTO ScheduleDetails (TrainId, StationName, TrainName, ScheduledlArrivalTime ) VALUES (12345, 'NJP', 'Saraighat Express', "17:04:22"); Now, checking the ScheduleDetails table : SELECT *, ADDTIME(ScheduledlArrivalTime, "00:10:00") AS ExpectedArrivalTime FROM ScheduleDetails; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery SQL Query to Convert VARCHAR to INT SQL | Date functions SQL - SELECT from Multiple Tables with MS SQL Server SQL Query to Insert Multiple Rows
[ { "code": null, "e": 24268, "s": 24240, "text": "\n16 Nov, 2020" }, { "code": null, "e": 24432, "s": 24268, "text": "ADDTIME() function in MySQL is used to add the specified time intervals to the given date and time. It returns the date or DateTime after adding the time interval." }, { "code": null, "e": 24441, "s": 24432, "text": "Syntax :" }, { "code": null, "e": 24464, "s": 24441, "text": "ADDTIME(expr1, expr2)\n" }, { "code": null, "e": 24511, "s": 24464, "text": "Parameter : This method accepts two parameter." }, { "code": null, "e": 24571, "s": 24511, "text": "expr1 : The given datetime or time which we want to modify." }, { "code": null, "e": 24675, "s": 24571, "text": "expr2 : The time interval which we want to add to given datetime. It can be both positive and negative." }, { "code": null, "e": 24755, "s": 24675, "text": "Returns : It returns the date or DateTime after adding the given time interval." }, { "code": null, "e": 24832, "s": 24755, "text": "Example-1 :Adding 15 seconds with the specified time using ADDTIME Function." }, { "code": null, "e": 24884, "s": 24832, "text": "SELECT ADDTIME(\"11:34:21\", \"15\") as Updated_time ;\n" }, { "code": null, "e": 24893, "s": 24884, "text": "Output :" }, { "code": null, "e": 24970, "s": 24893, "text": "Example-2 :Adding 10 minutes with the specified time using ADDTIME Function." }, { "code": null, "e": 25029, "s": 24970, "text": "SELECT ADDTIME(\"10:54:21\", \"00:10:00\") \nas Updated_time ;\n" }, { "code": null, "e": 25038, "s": 25029, "text": "Output :" }, { "code": null, "e": 25117, "s": 25038, "text": "Example-3 :Adding 12 hours with the specified datetime using ADDTIME Function." }, { "code": null, "e": 25194, "s": 25117, "text": "SELECT ADDTIME(\"2009-02-20 18:04:22.333444\", \"12:00:00\") \nas Updated_time ;\n" }, { "code": null, "e": 25203, "s": 25194, "text": "Output :" }, { "code": null, "e": 25326, "s": 25203, "text": "Example-4 :Adding 10 hours 30 minute 25 second and 100000 Microseconds with the specified datetime using ADDTIME Function." }, { "code": null, "e": 25410, "s": 25326, "text": "SELECT ADDTIME(\"2020-09-20 17:04:22.222333\", \"10:30:25.100000\") \nas Updated_time ;\n" }, { "code": null, "e": 25419, "s": 25410, "text": "Output :" }, { "code": null, "e": 25540, "s": 25419, "text": "Example-5 :The ADDTIME function can be used to set value of columns. To demonstrate create a table named ScheduleDetails" }, { "code": null, "e": 25720, "s": 25540, "text": "CREATE TABLE ScheduleDetails(\nTrainId INT NOT NULL,\nStationName VARCHAR(20) NOT NULL,\nTrainName VARCHAR(20) NOT NULL,\nScheduledlArrivalTime TIME NOT NULL,\nPRIMARY KEY(TrainId )\n);" }, { "code": null, "e": 25924, "s": 25720, "text": "Now inserting values in ScheduleDetails table. We will use ADDTIME function which will denote delay in arrival timing. The value in ExpectedArrivalTime column will be the value given by ADDTIME Function." }, { "code": null, "e": 26069, "s": 25924, "text": "INSERT INTO \nScheduleDetails (TrainId, StationName, TrainName, ScheduledlArrivalTime )\nVALUES\n(12345, 'NJP', 'Saraighat Express', \"17:04:22\");\n" }, { "code": null, "e": 26111, "s": 26069, "text": "Now, checking the ScheduleDetails table :" }, { "code": null, "e": 26211, "s": 26111, "text": "SELECT *, ADDTIME(ScheduledlArrivalTime, \"00:10:00\") \nAS ExpectedArrivalTime FROM ScheduleDetails;\n" }, { "code": null, "e": 26220, "s": 26211, "text": "Output :" }, { "code": null, "e": 26229, "s": 26220, "text": "DBMS-SQL" }, { "code": null, "e": 26235, "s": 26229, "text": "mysql" }, { "code": null, "e": 26239, "s": 26235, "text": "SQL" }, { "code": null, "e": 26243, "s": 26239, "text": "SQL" }, { "code": null, "e": 26341, "s": 26243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26350, "s": 26341, "text": "Comments" }, { "code": null, "e": 26363, "s": 26350, "text": "Old Comments" }, { "code": null, "e": 26429, "s": 26363, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26482, "s": 26429, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 26514, "s": 26482, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26592, "s": 26514, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26609, "s": 26592, "text": "SQL using Python" }, { "code": null, "e": 26624, "s": 26609, "text": "SQL | Subquery" }, { "code": null, "e": 26660, "s": 26624, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 26681, "s": 26660, "text": "SQL | Date functions" }, { "code": null, "e": 26734, "s": 26681, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" } ]
How to set the maximized bounds for a Frame in Java?
To set maximized bounds, use the setMaximizedBounds() method. Here, we will create a frame, which when maximized will form a shape − JFrame frame = new JFrame("Login!"); Above, we have created a frame and now we will use the Rectangle class to specify an area of coordinates − Rectangle bounds = new Rectangle(50, 10, 100, 200); Now, set maximized bounds − frame.setMaximizedBounds(bounds); The following is an example to set the maximized bounds for a frame − package my; import java.awt.GridLayout; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Login!"); JLabel label1, label2, label3; frame.setLayout(new GridLayout(2, 2)); label1 = new JLabel("DeptId", SwingConstants.CENTER); label2 = new JLabel("SSN", SwingConstants.CENTER); label3 = new JLabel("Password", SwingConstants.CENTER); JTextField deptid = new JTextField(20); JTextField ssn = new JTextField(20); JPasswordField passwd = new JPasswordField(); passwd.setEchoChar('*'); frame.add(label1); frame.add(label2); frame.add(label3); frame.add(deptid); frame.add(ssn); frame.add(passwd); Rectangle bounds = new Rectangle(50, 10, 100, 200); frame.setMaximizedBounds(bounds); frame.setSize(550, 200); frame.setVisible(true); } } Now, maximize it and you can see the rectangle bounds set above −
[ { "code": null, "e": 1195, "s": 1062, "text": "To set maximized bounds, use the setMaximizedBounds() method. Here, we will create a frame, which when maximized will form a shape −" }, { "code": null, "e": 1232, "s": 1195, "text": "JFrame frame = new JFrame(\"Login!\");" }, { "code": null, "e": 1339, "s": 1232, "text": "Above, we have created a frame and now we will use the Rectangle class to specify an area of coordinates −" }, { "code": null, "e": 1453, "s": 1339, "text": "Rectangle bounds = new Rectangle(50, 10, 100, 200);\nNow, set maximized bounds −\nframe.setMaximizedBounds(bounds);" }, { "code": null, "e": 1523, "s": 1453, "text": "The following is an example to set the maximized bounds for a frame −" }, { "code": null, "e": 2620, "s": 1523, "text": "package my;\nimport java.awt.GridLayout;\nimport java.awt.Rectangle;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Login!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"DeptId\", SwingConstants.CENTER);\n label2 = new JLabel(\"SSN\", SwingConstants.CENTER);\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n JTextField deptid = new JTextField(20);\n JTextField ssn = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(deptid);\n frame.add(ssn);\n frame.add(passwd);\n Rectangle bounds = new Rectangle(50, 10, 100, 200);\n frame.setMaximizedBounds(bounds);\n frame.setSize(550, 200);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2686, "s": 2620, "text": "Now, maximize it and you can see the rectangle bounds set above −" } ]
C library function - acos()
The C library function double acos(double x) returns the arc cosine of x in radians. Following is the declaration for acos() function. double acos(double x) x − This is the floating point value in the interval [-1,+1]. x − This is the floating point value in the interval [-1,+1]. This function returns principal arc cosine of x, in the interval [0, pi] radians. The following example shows the usage of acos() function. #include <stdio.h> #include <math.h> #define PI 3.14159265 int main () { double x, ret, val; x = 0.9; val = 180.0 / PI; ret = acos(x) * val; printf("The arc cosine of %lf is %lf degrees", x, ret); return(0); } Let us compile and run the above program that will produce the following result − The arc cosine of 0.900000 is 25.855040 degrees 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2092, "s": 2007, "text": "The C library function double acos(double x) returns the arc cosine of x in radians." }, { "code": null, "e": 2142, "s": 2092, "text": "Following is the declaration for acos() function." }, { "code": null, "e": 2164, "s": 2142, "text": "double acos(double x)" }, { "code": null, "e": 2226, "s": 2164, "text": "x − This is the floating point value in the interval [-1,+1]." }, { "code": null, "e": 2288, "s": 2226, "text": "x − This is the floating point value in the interval [-1,+1]." }, { "code": null, "e": 2370, "s": 2288, "text": "This function returns principal arc cosine of x, in the interval [0, pi] radians." }, { "code": null, "e": 2428, "s": 2370, "text": "The following example shows the usage of acos() function." }, { "code": null, "e": 2664, "s": 2428, "text": "#include <stdio.h>\n#include <math.h>\n\n#define PI 3.14159265\n\nint main () {\n double x, ret, val;\n\n x = 0.9;\n val = 180.0 / PI;\n\n ret = acos(x) * val;\n printf(\"The arc cosine of %lf is %lf degrees\", x, ret);\n \n return(0);\n}" }, { "code": null, "e": 2746, "s": 2664, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2795, "s": 2746, "text": "The arc cosine of 0.900000 is 25.855040 degrees\n" }, { "code": null, "e": 2828, "s": 2795, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2843, "s": 2828, "text": " Nishant Malik" }, { "code": null, "e": 2878, "s": 2843, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2893, "s": 2878, "text": " Nishant Malik" }, { "code": null, "e": 2928, "s": 2893, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2942, "s": 2928, "text": " Asif Hussain" }, { "code": null, "e": 2975, "s": 2942, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2993, "s": 2975, "text": " Richa Maheshwari" }, { "code": null, "e": 3028, "s": 2993, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3047, "s": 3028, "text": " Vandana Annavaram" }, { "code": null, "e": 3080, "s": 3047, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3092, "s": 3080, "text": " Amit Diwan" }, { "code": null, "e": 3099, "s": 3092, "text": " Print" }, { "code": null, "e": 3110, "s": 3099, "text": " Add Notes" } ]
Segment Tree | Set 1 (Sum of given range) - GeeksforGeeks
20 Aug, 2021 Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the sum of elements from index l to r where 0 <= l <= r <= n-12 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. A simple solution is to run a loop from l to r and calculate the sum of elements in the given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. Another solution is to create another array and store sum from start to i at the ith index in this array. The sum of a given range can now be calculated in O(1) time, but update operation takes O(n) time now. This works well if the number of query operations is large and very few updates.What if the number of query and updates are equal? Can we perform both the operations in O(log n) time once given the array? We can use a Segment Tree to do both operations in O(Logn) time. Representation of Segment trees 1. Leaf Nodes are the elements of the input array. 2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is sum of leaves under a node.An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at ⌊(i – 1) / 2⌋. How does above segment tree look in memory? Like Heap, the segment tree is also represented as an array. The difference here is, it is not a complete binary tree. It is rather a full binary tree (every node has 0 or 2 children) and all levels are filled except possibly the last level. Unlike Heap, the last level may have gaps between nodes. Below are the values in the segment tree array for the above diagram. Below is memory representation of segment tree for input array {1, 3, 5, 7, 9, 11} st[] = {36, 9, 27, 4, 5, 16, 11, 1, 3, DUMMY, DUMMY, 7, 9, DUMMY, DUMMY} The dummy values are never accessed and have no use. This is some wastage of space due to simple array representation. We may optimize this wastage using some clever implementations, but code for sum and update becomes more complex. Construction of Segment Tree from given array We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the sum in the corresponding node. All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because we always divide segments in two halves at every level. Since the constructed tree is always a full binary tree with n leaves, there will be n-1 internal nodes. So the total number of nodes will be 2*n – 1. Note that this does not include dummy nodes. What is the total size of the array representing segment tree? If n is a power of 2, then there are no dummy nodes. So the size of the segment tree is 2n-1 (n leaf nodes and n-1 internal nodes). If n is not a power of 2, then the size of the tree will be 2*x – 1 where x is the smallest power of 2 greater than n. For example, when n = 10, then size of array representing segment tree is 2*16-1 = 31. An alternate explanation for size is based on heignt. Height of the segment tree will be ⌈log2n⌉. Since the tree is represented using array and relation between parent and child indexes must be maintained, size of memory allocated for segment tree will be 2 * 2⌈log2n⌉ – 1. Query for Sum of given range Once the tree is constructed, how to get the sum using the constructed segment tree. The following is the algorithm to get the sum of elements. int getSum(node, l, r) { if the range of the node is within l and r return value in the node else if the range of the node is completely outside l and r return 0 else return getSum(node's left child, l, r) + getSum(node's right child, l, r) } Update a value Like tree construction and query operations, the update can also be done recursively. We are given an index which needs to be updated. Let diff be the value to be added. We start from the root of the segment tree and add diff to all nodes which have given index in their range. If a node doesn’t have a given index in its range, we don’t make any changes to that node. Implementation: Following is the implementation of segment tree. The program implements construction of segment tree for any given array. It also implements query and update operations. C++ C Java Python3 C# Javascript // C++ program to show segment tree operations like construction, query// and update#include <bits/stdc++.h>using namespace std; // 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 sum of values in the given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int *st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + getSumUtil(st, mid+1, se, qs, qe, 2*si+2);} /* A recursive function to update the nodes which have the givenindex in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in the input array.diff --> Value to be added to all nodes which have i in range */void updateValueUtil(int *st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int *st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n-1) { cout<<"Invalid Input"; return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0);} // Return sum of elements in range from index qs (query start)// to qe (query end). It mainly uses getSumUtil()int getSum(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 getSumUtil(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 stint constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, mid+1, se, st, si*2+2); return st[si];} /* Function to construct segment tree from given array. This functionallocates memory for segment tree and calls constructSTUtil() tofill the allocated memory */int *constructST(int arr[], int n){ // Allocate memory for the segment tree //Height of segment tree int x = (int)(ceil(log2(n))); //Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; // Allocate memory int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 cout<<"Sum of values in given range = "<<getSum(st, n, 1, 3)<<endl; // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated cout<<"Updated sum of values in given range = " <<getSum(st, n, 1, 3)<<endl; return 0;}//This code is contributed by rathbhupendra // C program to show segment tree operations like construction, query// and update#include <stdio.h>#include <math.h> // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int *st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + getSumUtil(st, mid+1, se, qs, qe, 2*si+2);} /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in the input array. diff --> Value to be added to all nodes which have i in range */void updateValueUtil(int *st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int *st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n-1) { printf("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0);} // Return sum of elements in range from index qs (query start)// to qe (query end). It mainly uses getSumUtil()int getSum(int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return getSumUtil(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 stint constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, 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 arr[], int n){ // Allocate memory for the segment tree //Height of segment tree int x = (int)(ceil(log2(n))); //Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; // Allocate memory int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 printf("Sum of values in given range = %dn", getSum(st, n, 1, 3)); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated printf("Updated sum of values in given range = %dn", getSum(st, n, 1, 3)); return 0;} // Java Program to show segment tree operations like construction,// query and updateclass SegmentTree{ int st[]; // The array that stores segment tree nodes /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ SegmentTree(int arr[], int n) { // Allocate memory for segment tree //Height of segment tree int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); //Maximum size of segment tree int max_size = 2 * (int) Math.pow(2, x) - 1; st = new int[max_size]; // Memory allocation constructSTUtil(arr, 0, n - 1, 0); } // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int ss, int se, int i, int diff, int si) { // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update the // value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(int arr[], int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { System.out.println("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range from index qs (query start) to // qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(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 int constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; SegmentTree tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3)); // Update: set arr[1] = 10 and update corresponding segment // tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated System.out.println("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); }}//This code is contributed by Ankur Narain Verma # Python3 program to show segment tree operations like# construction, query and updatefrom math import ceil, log2; # 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 sum of values in the given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range """def getSumUtil(st, ss, se, qs, qe, si) : # If segment of this node is a part of given range, # then return the sum of the segment if (qs <= ss and qe >= se) : return st[si]; # If segment of this node is # outside the given range if (se < qs or ss > qe) : return 0; # If a part of this segment overlaps # with the given range mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2 * si + 1) + getSumUtil(st, mid + 1, se, qs, qe, 2 * si + 2); """ A recursive function to update the nodeswhich have the given index in their range.The following are parameters st, si, ss and seare same as getSumUtil()i --> index of the element to be updated. This index is in the input array.diff --> Value to be added to all nodeswhich have i in range """def updateValueUtil(st, ss, se, i, diff, si) : # Base Case: If the input index lies # outside the range of this segment if (i < ss or i > se) : return; # If the input index is in range of this node, # then update the value of the node and its children st[si] = st[si] + diff; if (se != ss) : mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); # The function to update a value in input array# and segment tree. It uses updateValueUtil()# to update the value in segment treedef updateValue(arr, st, n, i, new_val) : # Check for erroneous input index if (i < 0 or i > n - 1) : print("Invalid Input", end = ""); return; # Get the difference between # new value and old value diff = new_val - arr[i]; # Update the value in array arr[i] = new_val; # Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0); # Return sum of elements in range from# index qs (query start) to qe (query end).# It mainly uses getSumUtil()def getSum(st, n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print("Invalid Input", end = ""); return -1; return getSumUtil(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 stdef constructSTUtil(arr, 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] = arr[ss]; return arr[ss]; # If there are more than one elements, # then recur for left and right subtrees # and store the sum of values in this node mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2); return st[si]; """ Function to construct segment treefrom given array. This function allocates memoryfor segment tree and calls constructSTUtil() tofill the allocated memory """def constructST(arr, n) : # Allocate memory for the segment tree # Height of segment tree x = (int)(ceil(log2(n))); # Maximum size of segment tree max_size = 2 * (int)(2**x) - 1; # Allocate memory st = [0] * max_size; # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); # Return the constructed segment tree return st; # Driver Codeif __name__ == "__main__" : arr = [1, 3, 5, 7, 9, 11]; n = len(arr); # Build segment tree from given array st = constructST(arr, n); # Print sum of values in array from index 1 to 3 print("Sum of values in given range = ", getSum(st, n, 1, 3)); # Update: set arr[1] = 10 and update # corresponding segment tree nodes updateValue(arr, st, n, 1, 10); # Find sum after the value is updated print("Updated sum of values in given range = ", getSum(st, n, 1, 3), end = ""); # This code is contributed by AnkitRai01 // C# Program to show segment tree// operations like construction,// query and updateusing System; class SegmentTree{ int []st; // The array that stores segment tree nodes /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ SegmentTree(int []arr, int n) { // Allocate memory for segment tree //Height of segment tree int x = (int) (Math.Ceiling(Math.Log(n) / Math.Log(2))); //Maximum size of segment tree int max_size = 2 * (int) Math.Pow(2, x) - 1; st = new int[max_size]; // Memory allocation constructSTUtil(arr, 0, n - 1, 0); } // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If segment of this node is a part // of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is // outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int ss, int se, int i, int diff, int si) { // Base Case: If the input index // lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of // this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value // in input array and segment tree. // It uses updateValueUtil() to // update the value in segment tree void updateValue(int []arr, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { Console.WriteLine("Invalid Input"); return; } // Get the difference between // new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range // from index qs (query start) to // qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine("Invalid Input"); return -1; } return getSumUtil(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 int constructSTUtil(int []arr, 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } // Driver code public static void Main() { int []arr = {1, 3, 5, 7, 9, 11}; int n = arr.Length; SegmentTree tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 Console.WriteLine("Sum of values in given range = " + tree.getSum(n, 1, 3)); // Update: set arr[1] = 10 and update // corresponding segment tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated Console.WriteLine("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript Program to show segment tree // operations like construction, // query and update class SegmentTree { /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ constructor(arr, n) { // Allocate memory for segment tree // Height of segment tree var x = parseInt(Math.ceil(Math.log(n) / Math.log(2))); //Maximum size of segment tree var max_size = 2 * parseInt(Math.pow(2, x) - 1); this.st = new Array(max_size).fill(0); // Memory allocation this.constructSTUtil(arr, 0, n - 1, 0); } // A utility function to get the // middle index from corner indexes. getMid(s, e) { return parseInt(s + (e - s) / 2); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ getSumUtil(ss, se, qs, qe, si) { // If segment of this node is a part // of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return this.st[si]; // If segment of this node is // outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range var mid = this.getMid(ss, se); return ( this.getSumUtil(ss, mid, qs, qe, 2 * si + 1) + this.getSumUtil(mid + 1, se, qs, qe, 2 * si + 2) ); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ updateValueUtil(ss, se, i, diff, si) { // Base Case: If the input index // lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of // this node, then update the value // of the node and its children this.st[si] = this.st[si] + diff; if (se != ss) { var mid = this.getMid(ss, se); this.updateValueUtil(ss, mid, i, diff, 2 * si + 1); this.updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value // in input array and segment tree. // It uses updateValueUtil() to // update the value in segment tree updateValue(arr, n, i, new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { document.write("Invalid Input"); return; } // Get the difference between // new value and old value var diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree this.updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range // from index qs (query start) to // qe (query end). It mainly uses getSumUtil() getSum(n, qs, qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write("Invalid Input"); return -1; } return this.getSumUtil(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 constructSTUtil(arr, ss, se, si) { // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) { this.st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of values in this node var mid = this.getMid(ss, se); this.st[si] = this.constructSTUtil(arr, ss, mid, si * 2 + 1) + this.constructSTUtil(arr, mid + 1, se, si * 2 + 2); return this.st[si]; } } // Driver code var arr = [1, 3, 5, 7, 9, 11]; var n = arr.length; var tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 document.write( "Sum of values in given range = " + tree.getSum(n, 1, 3) + "<br>" ); // Update: set arr[1] = 10 and update // corresponding segment tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated document.write( "Updated sum of values in given range = " + tree.getSum(n, 1, 3) + "<br>" ); </script> Output: Sum of values in given range = 15 Updated sum of values in given range = 22 Time Complexity: Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.Time complexity to query is O(Logn). To query a sum, we process at most four nodes at every level and number of levels is O(Logn). The time complexity of update is also O(Logn). To update a leaf value, we process one node at every level and number of levels is O(Logn).Segment Tree | Set 2 (Range Minimum Query) YouTubeGeeksforGeeks501K subscribersSum of given range | Segment Tree | Set 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0l3xN3BpxHg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: IIT Kanpur paper. princiraj1992 rathbhupendra AjayN ankthon jairbohara999 rishabhvarshney14 rdtank surinderdawra388 Amazon array-range-queries Segment-Tree Advanced Data Structure Arrays Mathematical Tree Amazon Arrays Mathematical Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Disjoint Set Data Structures Red-Black Tree | Set 2 (Insert) AVL Tree | Set 2 (Deletion) Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 24748, "s": 24720, "text": "\n20 Aug, 2021" }, { "code": null, "e": 25054, "s": 24748, "text": "Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the sum of elements from index l to r where 0 <= l <= r <= n-12 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1." }, { "code": null, "e": 25275, "s": 25054, "text": "A simple solution is to run a loop from l to r and calculate the sum of elements in the given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. " }, { "code": null, "e": 25754, "s": 25275, "text": "Another solution is to create another array and store sum from start to i at the ith index in this array. The sum of a given range can now be calculated in O(1) time, but update operation takes O(n) time now. This works well if the number of query operations is large and very few updates.What if the number of query and updates are equal? Can we perform both the operations in O(log n) time once given the array? We can use a Segment Tree to do both operations in O(Logn) time." }, { "code": null, "e": 26198, "s": 25754, "text": "Representation of Segment trees 1. Leaf Nodes are the elements of the input array. 2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is sum of leaves under a node.An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at ⌊(i – 1) / 2⌋. " }, { "code": null, "e": 26612, "s": 26198, "text": "How does above segment tree look in memory? Like Heap, the segment tree is also represented as an array. The difference here is, it is not a complete binary tree. It is rather a full binary tree (every node has 0 or 2 children) and all levels are filled except possibly the last level. Unlike Heap, the last level may have gaps between nodes. Below are the values in the segment tree array for the above diagram. " }, { "code": null, "e": 26768, "s": 26612, "text": "Below is memory representation of segment tree for input array {1, 3, 5, 7, 9, 11} st[] = {36, 9, 27, 4, 5, 16, 11, 1, 3, DUMMY, DUMMY, 7, 9, DUMMY, DUMMY}" }, { "code": null, "e": 27001, "s": 26768, "text": "The dummy values are never accessed and have no use. This is some wastage of space due to simple array representation. We may optimize this wastage using some clever implementations, but code for sum and update becomes more complex." }, { "code": null, "e": 27713, "s": 27001, "text": "Construction of Segment Tree from given array We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the sum in the corresponding node. All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because we always divide segments in two halves at every level. Since the constructed tree is always a full binary tree with n leaves, there will be n-1 internal nodes. So the total number of nodes will be 2*n – 1. Note that this does not include dummy nodes." }, { "code": null, "e": 28389, "s": 27713, "text": "What is the total size of the array representing segment tree? If n is a power of 2, then there are no dummy nodes. So the size of the segment tree is 2n-1 (n leaf nodes and n-1 internal nodes). If n is not a power of 2, then the size of the tree will be 2*x – 1 where x is the smallest power of 2 greater than n. For example, when n = 10, then size of array representing segment tree is 2*16-1 = 31. An alternate explanation for size is based on heignt. Height of the segment tree will be ⌈log2n⌉. Since the tree is represented using array and relation between parent and child indexes must be maintained, size of memory allocated for segment tree will be 2 * 2⌈log2n⌉ – 1." }, { "code": null, "e": 28564, "s": 28389, "text": "Query for Sum of given range Once the tree is constructed, how to get the sum using the constructed segment tree. The following is the algorithm to get the sum of elements. " }, { "code": null, "e": 28849, "s": 28564, "text": "int getSum(node, l, r) \n{\n if the range of the node is within l and r\n return value in the node\n else if the range of the node is completely outside l and r\n return 0\n else\n return getSum(node's left child, l, r) + \n getSum(node's right child, l, r)\n}" }, { "code": null, "e": 29233, "s": 28849, "text": "Update a value Like tree construction and query operations, the update can also be done recursively. We are given an index which needs to be updated. Let diff be the value to be added. We start from the root of the segment tree and add diff to all nodes which have given index in their range. If a node doesn’t have a given index in its range, we don’t make any changes to that node." }, { "code": null, "e": 29421, "s": 29233, "text": "Implementation: Following is the implementation of segment tree. The program implements construction of segment tree for any given array. It also implements query and update operations. " }, { "code": null, "e": 29425, "s": 29421, "text": "C++" }, { "code": null, "e": 29427, "s": 29425, "text": "C" }, { "code": null, "e": 29432, "s": 29427, "text": "Java" }, { "code": null, "e": 29440, "s": 29432, "text": "Python3" }, { "code": null, "e": 29443, "s": 29440, "text": "C#" }, { "code": null, "e": 29454, "s": 29443, "text": "Javascript" }, { "code": "// C++ program to show segment tree operations like construction, query// and update#include <bits/stdc++.h>using namespace std; // 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 sum of values in the given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int *st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + getSumUtil(st, mid+1, se, qs, qe, 2*si+2);} /* A recursive function to update the nodes which have the givenindex in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in the input array.diff --> Value to be added to all nodes which have i in range */void updateValueUtil(int *st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int *st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n-1) { cout<<\"Invalid Input\"; return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0);} // Return sum of elements in range from index qs (query start)// to qe (query end). It mainly uses getSumUtil()int getSum(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 getSumUtil(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 stint constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, mid+1, se, st, si*2+2); return st[si];} /* Function to construct segment tree from given array. This functionallocates memory for segment tree and calls constructSTUtil() tofill the allocated memory */int *constructST(int arr[], int n){ // Allocate memory for the segment tree //Height of segment tree int x = (int)(ceil(log2(n))); //Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; // Allocate memory int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 cout<<\"Sum of values in given range = \"<<getSum(st, n, 1, 3)<<endl; // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated cout<<\"Updated sum of values in given range = \" <<getSum(st, n, 1, 3)<<endl; return 0;}//This code is contributed by rathbhupendra", "e": 34225, "s": 29454, "text": null }, { "code": "// C program to show segment tree operations like construction, query// and update#include <stdio.h>#include <math.h> // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */int getSumUtil(int *st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + getSumUtil(st, mid+1, se, qs, qe, 2*si+2);} /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in the input array. diff --> Value to be added to all nodes which have i in range */void updateValueUtil(int *st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int *st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n-1) { printf(\"Invalid Input\"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0);} // Return sum of elements in range from index qs (query start)// to qe (query end). It mainly uses getSumUtil()int getSum(int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf(\"Invalid Input\"); return -1; } return getSumUtil(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 stint constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, 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 arr[], int n){ // Allocate memory for the segment tree //Height of segment tree int x = (int)(ceil(log2(n))); //Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; // Allocate memory int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 printf(\"Sum of values in given range = %dn\", getSum(st, n, 1, 3)); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated printf(\"Updated sum of values in given range = %dn\", getSum(st, n, 1, 3)); return 0;}", "e": 38988, "s": 34225, "text": null }, { "code": "// Java Program to show segment tree operations like construction,// query and updateclass SegmentTree{ int st[]; // The array that stores segment tree nodes /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ SegmentTree(int arr[], int n) { // Allocate memory for segment tree //Height of segment tree int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); //Maximum size of segment tree int max_size = 2 * (int) Math.pow(2, x) - 1; st = new int[max_size]; // Memory allocation constructSTUtil(arr, 0, n - 1, 0); } // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int ss, int se, int i, int diff, int si) { // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update the // value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(int arr[], int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { System.out.println(\"Invalid Input\"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range from index qs (query start) to // qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println(\"Invalid Input\"); return -1; } return getSumUtil(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 int constructSTUtil(int arr[], 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; SegmentTree tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 System.out.println(\"Sum of values in given range = \" + tree.getSum(n, 1, 3)); // Update: set arr[1] = 10 and update corresponding segment // tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated System.out.println(\"Updated sum of values in given range = \" + tree.getSum(n, 1, 3)); }}//This code is contributed by Ankur Narain Verma", "e": 44257, "s": 38988, "text": null }, { "code": "# Python3 program to show segment tree operations like# construction, query and updatefrom math import ceil, log2; # 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 sum of values in the given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range \"\"\"def getSumUtil(st, ss, se, qs, qe, si) : # If segment of this node is a part of given range, # then return the sum of the segment if (qs <= ss and qe >= se) : return st[si]; # If segment of this node is # outside the given range if (se < qs or ss > qe) : return 0; # If a part of this segment overlaps # with the given range mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2 * si + 1) + getSumUtil(st, mid + 1, se, qs, qe, 2 * si + 2); \"\"\" A recursive function to update the nodeswhich have the given index in their range.The following are parameters st, si, ss and seare same as getSumUtil()i --> index of the element to be updated. This index is in the input array.diff --> Value to be added to all nodeswhich have i in range \"\"\"def updateValueUtil(st, ss, se, i, diff, si) : # Base Case: If the input index lies # outside the range of this segment if (i < ss or i > se) : return; # If the input index is in range of this node, # then update the value of the node and its children st[si] = st[si] + diff; if (se != ss) : mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); # The function to update a value in input array# and segment tree. It uses updateValueUtil()# to update the value in segment treedef updateValue(arr, st, n, i, new_val) : # Check for erroneous input index if (i < 0 or i > n - 1) : print(\"Invalid Input\", end = \"\"); return; # Get the difference between # new value and old value diff = new_val - arr[i]; # Update the value in array arr[i] = new_val; # Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0); # Return sum of elements in range from# index qs (query start) to qe (query end).# It mainly uses getSumUtil()def getSum(st, n, qs, qe) : # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe) : print(\"Invalid Input\", end = \"\"); return -1; return getSumUtil(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 stdef constructSTUtil(arr, 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] = arr[ss]; return arr[ss]; # If there are more than one elements, # then recur for left and right subtrees # and store the sum of values in this node mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2); return st[si]; \"\"\" Function to construct segment treefrom given array. This function allocates memoryfor segment tree and calls constructSTUtil() tofill the allocated memory \"\"\"def constructST(arr, n) : # Allocate memory for the segment tree # Height of segment tree x = (int)(ceil(log2(n))); # Maximum size of segment tree max_size = 2 * (int)(2**x) - 1; # Allocate memory st = [0] * max_size; # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); # Return the constructed segment tree return st; # Driver Codeif __name__ == \"__main__\" : arr = [1, 3, 5, 7, 9, 11]; n = len(arr); # Build segment tree from given array st = constructST(arr, n); # Print sum of values in array from index 1 to 3 print(\"Sum of values in given range = \", getSum(st, n, 1, 3)); # Update: set arr[1] = 10 and update # corresponding segment tree nodes updateValue(arr, st, n, 1, 10); # Find sum after the value is updated print(\"Updated sum of values in given range = \", getSum(st, n, 1, 3), end = \"\"); # This code is contributed by AnkitRai01", "e": 48954, "s": 44257, "text": null }, { "code": "// C# Program to show segment tree// operations like construction,// query and updateusing System; class SegmentTree{ int []st; // The array that stores segment tree nodes /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ SegmentTree(int []arr, int n) { // Allocate memory for segment tree //Height of segment tree int x = (int) (Math.Ceiling(Math.Log(n) / Math.Log(2))); //Maximum size of segment tree int max_size = 2 * (int) Math.Pow(2, x) - 1; st = new int[max_size]; // Memory allocation constructSTUtil(arr, 0, n - 1, 0); } // 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 sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int ss, int se, int qs, int qe, int si) { // If segment of this node is a part // of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is // outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int ss, int se, int i, int diff, int si) { // Base Case: If the input index // lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of // this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value // in input array and segment tree. // It uses updateValueUtil() to // update the value in segment tree void updateValue(int []arr, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { Console.WriteLine(\"Invalid Input\"); return; } // Get the difference between // new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range // from index qs (query start) to // qe (query end). It mainly uses getSumUtil() int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine(\"Invalid Input\"); return -1; } return getSumUtil(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 int constructSTUtil(int []arr, 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) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } // Driver code public static void Main() { int []arr = {1, 3, 5, 7, 9, 11}; int n = arr.Length; SegmentTree tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 Console.WriteLine(\"Sum of values in given range = \" + tree.getSum(n, 1, 3)); // Update: set arr[1] = 10 and update // corresponding segment tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated Console.WriteLine(\"Updated sum of values in given range = \" + tree.getSum(n, 1, 3)); }} /* This code contributed by PrinciRaj1992 */", "e": 54376, "s": 48954, "text": null }, { "code": "<script> // JavaScript Program to show segment tree // operations like construction, // query and update class SegmentTree { /* Constructor to construct segment tree from given array. This constructor allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ constructor(arr, n) { // Allocate memory for segment tree // Height of segment tree var x = parseInt(Math.ceil(Math.log(n) / Math.log(2))); //Maximum size of segment tree var max_size = 2 * parseInt(Math.pow(2, x) - 1); this.st = new Array(max_size).fill(0); // Memory allocation this.constructSTUtil(arr, 0, n - 1, 0); } // A utility function to get the // middle index from corner indexes. getMid(s, e) { return parseInt(s + (e - s) / 2); } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> 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[si] qs & qe --> Starting and ending indexes of query range */ getSumUtil(ss, se, qs, qe, si) { // If segment of this node is a part // of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return this.st[si]; // If segment of this node is // outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range var mid = this.getMid(ss, se); return ( this.getSumUtil(ss, mid, qs, qe, 2 * si + 1) + this.getSumUtil(mid + 1, se, qs, qe, 2 * si + 2) ); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ updateValueUtil(ss, se, i, diff, si) { // Base Case: If the input index // lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of // this node, then update the value // of the node and its children this.st[si] = this.st[si] + diff; if (se != ss) { var mid = this.getMid(ss, se); this.updateValueUtil(ss, mid, i, diff, 2 * si + 1); this.updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value // in input array and segment tree. // It uses updateValueUtil() to // update the value in segment tree updateValue(arr, n, i, new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { document.write(\"Invalid Input\"); return; } // Get the difference between // new value and old value var diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree this.updateValueUtil(0, n - 1, i, diff, 0); } // Return sum of elements in range // from index qs (query start) to // qe (query end). It mainly uses getSumUtil() getSum(n, qs, qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write(\"Invalid Input\"); return -1; } return this.getSumUtil(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 constructSTUtil(arr, ss, se, si) { // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) { this.st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of values in this node var mid = this.getMid(ss, se); this.st[si] = this.constructSTUtil(arr, ss, mid, si * 2 + 1) + this.constructSTUtil(arr, mid + 1, se, si * 2 + 2); return this.st[si]; } } // Driver code var arr = [1, 3, 5, 7, 9, 11]; var n = arr.length; var tree = new SegmentTree(arr, n); // Build segment tree from given array // Print sum of values in array from index 1 to 3 document.write( \"Sum of values in given range = \" + tree.getSum(n, 1, 3) + \"<br>\" ); // Update: set arr[1] = 10 and update // corresponding segment tree nodes tree.updateValue(arr, n, 1, 10); // Find sum after the value is updated document.write( \"Updated sum of values in given range = \" + tree.getSum(n, 1, 3) + \"<br>\" ); </script>", "e": 59936, "s": 54376, "text": null }, { "code": null, "e": 59945, "s": 59936, "text": "Output: " }, { "code": null, "e": 60021, "s": 59945, "text": "Sum of values in given range = 15\nUpdated sum of values in given range = 22" }, { "code": null, "e": 60494, "s": 60021, "text": "Time Complexity: Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.Time complexity to query is O(Logn). To query a sum, we process at most four nodes at every level and number of levels is O(Logn). The time complexity of update is also O(Logn). To update a leaf value, we process one node at every level and number of levels is O(Logn).Segment Tree | Set 2 (Range Minimum Query)" }, { "code": null, "e": 61334, "s": 60494, "text": "YouTubeGeeksforGeeks501K subscribersSum of given range | Segment Tree | Set 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0l3xN3BpxHg\" 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": 61365, "s": 61334, "text": "References: IIT Kanpur paper. " }, { "code": null, "e": 61379, "s": 61365, "text": "princiraj1992" }, { "code": null, "e": 61393, "s": 61379, "text": "rathbhupendra" }, { "code": null, "e": 61399, "s": 61393, "text": "AjayN" }, { "code": null, "e": 61407, "s": 61399, "text": "ankthon" }, { "code": null, "e": 61421, "s": 61407, "text": "jairbohara999" }, { "code": null, "e": 61439, "s": 61421, "text": "rishabhvarshney14" }, { "code": null, "e": 61446, "s": 61439, "text": "rdtank" }, { "code": null, "e": 61463, "s": 61446, "text": "surinderdawra388" }, { "code": null, "e": 61470, "s": 61463, "text": "Amazon" }, { "code": null, "e": 61490, "s": 61470, "text": "array-range-queries" }, { "code": null, "e": 61503, "s": 61490, "text": "Segment-Tree" }, { "code": null, "e": 61527, "s": 61503, "text": "Advanced Data Structure" }, { "code": null, "e": 61534, "s": 61527, "text": "Arrays" }, { "code": null, "e": 61547, "s": 61534, "text": "Mathematical" }, { "code": null, "e": 61552, "s": 61547, "text": "Tree" }, { "code": null, "e": 61559, "s": 61552, "text": "Amazon" }, { "code": null, "e": 61566, "s": 61559, "text": "Arrays" }, { "code": null, "e": 61579, "s": 61566, "text": "Mathematical" }, { "code": null, "e": 61584, "s": 61579, "text": "Tree" }, { "code": null, "e": 61597, "s": 61584, "text": "Segment-Tree" }, { "code": null, "e": 61695, "s": 61597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 61729, "s": 61695, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 61769, "s": 61729, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 61798, "s": 61769, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 61830, "s": 61798, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 61858, "s": 61830, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 61873, "s": 61858, "text": "Arrays in Java" }, { "code": null, "e": 61889, "s": 61873, "text": "Arrays in C/C++" }, { "code": null, "e": 61916, "s": 61889, "text": "Program for array rotation" }, { "code": null, "e": 61964, "s": 61916, "text": "Stack Data Structure (Introduction and Program)" } ]
tsfresh on Large Data Samples — Part II | by Nils Braun | Towards Data Science
In the last post, we have explored how tsfresh automatically extracts many time-series features from your input data. We have also discussed two possibilities to speed up your feature extraction calculation: using multiple cores on your local machine (which is already turned on by default) or distributing the calculation over a cluster of machines. In this post we will go one step further: what happens if your data is so large that loading the data into your scheduling machine is not an option anymore? For many applications, this is not the case (and keeping everything local speeds up the development cycle as well as decreased the number of possible mistakes). However, sometimes you really need to think big. There exist multiple solutions to solve the problem of distributing not only the work but also the data — actually the whole field of big data and data engineering builds around that. The general idea is to only load a fraction of the data into each machine and perform the calculation on this partition of the data — instead of loading all the data at the same time. The inputs and results are distributed either via network transmissions or via a distributed file system, such as HDFS. Two of the best-known examples for this (at least in the Python world) are Apache Spark (with its python bindings PySpark) and dask. We will not cover the basics of Apache Spark nor dask here - they are both wonderful libraries and if you never used them you should definitely check them out! If you do not want to use any of those frameworks, but you still have too much data to handle, have a look into the next section where we will discuss a simplified (but also less powerful) solution. Since version 0.15, tsfresh contains convenience functions to input a Spark data frame or a dask data frame into tsfresh (remember: normally you can only use pandas data frames). They are both defined in the tsfresh.convenience.bindings module (with documentation here) and we will cover them in the remainder of this section. The idea is as follows: You take care of converting the data into the correct format for tsfresh (see below, what this means). For pandas data frames this is something we can do on our side. But for those distributed systems, so much careful craftsmanship goes into transforming the data - we can not handle this in a general way. You use one of the bindings mentioned above, to add the tsfresh feature extraction to the data pipeline. Both the input as well as the output of these functions are dask or PySpark data frames. Internally, tsfresh will convert each chunk of your data to a pandas data frame and use the normal feature extraction procedure. Afterward, the result is converted back - so you will not notice this. You continue working with this data frame, e.g. store it as a file or execute additional data transformations. As an example, we will again use the robot failure data sample from our Quickstart. Even though it is still small enough to fit into your memory, we will treat it as “big data” and spill it out to multiple parquet files on disk. Make sure to have a pandas parquet binding installed for this (such as pyarrow, see installation instructions) or use a different format. from tsfresh.examples import robot_execution_failuresimport osrobot_execution_failures.download_robot_execution_failures()timeseries, _ = robot_execution_failures.load_robot_execution_failures()def store_data(data_chunk): data_id = data_chunk["id"].iloc[0] os.makedirs(f"data/{data_id}", exist_ok=True) data_chunk.to_parquet(f"data/{data_id}/data.parquet", index=False)timeseries.groupby("id").apply(store_data) Let's start with Apache Spark first. Apache Spark is basically the framework for writing and distributing fault-tolerant data pipelines. Even though it is written in Java (and Scala), it has very good and well-documented Python bindings called pyspark. After having installed Apache Spark (see here), you need to create a Spark cluster for distributing the work. As usual, there exist many ways for this (see here for a start), but as an example, we will just use the standalone cluster, which is started when you do not specify differently (also called “local” mode). We will demonstrate the calculation in the following with a pyspark interactive console, but you can of course also write it into a python script and submit it via spark-submit (check out the documentation). Important: Spark leverages the arrow bindings for efficient transformation between pandas and Spark data frames. Therefore, you need to have arrow installed. In a recent arrow version, the internal data format has changed and is now incompatible with Spark. For it to still work, you need to add the line ARROW_PRE_0_15_IPC_FORMAT=1 to your Spark environment settings file $SPARK_HOME/conf/spark-env.sh as stated in the documentation. Now let’s create a data pipeline! We will use Spark’s structured declarative data frame API in the following. Remember that Spark will only build up the computation DAG until you trigger an action in the end. So first, let's spin up an interactive pyspark shell and read in the parquet files. As we are running in local mode we do not need to make sure that the data is available for all workers (as there is only one local worker). In a productive environment, you would probably use S3 or HDFS or any other shared data storage. $ pyspark>>> df = spark.read \... .parquet("data/*/data.parquet")>>> df.printSchema()root|-- id: integer (nullable = true)|-- time: integer (nullable = true)|-- F_x: integer (nullable = true)|-- F_y: integer (nullable = true)|-- F_z: integer (nullable = true)|-- T_x: integer (nullable = true)|-- T_y: integer (nullable = true)|-- T_z: integer (nullable = true)>>> df.show()+---+----+----+---+-----+----+----+---+| id|time| F_x|F_y| F_z| T_x| T_y|T_z|+---+----+----+---+-----+----+----+---+| 71| 0| -59| 44| -205|-305|-226| 37|| 71| 1| -71| 55| -273|-368|-271| 42|| 71| 2| -75| 58| -305|-403|-294| 48|| 71| 3| -89| 66| -408|-471|-342| 51|| 71| 4| -95| 64| -461|-503|-372| 47|| 71| 5|-100| 67| -524|-545|-400| 51|| 71| 6|-104| 55| -567|-547|-429| 56|... This is the format of the robot data. id is the identifier for each time series, time is the time (sorting) parameter, and the F_* and T_* are the different value series (remember: what we call the kind of the time series). Please note that this data format and the pre-processing we will perform in the following is just an example - your data might look differently and other data transformation steps might be necessary. For example, if your column names are different (e.g. the id column is not called “id”), you will need to edit the steps accordingly. The feature extraction will later run on each of these series separately — so we first need to group it both by the time-series identifier id and the kind. However, the data is not easily groupable by kind (data of the same kind are not separated) - so we first need to reshape the data. This transformation is usually called melting and there exist various ways to do this in PySpark. For example, you could follow one of the answers to this StackOverflow discussion. Just make sure to change the column name identifiers if needed. >>> ... your melt function, e.g. see in the link above>>> df_melted = melt(df, id_vars=["id", "time"],... value_vars=["F_x", "F_y", "F_z", "T_x", "T_y", "T_z"],... var_name="kind", value_name="value")>>> df_melted.printSchema()root|-- id: integer (nullable = true)|-- time: integer (nullable = true)|-- kind: string (nullable = false)|-- value: integer (nullable = true)>>> df_melted.show()+---+----+----+-----+| id|time|kind|value|+---+----+----+-----+| 71| 0| F_x| -59|| 71| 0| F_y| 44|| 71| 0| F_z| -205|| 71| 0| T_x| -305|| 71| 0| T_y| -226|| 71| 0| T_z| 37|| 71| 1| F_x| -71|| 71| 1| F_y| 55|| 71| 1| F_z| -273|| 71| 1| T_x| -368|| 71| 1| T_y| -271|| 71| 1| T_z| 42|... After melting, the resulting data frame is a concatenated set of each kind of the time-series, while keeping the id and time columns. When we now group by id and kind >>> df_grouped = df_melted.groupby(["id", "kind"]) each grouped chunk of data only contains the data of one kind and one id. We are now ready to use tsfresh! The preprocessing part might look different for your data sample, but you should always end up with a dataset grouped by id and kind before using tsfresh. With the given column names in the example, the call to tsfresh looks like this: >>> from tsfresh.convenience.bindings import spark_feature_extraction_on_chunk>>> from tsfresh.feature_extraction import ComprehensiveFCParameters>>> features = spark_feature_extraction_on_chunk(df_grouped, ... column_id="id",... column_kind="kind",... column_sort="time",... column_value="value",... default_fc_parameters=ComprehensiveFCParameters()) Please remember that Spark will only trigger the calculation once you call an action, so it is still only building up the calculation DAG. Internally, tsfresh will call the following on each grouped chunk: Transform the chunk to a pandas data frame (which is very efficient due to the usage of arrow). Extract the features using the parameters and settings you gave (check out the documentation for more information on the settings). We are using the full set of feature calculators here just as an example. Then convert back to a format PySpark understands. In the end, it will return a Spark data frame, where each line is the value for a different feature of a different time series id and kind. >>> features.printSchema()root|-- id: long (nullable = true)|-- variable: string (nullable = true)|-- value: double (nullable = true)>>> features.show()+---+--------------------+-------------------+| id| variable| value|+---+--------------------+-------------------+| 12| F_x__sum_values| -6.0|| 12| F_x__median| -1.0|| 12| F_x__mean| -0.4|| 12| F_x__length| 15.0|... Depending on your use case, you might want to bring them into the usual tabular form (but please note that this might imply heavy shuffling and especially some immediate calculations as the column names need to be known): >>> from pyspark.sql import functions as F>>> pivoted_features = features.groupby("id").pivot("variable")>>> feature_table = pivoted_features.agg(F.first("value"))>>> feature_table.printSchema()root|-- id: long (nullable = true)|-- F_x__length: double (nullable = true)|-- F_x__maximum: double (nullable = true)... In any case, you can now apply additional transformations or write out the result of the calculation. As long as you have enough workers, this basically scales infinitely. In principle interacting with tsfresh from dask follows the same principles as with Spark, so lets quickly walk through them: Spin up a dask cluster. There are again multiple ways how to do this depending on your environment. A very good starting point is the dask documentation. If you do not have a cluster to play around, local mode will also work (which means you do not need to setup or import anything). For testing, you can use an interactive python shell or a jupyter notebook. Read in the data sample >>> from dask import dataframe as dd >>> # Make sure to setup your client here if you have a cluster >>> df = dd.read_parquet("data/*/data.parquet") Bring the data into the same format as above, where data with different id and kind can be separated easily. Fortunately, dask has already a melt feature, so you just need to call it: >>> df_melted = df.melt(id_vars=["id", "time"], ... value_vars=["F_x", "F_y", "F_z", "T_x", "T_y", "T_z"], ... var_name="kind", value_name="value") >>> df_melted.columns Index(['id', 'time', 'kind', 'value'], dtype='object') >>> df_melted.head() id time kind value 0 1 0 F_x -1 1 1 1 F_x 0 2 1 2 F_x -1 3 1 3 F_x -1 4 1 4 F_x -1 Now separate the data for different id and kind by grouping >>> df_grouped = df_melted.groupby(["id", "kind"]) The data is in the correct format — we can apply tsfresh! We are again using the full set of feature calculators as an example here, but have a look into the documentation for more information. >>> from tsfresh.convenience.bindings import dask_feature_extraction_on_chunk >>> from tsfresh.feature_extraction.settings import ComprehensiveFCParameters >>> features = dask_feature_extraction_on_chunk(df_grouped, ... column_id="id", ... column_kind="kind", ... column_sort="time", ... column_value="value", ... default_fc_parameters=ComprehensiveFCParameters()) Again, this will internally transform each chunk into a pandas data frame, apply the feature extraction, and transform it back into a dask data frame. The result will be a data frame with one extracted feature for one id and kind per row. >>> features.columns Index(['id', 'variable', 'value'], dtype='object') >>> features.head() id variable value id kind 11 T_x 0 11 T_x__sum_values -49.000000 1 11 T_x__median -5.000000 2 11 T_x__mean -3.266667 3 11 T_x__length 15.000000 4 11 T_x__standard_deviation 3.549022 Continue with your calculation, e.g. transform the results into the usual tabular form (again: this might be computationally very intensive!): >>> features = features.categorize(columns=["variable"]) >>> features = features.reset_index(drop=True) >>> feature_table = features.pivot_table(index="id", ... columns="variable", values="value", ... aggfunc="sum") In case you are wondering: the aggregation function “sum” does not really matter here: there is only ever a single value per feature name and identifier. You might ask yourself what the difference is between using a ClusterDaskDistributor (which distributes to a dask cluster) as described in the last post and this dask binding. The ClusterDaskDistributor allows you to distribute the feature extraction calculation via a dask cluster of workers, while still keeping all the data in a non-distributed pandas data frame format. It is therefore useful if you want to parallelize the calculation, but the amount of data is still small enough for you to handle with pandas (on a single machine). The dask (or PySpark) bindings described here allow you to have a non-pandas input, where the data itself is already distributed. It gives you much more flexibility to add tsfresh into your data pipeline. The data preprocessing depends a lot on the shape of your data and the way shown here is most likely not the most efficient way for you (because it might lead to a lot of shuffling or re-partitioning). Please think about how you can transform your data efficiently into the input format for tsfresh. You have a lot of data which does not fit into memory, but you do not want to add the burden of using a distributed framework (such as dask or PySpark) to your project? Then read on! In the following, we will follow the ideas of a distributed framework such as dask or Apache Spark without actually using one (which of course also has some downsides, see below). The idea is: Remember that we can extract the features for a time series of given id and kind independently from others. This means we can separate each cycle of: 1. read in the data for a specific kind and id, 2. extract the features on this data, 3. write out the data. Now we just need to orchestrate these work tasks. For this part, we will use the powers of luigi, a task orchestrator framework. If you have never used luigi have a look into the documentation for a first overview before you continue. We will also try to walk through the basic ideas in the following. We will also assume that your data is stored to disk (maybe on a distributed storage like HDFS) and already partitioned by id and kind. For example, it might be in the form <path>/<id>/<kind>/input.parquet If you want to generate some test data with the robot dataset, you can use the following python snippet: from tsfresh.examples import robot_execution_failuresimport osrobot_execution_failures.download_robot_execution_failures()timeseries, _ = robot_execution_failures.load_robot_execution_failures()def store_data(data_chunk): data_id = data_chunk["id"].iloc[0] data_kind = data_chunk["kind"].iloc[0] os.makedirs(f"data/{data_id}/{data_kind}", exist_ok=True) data_chunk.to_parquet(f"data/{data_id}/{data_kind}/input.parquet", index=False)timeseries.melt(id_vars=["id", "time"], value_vars=["F_x", "F_y", "F_z", "T_x", "T_y", "T_z"], var_name="kind", value_name="value").groupby(["id", "kind"]).apply(store_data) Please note that the data is basically already melted due to the way it is stored. It is also possible to store the data only separated by id and let tsfresh extract the features for all kinds simultaneously. Feel free to adjust the luigi script below to your needs. The core building block of luigi are tasks. Tasks can have dependencies among each other, they define which output files they create and of course what to do when the task runs. They are controlled by parameters, which can be used to distinguish different instances of the same task. Let’s define a Task for the cycle of reading, extracting, and writing the data as described above. import luigiimport pandas as pdfrom tsfresh import extract_features# Where the input data is stored.DATA_INPUT_NAME = "data/{data_id}/{data_kind}/input.parquet"# Where the output data will be storedDATA_OUTPUT_NAME = "data/{data_id}/{data_kind}/output.parquet"class FeatureExtractorTask(luigi.Task): """ Task to extract the features for one time series of given `id` and `kind`. Reads in the data, extracts the features and stores the data again. """ data_id = luigi.Parameter() data_kind = luigi.Parameter() def output(self): """Define what this task will output""" return luigi.LocalTarget(DATA_OUTPUT_NAME.format(data_id=self.data_id, data_kind=self.data_kind)) def run(self): """Define, what the task will actually do""" # 1. Read in the time series data from disk input_file = DATA_INPUT_NAME.format(data_id=self.data_id, data_kind=self.data_kind) df = pd.read_parquet(input_file) # 2. Extract the features. # Turn of multiprocessing - the parallelism comes with multiple luigi workers. features = extract_features(df, column_id="id", column_kind="kind", column_sort="time", column_value="value", n_jobs=0) # 3. Store the data features.to_parquet(self.output().path) As you can see, the code is quite straightforward. We are again assuming only local setup for this example — in a real-world application the input and output paths will be on a shared file system (NFS, HDFS, S3) so that both the scheduler and the worker can read/write the files. Once we have defined a task for this cycle, we just need to run it. There exist multiple ways to do this — you could use a local scheduler, a central scheduler, or even a batch system (maybe with the help of my package b2luigi ;-)). As an example, we will just define a list of tasks to run and give it to the luigi.build function. Also, we are only using a single worker and a local scheduler. # ... continue from aboveif __name__ == "__main__": task_list = [] for data_kind in ["F_x", "F_y"]: for data_id in range(1, 5): task_list.append(FeatureExtractorTask(data_kind=data_kind, data_id=str(data_id))) luigi.build(task_list, local_scheduler=True) Running this script will give you a happy smiley output and your output data stored in the specified paths. For distributing the work among several machines, start a central scheduler $ luigid And remove the local_scheduler flag. Each call to the luigi script will now start another worker, which will connect to the central scheduler and start processing work (if your code is running on multiple machines, you need to give the scheduler hostname as well). The documentation describes more options. If you want to test it out, make sure to increase the number of ids it needs to process — otherwise, it will run out of work quickly. Using luigi comes with the benefit of a very simple code base and a simplified execution model. But of course, this can not replace a distributed framework such as dask or Apache Spark with all its features: You basically need to implement all the data handling by yourself (e.g. joining) using file operations. If you need this, you should really think about using one of the frameworks. There is a lot of file IO involved (luigi tasks can only communicate via file output). There is no “high-level” API for data pipelines, everything needs to be implemented as single tasks by hand. But following the KISS principle, I would always prefer a small luigi application over running a complex distributed application (and have done so successfully several times in the past). After all these possibilities, the question arises: When should you use what? Let’s try to give some usage hints: Use the simplest possibility that solves your task. If you can effort to read in all the data in memory, stick with pandas and use multiprocessing or a distributor. If you do not need to build a complex data pipeline, but rather only extract the features, think about using luigi (or anything alike, such as Airflow or celery) The same applies to the single or multi-node calculation: fewer machines, fewer problems. Try to stay with single-processing or local calculations as long as possible. If the rest of your data pipeline is already implemented in another framework which is not mentioned here, try to stick with your framework. The code for the bindings is actually quite simple — so you can easily reproduce it in your framework. There is a lot more to discover when it comes to distributed computing or distributed data. If you find out about interesting bindings between your framework and tsfresh or of you developed a cool distributor you want to share, we are already happy for pull requests. Happy coding! Big thanks to @dotcsDE for great suggestions!
[ { "code": null, "e": 522, "s": 171, "text": "In the last post, we have explored how tsfresh automatically extracts many time-series features from your input data. We have also discussed two possibilities to speed up your feature extraction calculation: using multiple cores on your local machine (which is already turned on by default) or distributing the calculation over a cluster of machines." }, { "code": null, "e": 889, "s": 522, "text": "In this post we will go one step further: what happens if your data is so large that loading the data into your scheduling machine is not an option anymore? For many applications, this is not the case (and keeping everything local speeds up the development cycle as well as decreased the number of possible mistakes). However, sometimes you really need to think big." }, { "code": null, "e": 1377, "s": 889, "text": "There exist multiple solutions to solve the problem of distributing not only the work but also the data — actually the whole field of big data and data engineering builds around that. The general idea is to only load a fraction of the data into each machine and perform the calculation on this partition of the data — instead of loading all the data at the same time. The inputs and results are distributed either via network transmissions or via a distributed file system, such as HDFS." }, { "code": null, "e": 1869, "s": 1377, "text": "Two of the best-known examples for this (at least in the Python world) are Apache Spark (with its python bindings PySpark) and dask. We will not cover the basics of Apache Spark nor dask here - they are both wonderful libraries and if you never used them you should definitely check them out! If you do not want to use any of those frameworks, but you still have too much data to handle, have a look into the next section where we will discuss a simplified (but also less powerful) solution." }, { "code": null, "e": 2196, "s": 1869, "text": "Since version 0.15, tsfresh contains convenience functions to input a Spark data frame or a dask data frame into tsfresh (remember: normally you can only use pandas data frames). They are both defined in the tsfresh.convenience.bindings module (with documentation here) and we will cover them in the remainder of this section." }, { "code": null, "e": 2220, "s": 2196, "text": "The idea is as follows:" }, { "code": null, "e": 2527, "s": 2220, "text": "You take care of converting the data into the correct format for tsfresh (see below, what this means). For pandas data frames this is something we can do on our side. But for those distributed systems, so much careful craftsmanship goes into transforming the data - we can not handle this in a general way." }, { "code": null, "e": 2921, "s": 2527, "text": "You use one of the bindings mentioned above, to add the tsfresh feature extraction to the data pipeline. Both the input as well as the output of these functions are dask or PySpark data frames. Internally, tsfresh will convert each chunk of your data to a pandas data frame and use the normal feature extraction procedure. Afterward, the result is converted back - so you will not notice this." }, { "code": null, "e": 3032, "s": 2921, "text": "You continue working with this data frame, e.g. store it as a file or execute additional data transformations." }, { "code": null, "e": 3399, "s": 3032, "text": "As an example, we will again use the robot failure data sample from our Quickstart. Even though it is still small enough to fit into your memory, we will treat it as “big data” and spill it out to multiple parquet files on disk. Make sure to have a pandas parquet binding installed for this (such as pyarrow, see installation instructions) or use a different format." }, { "code": null, "e": 3820, "s": 3399, "text": "from tsfresh.examples import robot_execution_failuresimport osrobot_execution_failures.download_robot_execution_failures()timeseries, _ = robot_execution_failures.load_robot_execution_failures()def store_data(data_chunk): data_id = data_chunk[\"id\"].iloc[0] os.makedirs(f\"data/{data_id}\", exist_ok=True) data_chunk.to_parquet(f\"data/{data_id}/data.parquet\", index=False)timeseries.groupby(\"id\").apply(store_data)" }, { "code": null, "e": 3857, "s": 3820, "text": "Let's start with Apache Spark first." }, { "code": null, "e": 4597, "s": 3857, "text": "Apache Spark is basically the framework for writing and distributing fault-tolerant data pipelines. Even though it is written in Java (and Scala), it has very good and well-documented Python bindings called pyspark. After having installed Apache Spark (see here), you need to create a Spark cluster for distributing the work. As usual, there exist many ways for this (see here for a start), but as an example, we will just use the standalone cluster, which is started when you do not specify differently (also called “local” mode). We will demonstrate the calculation in the following with a pyspark interactive console, but you can of course also write it into a python script and submit it via spark-submit (check out the documentation)." }, { "code": null, "e": 4902, "s": 4597, "text": "Important: Spark leverages the arrow bindings for efficient transformation between pandas and Spark data frames. Therefore, you need to have arrow installed. In a recent arrow version, the internal data format has changed and is now incompatible with Spark. For it to still work, you need to add the line" }, { "code": null, "e": 4930, "s": 4902, "text": "ARROW_PRE_0_15_IPC_FORMAT=1" }, { "code": null, "e": 5032, "s": 4930, "text": "to your Spark environment settings file $SPARK_HOME/conf/spark-env.sh as stated in the documentation." }, { "code": null, "e": 5241, "s": 5032, "text": "Now let’s create a data pipeline! We will use Spark’s structured declarative data frame API in the following. Remember that Spark will only build up the computation DAG until you trigger an action in the end." }, { "code": null, "e": 5562, "s": 5241, "text": "So first, let's spin up an interactive pyspark shell and read in the parquet files. As we are running in local mode we do not need to make sure that the data is available for all workers (as there is only one local worker). In a productive environment, you would probably use S3 or HDFS or any other shared data storage." }, { "code": null, "e": 6338, "s": 5562, "text": "$ pyspark>>> df = spark.read \\... .parquet(\"data/*/data.parquet\")>>> df.printSchema()root|-- id: integer (nullable = true)|-- time: integer (nullable = true)|-- F_x: integer (nullable = true)|-- F_y: integer (nullable = true)|-- F_z: integer (nullable = true)|-- T_x: integer (nullable = true)|-- T_y: integer (nullable = true)|-- T_z: integer (nullable = true)>>> df.show()+---+----+----+---+-----+----+----+---+| id|time| F_x|F_y| F_z| T_x| T_y|T_z|+---+----+----+---+-----+----+----+---+| 71| 0| -59| 44| -205|-305|-226| 37|| 71| 1| -71| 55| -273|-368|-271| 42|| 71| 2| -75| 58| -305|-403|-294| 48|| 71| 3| -89| 66| -408|-471|-342| 51|| 71| 4| -95| 64| -461|-503|-372| 47|| 71| 5|-100| 67| -524|-545|-400| 51|| 71| 6|-104| 55| -567|-547|-429| 56|..." }, { "code": null, "e": 6896, "s": 6338, "text": "This is the format of the robot data. id is the identifier for each time series, time is the time (sorting) parameter, and the F_* and T_* are the different value series (remember: what we call the kind of the time series). Please note that this data format and the pre-processing we will perform in the following is just an example - your data might look differently and other data transformation steps might be necessary. For example, if your column names are different (e.g. the id column is not called “id”), you will need to edit the steps accordingly." }, { "code": null, "e": 7429, "s": 6896, "text": "The feature extraction will later run on each of these series separately — so we first need to group it both by the time-series identifier id and the kind. However, the data is not easily groupable by kind (data of the same kind are not separated) - so we first need to reshape the data. This transformation is usually called melting and there exist various ways to do this in PySpark. For example, you could follow one of the answers to this StackOverflow discussion. Just make sure to change the column name identifiers if needed." }, { "code": null, "e": 8172, "s": 7429, "text": ">>> ... your melt function, e.g. see in the link above>>> df_melted = melt(df, id_vars=[\"id\", \"time\"],... value_vars=[\"F_x\", \"F_y\", \"F_z\", \"T_x\", \"T_y\", \"T_z\"],... var_name=\"kind\", value_name=\"value\")>>> df_melted.printSchema()root|-- id: integer (nullable = true)|-- time: integer (nullable = true)|-- kind: string (nullable = false)|-- value: integer (nullable = true)>>> df_melted.show()+---+----+----+-----+| id|time|kind|value|+---+----+----+-----+| 71| 0| F_x| -59|| 71| 0| F_y| 44|| 71| 0| F_z| -205|| 71| 0| T_x| -305|| 71| 0| T_y| -226|| 71| 0| T_z| 37|| 71| 1| F_x| -71|| 71| 1| F_y| 55|| 71| 1| F_z| -273|| 71| 1| T_x| -368|| 71| 1| T_y| -271|| 71| 1| T_z| 42|..." }, { "code": null, "e": 8339, "s": 8172, "text": "After melting, the resulting data frame is a concatenated set of each kind of the time-series, while keeping the id and time columns. When we now group by id and kind" }, { "code": null, "e": 8390, "s": 8339, "text": ">>> df_grouped = df_melted.groupby([\"id\", \"kind\"])" }, { "code": null, "e": 8652, "s": 8390, "text": "each grouped chunk of data only contains the data of one kind and one id. We are now ready to use tsfresh! The preprocessing part might look different for your data sample, but you should always end up with a dataset grouped by id and kind before using tsfresh." }, { "code": null, "e": 8733, "s": 8652, "text": "With the given column names in the example, the call to tsfresh looks like this:" }, { "code": null, "e": 9150, "s": 8733, "text": ">>> from tsfresh.convenience.bindings import spark_feature_extraction_on_chunk>>> from tsfresh.feature_extraction import ComprehensiveFCParameters>>> features = spark_feature_extraction_on_chunk(df_grouped, ... column_id=\"id\",... column_kind=\"kind\",... column_sort=\"time\",... column_value=\"value\",... default_fc_parameters=ComprehensiveFCParameters())" }, { "code": null, "e": 9289, "s": 9150, "text": "Please remember that Spark will only trigger the calculation once you call an action, so it is still only building up the calculation DAG." }, { "code": null, "e": 9356, "s": 9289, "text": "Internally, tsfresh will call the following on each grouped chunk:" }, { "code": null, "e": 9452, "s": 9356, "text": "Transform the chunk to a pandas data frame (which is very efficient due to the usage of arrow)." }, { "code": null, "e": 9658, "s": 9452, "text": "Extract the features using the parameters and settings you gave (check out the documentation for more information on the settings). We are using the full set of feature calculators here just as an example." }, { "code": null, "e": 9709, "s": 9658, "text": "Then convert back to a format PySpark understands." }, { "code": null, "e": 9849, "s": 9709, "text": "In the end, it will return a Spark data frame, where each line is the value for a different feature of a different time series id and kind." }, { "code": null, "e": 10327, "s": 9849, "text": ">>> features.printSchema()root|-- id: long (nullable = true)|-- variable: string (nullable = true)|-- value: double (nullable = true)>>> features.show()+---+--------------------+-------------------+| id| variable| value|+---+--------------------+-------------------+| 12| F_x__sum_values| -6.0|| 12| F_x__median| -1.0|| 12| F_x__mean| -0.4|| 12| F_x__length| 15.0|..." }, { "code": null, "e": 10549, "s": 10327, "text": "Depending on your use case, you might want to bring them into the usual tabular form (but please note that this might imply heavy shuffling and especially some immediate calculations as the column names need to be known):" }, { "code": null, "e": 10864, "s": 10549, "text": ">>> from pyspark.sql import functions as F>>> pivoted_features = features.groupby(\"id\").pivot(\"variable\")>>> feature_table = pivoted_features.agg(F.first(\"value\"))>>> feature_table.printSchema()root|-- id: long (nullable = true)|-- F_x__length: double (nullable = true)|-- F_x__maximum: double (nullable = true)..." }, { "code": null, "e": 11036, "s": 10864, "text": "In any case, you can now apply additional transformations or write out the result of the calculation. As long as you have enough workers, this basically scales infinitely." }, { "code": null, "e": 11162, "s": 11036, "text": "In principle interacting with tsfresh from dask follows the same principles as with Spark, so lets quickly walk through them:" }, { "code": null, "e": 11522, "s": 11162, "text": "Spin up a dask cluster. There are again multiple ways how to do this depending on your environment. A very good starting point is the dask documentation. If you do not have a cluster to play around, local mode will also work (which means you do not need to setup or import anything). For testing, you can use an interactive python shell or a jupyter notebook." }, { "code": null, "e": 11546, "s": 11522, "text": "Read in the data sample" }, { "code": null, "e": 11697, "s": 11546, "text": ">>> from dask import dataframe as dd >>> # Make sure to setup your client here if you have a cluster >>> df = dd.read_parquet(\"data/*/data.parquet\")" }, { "code": null, "e": 11881, "s": 11697, "text": "Bring the data into the same format as above, where data with different id and kind can be separated easily. Fortunately, dask has already a melt feature, so you just need to call it:" }, { "code": null, "e": 12323, "s": 11881, "text": ">>> df_melted = df.melt(id_vars=[\"id\", \"time\"], ... value_vars=[\"F_x\", \"F_y\", \"F_z\", \"T_x\", \"T_y\", \"T_z\"], ... var_name=\"kind\", value_name=\"value\") >>> df_melted.columns Index(['id', 'time', 'kind', 'value'], dtype='object') >>> df_melted.head() id time kind value 0 1 0 F_x -1 1 1 1 F_x 0 2 1 2 F_x -1 3 1 3 F_x -1 4 1 4 F_x -1" }, { "code": null, "e": 12383, "s": 12323, "text": "Now separate the data for different id and kind by grouping" }, { "code": null, "e": 12434, "s": 12383, "text": ">>> df_grouped = df_melted.groupby([\"id\", \"kind\"])" }, { "code": null, "e": 12628, "s": 12434, "text": "The data is in the correct format — we can apply tsfresh! We are again using the full set of feature calculators as an example here, but have a look into the documentation for more information." }, { "code": null, "e": 13070, "s": 12628, "text": ">>> from tsfresh.convenience.bindings import dask_feature_extraction_on_chunk >>> from tsfresh.feature_extraction.settings import ComprehensiveFCParameters >>> features = dask_feature_extraction_on_chunk(df_grouped, ... column_id=\"id\", ... column_kind=\"kind\", ... column_sort=\"time\", ... column_value=\"value\", ... default_fc_parameters=ComprehensiveFCParameters())" }, { "code": null, "e": 13309, "s": 13070, "text": "Again, this will internally transform each chunk into a pandas data frame, apply the feature extraction, and transform it back into a dask data frame. The result will be a data frame with one extracted feature for one id and kind per row." }, { "code": null, "e": 13762, "s": 13309, "text": ">>> features.columns Index(['id', 'variable', 'value'], dtype='object') >>> features.head() id variable value id kind 11 T_x 0 11 T_x__sum_values -49.000000 1 11 T_x__median -5.000000 2 11 T_x__mean -3.266667 3 11 T_x__length 15.000000 4 11 T_x__standard_deviation 3.549022" }, { "code": null, "e": 13905, "s": 13762, "text": "Continue with your calculation, e.g. transform the results into the usual tabular form (again: this might be computationally very intensive!):" }, { "code": null, "e": 14165, "s": 13905, "text": ">>> features = features.categorize(columns=[\"variable\"]) >>> features = features.reset_index(drop=True) >>> feature_table = features.pivot_table(index=\"id\", ... columns=\"variable\", values=\"value\", ... aggfunc=\"sum\")" }, { "code": null, "e": 14319, "s": 14165, "text": "In case you are wondering: the aggregation function “sum” does not really matter here: there is only ever a single value per feature name and identifier." }, { "code": null, "e": 14495, "s": 14319, "text": "You might ask yourself what the difference is between using a ClusterDaskDistributor (which distributes to a dask cluster) as described in the last post and this dask binding." }, { "code": null, "e": 14858, "s": 14495, "text": "The ClusterDaskDistributor allows you to distribute the feature extraction calculation via a dask cluster of workers, while still keeping all the data in a non-distributed pandas data frame format. It is therefore useful if you want to parallelize the calculation, but the amount of data is still small enough for you to handle with pandas (on a single machine)." }, { "code": null, "e": 15063, "s": 14858, "text": "The dask (or PySpark) bindings described here allow you to have a non-pandas input, where the data itself is already distributed. It gives you much more flexibility to add tsfresh into your data pipeline." }, { "code": null, "e": 15363, "s": 15063, "text": "The data preprocessing depends a lot on the shape of your data and the way shown here is most likely not the most efficient way for you (because it might lead to a lot of shuffling or re-partitioning). Please think about how you can transform your data efficiently into the input format for tsfresh." }, { "code": null, "e": 15546, "s": 15363, "text": "You have a lot of data which does not fit into memory, but you do not want to add the burden of using a distributed framework (such as dask or PySpark) to your project? Then read on!" }, { "code": null, "e": 15739, "s": 15546, "text": "In the following, we will follow the ideas of a distributed framework such as dask or Apache Spark without actually using one (which of course also has some downsides, see below). The idea is:" }, { "code": null, "e": 15847, "s": 15739, "text": "Remember that we can extract the features for a time series of given id and kind independently from others." }, { "code": null, "e": 15998, "s": 15847, "text": "This means we can separate each cycle of: 1. read in the data for a specific kind and id, 2. extract the features on this data, 3. write out the data." }, { "code": null, "e": 16048, "s": 15998, "text": "Now we just need to orchestrate these work tasks." }, { "code": null, "e": 16300, "s": 16048, "text": "For this part, we will use the powers of luigi, a task orchestrator framework. If you have never used luigi have a look into the documentation for a first overview before you continue. We will also try to walk through the basic ideas in the following." }, { "code": null, "e": 16473, "s": 16300, "text": "We will also assume that your data is stored to disk (maybe on a distributed storage like HDFS) and already partitioned by id and kind. For example, it might be in the form" }, { "code": null, "e": 16506, "s": 16473, "text": "<path>/<id>/<kind>/input.parquet" }, { "code": null, "e": 16611, "s": 16506, "text": "If you want to generate some test data with the robot dataset, you can use the following python snippet:" }, { "code": null, "e": 17260, "s": 16611, "text": "from tsfresh.examples import robot_execution_failuresimport osrobot_execution_failures.download_robot_execution_failures()timeseries, _ = robot_execution_failures.load_robot_execution_failures()def store_data(data_chunk): data_id = data_chunk[\"id\"].iloc[0] data_kind = data_chunk[\"kind\"].iloc[0] os.makedirs(f\"data/{data_id}/{data_kind}\", exist_ok=True) data_chunk.to_parquet(f\"data/{data_id}/{data_kind}/input.parquet\", index=False)timeseries.melt(id_vars=[\"id\", \"time\"], value_vars=[\"F_x\", \"F_y\", \"F_z\", \"T_x\", \"T_y\", \"T_z\"], var_name=\"kind\", value_name=\"value\").groupby([\"id\", \"kind\"]).apply(store_data)" }, { "code": null, "e": 17527, "s": 17260, "text": "Please note that the data is basically already melted due to the way it is stored. It is also possible to store the data only separated by id and let tsfresh extract the features for all kinds simultaneously. Feel free to adjust the luigi script below to your needs." }, { "code": null, "e": 17910, "s": 17527, "text": "The core building block of luigi are tasks. Tasks can have dependencies among each other, they define which output files they create and of course what to do when the task runs. They are controlled by parameters, which can be used to distinguish different instances of the same task. Let’s define a Task for the cycle of reading, extracting, and writing the data as described above." }, { "code": null, "e": 19382, "s": 17910, "text": "import luigiimport pandas as pdfrom tsfresh import extract_features# Where the input data is stored.DATA_INPUT_NAME = \"data/{data_id}/{data_kind}/input.parquet\"# Where the output data will be storedDATA_OUTPUT_NAME = \"data/{data_id}/{data_kind}/output.parquet\"class FeatureExtractorTask(luigi.Task): \"\"\" Task to extract the features for one time series of given `id` and `kind`. Reads in the data, extracts the features and stores the data again. \"\"\" data_id = luigi.Parameter() data_kind = luigi.Parameter() def output(self): \"\"\"Define what this task will output\"\"\" return luigi.LocalTarget(DATA_OUTPUT_NAME.format(data_id=self.data_id, data_kind=self.data_kind)) def run(self): \"\"\"Define, what the task will actually do\"\"\" # 1. Read in the time series data from disk input_file = DATA_INPUT_NAME.format(data_id=self.data_id, data_kind=self.data_kind) df = pd.read_parquet(input_file) # 2. Extract the features. # Turn of multiprocessing - the parallelism comes with multiple luigi workers. features = extract_features(df, column_id=\"id\", column_kind=\"kind\", column_sort=\"time\", column_value=\"value\", n_jobs=0) # 3. Store the data features.to_parquet(self.output().path)" }, { "code": null, "e": 19662, "s": 19382, "text": "As you can see, the code is quite straightforward. We are again assuming only local setup for this example — in a real-world application the input and output paths will be on a shared file system (NFS, HDFS, S3) so that both the scheduler and the worker can read/write the files." }, { "code": null, "e": 20057, "s": 19662, "text": "Once we have defined a task for this cycle, we just need to run it. There exist multiple ways to do this — you could use a local scheduler, a central scheduler, or even a batch system (maybe with the help of my package b2luigi ;-)). As an example, we will just define a list of tasks to run and give it to the luigi.build function. Also, we are only using a single worker and a local scheduler." }, { "code": null, "e": 20339, "s": 20057, "text": "# ... continue from aboveif __name__ == \"__main__\": task_list = [] for data_kind in [\"F_x\", \"F_y\"]: for data_id in range(1, 5): task_list.append(FeatureExtractorTask(data_kind=data_kind, data_id=str(data_id))) luigi.build(task_list, local_scheduler=True)" }, { "code": null, "e": 20523, "s": 20339, "text": "Running this script will give you a happy smiley output and your output data stored in the specified paths. For distributing the work among several machines, start a central scheduler" }, { "code": null, "e": 20532, "s": 20523, "text": "$ luigid" }, { "code": null, "e": 20973, "s": 20532, "text": "And remove the local_scheduler flag. Each call to the luigi script will now start another worker, which will connect to the central scheduler and start processing work (if your code is running on multiple machines, you need to give the scheduler hostname as well). The documentation describes more options. If you want to test it out, make sure to increase the number of ids it needs to process — otherwise, it will run out of work quickly." }, { "code": null, "e": 21181, "s": 20973, "text": "Using luigi comes with the benefit of a very simple code base and a simplified execution model. But of course, this can not replace a distributed framework such as dask or Apache Spark with all its features:" }, { "code": null, "e": 21362, "s": 21181, "text": "You basically need to implement all the data handling by yourself (e.g. joining) using file operations. If you need this, you should really think about using one of the frameworks." }, { "code": null, "e": 21449, "s": 21362, "text": "There is a lot of file IO involved (luigi tasks can only communicate via file output)." }, { "code": null, "e": 21558, "s": 21449, "text": "There is no “high-level” API for data pipelines, everything needs to be implemented as single tasks by hand." }, { "code": null, "e": 21746, "s": 21558, "text": "But following the KISS principle, I would always prefer a small luigi application over running a complex distributed application (and have done so successfully several times in the past)." }, { "code": null, "e": 21824, "s": 21746, "text": "After all these possibilities, the question arises: When should you use what?" }, { "code": null, "e": 21860, "s": 21824, "text": "Let’s try to give some usage hints:" }, { "code": null, "e": 22187, "s": 21860, "text": "Use the simplest possibility that solves your task. If you can effort to read in all the data in memory, stick with pandas and use multiprocessing or a distributor. If you do not need to build a complex data pipeline, but rather only extract the features, think about using luigi (or anything alike, such as Airflow or celery)" }, { "code": null, "e": 22355, "s": 22187, "text": "The same applies to the single or multi-node calculation: fewer machines, fewer problems. Try to stay with single-processing or local calculations as long as possible." }, { "code": null, "e": 22599, "s": 22355, "text": "If the rest of your data pipeline is already implemented in another framework which is not mentioned here, try to stick with your framework. The code for the bindings is actually quite simple — so you can easily reproduce it in your framework." }, { "code": null, "e": 22881, "s": 22599, "text": "There is a lot more to discover when it comes to distributed computing or distributed data. If you find out about interesting bindings between your framework and tsfresh or of you developed a cool distributor you want to share, we are already happy for pull requests. Happy coding!" } ]
How to convert negative values in a matrix to 0 in R?
To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0). Consider the below data frame − Live Demo M1<-matrix(sample(-10:2,40,replace=TRUE),ncol=2) M1 [,1] [,2] [1,] 0 -2 [2,] -1 0 [3,] -10 1 [4,] -4 -8 [5,] -7 -8 [6,] 0 0 [7,] -7 0 [8,] -8 -3 [9,] -1 -9 [10,] -4 -10 [11,] 1 -7 [12,] 0 -5 [13,] -6 -3 [14,] -4 -4 [15,] -4 -4 [16,] 0 2 [17,] -7 -2 [18,] -7 -2 [19,] -5 -5 [20,] -6 -7 Converting negative values in matrix M1 to 0 − pmax(M1,0) [,1] [,2] [1,] 0 0 [2,] 0 0 [3,] 0 1 [4,] 0 0 [5,] 0 0 [6,] 0 0 [7,] 0 0 [8,] 0 0 [9,] 0 0 [10,] 0 0 [11,] 1 0 [12,] 0 0 [13,] 0 0 [14,] 0 0 [15,] 0 0 [16,] 0 2 [17,] 0 0 [18,] 0 0 [19,] 0 0 [20,] 0 0 Live Demo M2<-matrix(sample(-10:10,80,replace=TRUE),ncol=4) M2 [,1] [,2] [,3] [,4] [1,] -10 1 4 7 [2,] -9 5 6 2 [3,] 7 4 1 -5 [4,] 2 9 0 2 [5,] -2 -6 1 -9 [6,] 8 -9 -9 1 [7,] 3 -3 0 -1 [8,] 5 0 -3 5 [9,] -2 5 7 -5 [10,] -3 0 -8 1 [11,] -4 3 -2 -4 [12,] 5 4 -5 2 [13,] 0 10 -1 -8 [14,] 5 -9 -4 -1 [15,] 6 -6 2 0 [16,] -6 -9 -5 -8 [17,] -4 4 -9 -3 [18,] 4 -10 4 7 [19,] -9 -8 2 -4 [20,] -2 3 9 -8 Converting negative values in matrix M2 to 0 − pmax(M2,0) [,1] [,2] [,3] [,4] [1,] 0 1 4 7 [2,] 0 5 6 2 [3,] 7 4 1 0 [4,] 2 9 0 2 [5,] 0 0 1 0 [6,] 8 0 0 1 [7,] 3 0 0 0 [8,] 5 0 0 5 [9,] 0 5 7 0 [10,] 0 0 0 1 [11,] 0 3 0 0 [12,] 5 4 0 2 [13,] 0 10 0 0 [14,] 5 0 0 0 [15,] 6 0 2 0 [16,] 0 0 0 0 [17,] 0 4 0 0 [18,] 4 0 4 7 [19,] 0 0 2 0 [20,] 0 3 9 0
[ { "code": null, "e": 1321, "s": 1062, "text": "To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0)." }, { "code": null, "e": 1353, "s": 1321, "text": "Consider the below data frame −" }, { "code": null, "e": 1364, "s": 1353, "text": " Live Demo" }, { "code": null, "e": 1416, "s": 1364, "text": "M1<-matrix(sample(-10:2,40,replace=TRUE),ncol=2)\nM1" }, { "code": null, "e": 1724, "s": 1416, "text": " [,1] [,2]\n[1,] 0 -2\n[2,] -1 0\n[3,] -10 1\n[4,] -4 -8\n[5,] -7 -8\n[6,] 0 0\n[7,] -7 0\n[8,] -8 -3\n[9,] -1 -9\n[10,] -4 -10\n[11,] 1 -7\n[12,] 0 -5\n[13,] -6 -3\n[14,] -4 -4\n[15,] -4 -4\n[16,] 0 2\n[17,] -7 -2\n[18,] -7 -2\n[19,] -5 -5\n[20,] -6 -7" }, { "code": null, "e": 1771, "s": 1724, "text": "Converting negative values in matrix M1 to 0 −" }, { "code": null, "e": 1782, "s": 1771, "text": "pmax(M1,0)" }, { "code": null, "e": 2057, "s": 1782, "text": " [,1] [,2]\n[1,] 0 0\n[2,] 0 0\n[3,] 0 1\n[4,] 0 0\n[5,] 0 0\n[6,] 0 0\n[7,] 0 0\n[8,] 0 0\n[9,] 0 0\n[10,] 0 0\n[11,] 1 0\n[12,] 0 0\n[13,] 0 0\n[14,] 0 0\n[15,] 0 0\n[16,] 0 2\n[17,] 0 0\n[18,] 0 0\n[19,] 0 0\n[20,] 0 0" }, { "code": null, "e": 2068, "s": 2057, "text": " Live Demo" }, { "code": null, "e": 2121, "s": 2068, "text": "M2<-matrix(sample(-10:10,80,replace=TRUE),ncol=4)\nM2" }, { "code": null, "e": 2627, "s": 2121, "text": " [,1] [,2] [,3] [,4]\n[1,] -10 1 4 7\n[2,] -9 5 6 2\n[3,] 7 4 1 -5\n[4,] 2 9 0 2\n[5,] -2 -6 1 -9\n[6,] 8 -9 -9 1\n[7,] 3 -3 0 -1\n[8,] 5 0 -3 5\n[9,] -2 5 7 -5\n[10,] -3 0 -8 1\n[11,] -4 3 -2 -4\n[12,] 5 4 -5 2\n[13,] 0 10 -1 -8\n[14,] 5 -9 -4 -1\n[15,] 6 -6 2 0\n[16,] -6 -9 -5 -8\n[17,] -4 4 -9 -3\n[18,] 4 -10 4 7\n[19,] -9 -8 2 -4\n[20,] -2 3 9 -8" }, { "code": null, "e": 2674, "s": 2627, "text": "Converting negative values in matrix M2 to 0 −" }, { "code": null, "e": 2685, "s": 2674, "text": "pmax(M2,0)" }, { "code": null, "e": 3191, "s": 2685, "text": " [,1] [,2] [,3] [,4]\n[1,] 0 1 4 7\n[2,] 0 5 6 2\n[3,] 7 4 1 0\n[4,] 2 9 0 2\n[5,] 0 0 1 0\n[6,] 8 0 0 1\n[7,] 3 0 0 0\n[8,] 5 0 0 5\n[9,] 0 5 7 0\n[10,] 0 0 0 1\n[11,] 0 3 0 0\n[12,] 5 4 0 2\n[13,] 0 10 0 0\n[14,] 5 0 0 0\n[15,] 6 0 2 0\n[16,] 0 0 0 0\n[17,] 0 4 0 0\n[18,] 4 0 4 7\n[19,] 0 0 2 0\n[20,] 0 3 9 0" } ]
Find largest subtree sum in a tree - GeeksforGeeks
28 Jun, 2021 Given a binary tree, task is to find subtree with maximum sum in tree.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 28 As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements. Input : 1 / \ -2 3 / \ / \ 4 5 -6 2 Output : 7 Subtree with largest sum is : -2 / \ 4 5 Also, entire tree sum is also 7. Approach : Do post order traversal of the binary tree. At every node, find left subtree value and right subtree value recursively. The value of subtree rooted at current node is equal to sum of current node value, left node subtree sum and right node subtree sum. Compare current subtree sum with overall maximum subtree sum so far.Implementation : C++ Java Python3 C# Javascript // C++ program to find largest subtree// sum in a given binary tree.#include <bits/stdc++.h>using namespace std; // Structure of a tree node.struct Node { int key; Node *left, *right;}; // Function to create new tree node.Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Helper function to find largest// subtree sum recursively.int findLargestSubtreeSumUtil(Node* root, int& ans){ // If current node is null then // return 0 to parent node. if (root == NULL) return 0; // Subtree sum rooted at current node. int currSum = root->key + findLargestSubtreeSumUtil(root->left, ans) + findLargestSubtreeSumUtil(root->right, ans); // Update answer if current subtree // sum is greater than answer so far. ans = max(ans, currSum); // Return current subtree sum to // its parent node. return currSum;} // Function to find largest subtree sum.int findLargestSubtreeSum(Node* root){ // If tree does not exist, // then answer is 0. if (root == NULL) return 0; // Variable to store maximum subtree sum. int ans = INT_MIN; // Call to recursive function to // find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans;} // Driver functionint main(){ /* 1 / \ / \ -2 3 / \ / \ / \ / \ 4 5 -6 2 */ Node* root = newNode(1); root->left = newNode(-2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(-6); root->right->right = newNode(2); cout << findLargestSubtreeSum(root); return 0;} // Java program to find largest// subtree sum in a given binary tree.import java.util.*;class GFG{ // Structure of a tree node.static class Node{ int key; Node left, right;} static class INT{ int v; INT(int a) { v = a; }} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return temp;} // Helper function to find largest// subtree sum recursively.static int findLargestSubtreeSumUtil(Node root, INT ans){ // If current node is null then // return 0 to parent node. if (root == null) return 0; // Subtree sum rooted // at current node. int currSum = root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans); // Update answer if current subtree // sum is greater than answer so far. ans.v = Math.max(ans.v, currSum); // Return current subtree // sum to its parent node. return currSum;} // Function to find// largest subtree sum.static int findLargestSubtreeSum(Node root){ // If tree does not exist, // then answer is 0. if (root == null) return 0; // Variable to store // maximum subtree sum. INT ans = new INT(-9999999); // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans.v;} // Driver Codepublic static void main(String args[]){ /* 1 / \ / \ -2 3 / \ / \ / \ / \ 4 5 -6 2 */ Node root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); System.out.println(findLargestSubtreeSum(root));}} // This code is contributed by Arnab Kundu # Python3 program to find largest subtree# sum in a given binary tree. # Function to create new tree node.class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Helper function to find largest# subtree sum recursively.def findLargestSubtreeSumUtil(root, ans): # If current node is None then # return 0 to parent node. if (root == None): return 0 # Subtree sum rooted at current node. currSum = (root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans)) # Update answer if current subtree # sum is greater than answer so far. ans[0] = max(ans[0], currSum) # Return current subtree sum to # its parent node. return currSum # Function to find largest subtree sum.def findLargestSubtreeSum(root): # If tree does not exist, # then answer is 0. if (root == None): return 0 # Variable to store maximum subtree sum. ans = [-999999999999] # Call to recursive function to # find maximum subtree sum. findLargestSubtreeSumUtil(root, ans) return ans[0] # Driver Codeif __name__ == '__main__': # # 1 # / \ # / \ # -2 3 # / \ / \ # / \ / \ # 4 5 -6 2 root = newNode(1) root.left = newNode(-2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(-6) root.right.right = newNode(2) print(findLargestSubtreeSum(root)) # This code is contributed by PranchalK using System; // C# program to find largest// subtree sum in a given binary tree. public class GFG{ // Structure of a tree node.public class Node{ public int key; public Node left, right;} public class INT{ public int v; public INT(int a) { v = a; }} // Function to create new tree node.public static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return temp;} // Helper function to find largest// subtree sum recursively.public static int findLargestSubtreeSumUtil(Node root, INT ans){ // If current node is null then // return 0 to parent node. if (root == null) { return 0; } // Subtree sum rooted // at current node. int currSum = root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans); // Update answer if current subtree // sum is greater than answer so far. ans.v = Math.Max(ans.v, currSum); // Return current subtree // sum to its parent node. return currSum;} // Function to find// largest subtree sum.public static int findLargestSubtreeSum(Node root){ // If tree does not exist, // then answer is 0. if (root == null) { return 0; } // Variable to store // maximum subtree sum. INT ans = new INT(-9999999); // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans.v;} // Driver Codepublic static void Main(string[] args){ /* 1 / \ / \ -2 3 / \ / \ / \ / \ 4 5 -6 2 */ Node root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); Console.WriteLine(findLargestSubtreeSum(root));}} // This code is contributed by Shrikant13 <script> // Javascript program to find largest // subtree sum in a given binary tree. // Structure of a tree node. class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } let v; // Function to create new tree node. function newNode(key) { let temp = new Node(key); return temp; } // Helper function to find largest // subtree sum recursively. function findLargestSubtreeSumUtil(root) { // If current node is null then // return 0 to parent node. if (root == null) return 0; // Subtree sum rooted // at current node. let currSum = root.key + findLargestSubtreeSumUtil(root.left) + findLargestSubtreeSumUtil(root.right); // Update answer if current subtree // sum is greater than answer so far. v = Math.max(v, currSum); // Return current subtree // sum to its parent node. return currSum; } // Function to find // largest subtree sum. function findLargestSubtreeSum(root) { // If tree does not exist, // then answer is 0. if (root == null) return 0; // Variable to store // maximum subtree sum. v = -9999999; // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root); return v; } /* 1 / \ / \ -2 3 / \ / \ / \ / \ 4 5 -6 2 */ let root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); document.write(findLargestSubtreeSum(root)); // This code is contributed by divyesh072019.</script> 7 Time Complexity: O(n), where n is number of nodes. Auxiliary Space: O(n), function call stack size. YouTubeGeeksforGeeks500K subscribersFind largest subtree sum in a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:59•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7opoOv7SVko" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk andrew1234 shrikanth13 PranchalKatiyar divyesh072019 Binary Trees Quiz Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Inorder Tree Traversal without recursion and without stack!
[ { "code": null, "e": 35455, "s": 35427, "text": "\n28 Jun, 2021" }, { "code": null, "e": 35537, "s": 35455, "text": "Given a binary tree, task is to find subtree with maximum sum in tree.Examples: " }, { "code": null, "e": 35996, "s": 35537, "text": "Input : 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nOutput : 28\nAs all the tree elements are positive,\nthe largest subtree sum is equal to\nsum of all tree elements.\n\nInput : 1\n / \\\n -2 3\n / \\ / \\\n 4 5 -6 2\nOutput : 7\nSubtree with largest sum is : -2\n / \\ \n 4 5\nAlso, entire tree sum is also 7." }, { "code": null, "e": 36349, "s": 35998, "text": "Approach : Do post order traversal of the binary tree. At every node, find left subtree value and right subtree value recursively. The value of subtree rooted at current node is equal to sum of current node value, left node subtree sum and right node subtree sum. Compare current subtree sum with overall maximum subtree sum so far.Implementation : " }, { "code": null, "e": 36353, "s": 36349, "text": "C++" }, { "code": null, "e": 36358, "s": 36353, "text": "Java" }, { "code": null, "e": 36366, "s": 36358, "text": "Python3" }, { "code": null, "e": 36369, "s": 36366, "text": "C#" }, { "code": null, "e": 36380, "s": 36369, "text": "Javascript" }, { "code": "// C++ program to find largest subtree// sum in a given binary tree.#include <bits/stdc++.h>using namespace std; // Structure of a tree node.struct Node { int key; Node *left, *right;}; // Function to create new tree node.Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Helper function to find largest// subtree sum recursively.int findLargestSubtreeSumUtil(Node* root, int& ans){ // If current node is null then // return 0 to parent node. if (root == NULL) return 0; // Subtree sum rooted at current node. int currSum = root->key + findLargestSubtreeSumUtil(root->left, ans) + findLargestSubtreeSumUtil(root->right, ans); // Update answer if current subtree // sum is greater than answer so far. ans = max(ans, currSum); // Return current subtree sum to // its parent node. return currSum;} // Function to find largest subtree sum.int findLargestSubtreeSum(Node* root){ // If tree does not exist, // then answer is 0. if (root == NULL) return 0; // Variable to store maximum subtree sum. int ans = INT_MIN; // Call to recursive function to // find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans;} // Driver functionint main(){ /* 1 / \\ / \\ -2 3 / \\ / \\ / \\ / \\ 4 5 -6 2 */ Node* root = newNode(1); root->left = newNode(-2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(-6); root->right->right = newNode(2); cout << findLargestSubtreeSum(root); return 0;}", "e": 38159, "s": 36380, "text": null }, { "code": "// Java program to find largest// subtree sum in a given binary tree.import java.util.*;class GFG{ // Structure of a tree node.static class Node{ int key; Node left, right;} static class INT{ int v; INT(int a) { v = a; }} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return temp;} // Helper function to find largest// subtree sum recursively.static int findLargestSubtreeSumUtil(Node root, INT ans){ // If current node is null then // return 0 to parent node. if (root == null) return 0; // Subtree sum rooted // at current node. int currSum = root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans); // Update answer if current subtree // sum is greater than answer so far. ans.v = Math.max(ans.v, currSum); // Return current subtree // sum to its parent node. return currSum;} // Function to find// largest subtree sum.static int findLargestSubtreeSum(Node root){ // If tree does not exist, // then answer is 0. if (root == null) return 0; // Variable to store // maximum subtree sum. INT ans = new INT(-9999999); // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans.v;} // Driver Codepublic static void main(String args[]){ /* 1 / \\ / \\ -2 3 / \\ / \\ / \\ / \\ 4 5 -6 2 */ Node root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); System.out.println(findLargestSubtreeSum(root));}} // This code is contributed by Arnab Kundu", "e": 40107, "s": 38159, "text": null }, { "code": "# Python3 program to find largest subtree# sum in a given binary tree. # Function to create new tree node.class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Helper function to find largest# subtree sum recursively.def findLargestSubtreeSumUtil(root, ans): # If current node is None then # return 0 to parent node. if (root == None): return 0 # Subtree sum rooted at current node. currSum = (root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans)) # Update answer if current subtree # sum is greater than answer so far. ans[0] = max(ans[0], currSum) # Return current subtree sum to # its parent node. return currSum # Function to find largest subtree sum.def findLargestSubtreeSum(root): # If tree does not exist, # then answer is 0. if (root == None): return 0 # Variable to store maximum subtree sum. ans = [-999999999999] # Call to recursive function to # find maximum subtree sum. findLargestSubtreeSumUtil(root, ans) return ans[0] # Driver Codeif __name__ == '__main__': # # 1 # / \\ # / \\ # -2 3 # / \\ / \\ # / \\ / \\ # 4 5 -6 2 root = newNode(1) root.left = newNode(-2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(-6) root.right.right = newNode(2) print(findLargestSubtreeSum(root)) # This code is contributed by PranchalK", "e": 41728, "s": 40107, "text": null }, { "code": "using System; // C# program to find largest// subtree sum in a given binary tree. public class GFG{ // Structure of a tree node.public class Node{ public int key; public Node left, right;} public class INT{ public int v; public INT(int a) { v = a; }} // Function to create new tree node.public static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return temp;} // Helper function to find largest// subtree sum recursively.public static int findLargestSubtreeSumUtil(Node root, INT ans){ // If current node is null then // return 0 to parent node. if (root == null) { return 0; } // Subtree sum rooted // at current node. int currSum = root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans); // Update answer if current subtree // sum is greater than answer so far. ans.v = Math.Max(ans.v, currSum); // Return current subtree // sum to its parent node. return currSum;} // Function to find// largest subtree sum.public static int findLargestSubtreeSum(Node root){ // If tree does not exist, // then answer is 0. if (root == null) { return 0; } // Variable to store // maximum subtree sum. INT ans = new INT(-9999999); // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root, ans); return ans.v;} // Driver Codepublic static void Main(string[] args){ /* 1 / \\ / \\ -2 3 / \\ / \\ / \\ / \\ 4 5 -6 2 */ Node root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); Console.WriteLine(findLargestSubtreeSum(root));}} // This code is contributed by Shrikant13", "e": 43709, "s": 41728, "text": null }, { "code": "<script> // Javascript program to find largest // subtree sum in a given binary tree. // Structure of a tree node. class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } let v; // Function to create new tree node. function newNode(key) { let temp = new Node(key); return temp; } // Helper function to find largest // subtree sum recursively. function findLargestSubtreeSumUtil(root) { // If current node is null then // return 0 to parent node. if (root == null) return 0; // Subtree sum rooted // at current node. let currSum = root.key + findLargestSubtreeSumUtil(root.left) + findLargestSubtreeSumUtil(root.right); // Update answer if current subtree // sum is greater than answer so far. v = Math.max(v, currSum); // Return current subtree // sum to its parent node. return currSum; } // Function to find // largest subtree sum. function findLargestSubtreeSum(root) { // If tree does not exist, // then answer is 0. if (root == null) return 0; // Variable to store // maximum subtree sum. v = -9999999; // Call to recursive function // to find maximum subtree sum. findLargestSubtreeSumUtil(root); return v; } /* 1 / \\ / \\ -2 3 / \\ / \\ / \\ / \\ 4 5 -6 2 */ let root = newNode(1); root.left = newNode(-2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(-6); root.right.right = newNode(2); document.write(findLargestSubtreeSum(root)); // This code is contributed by divyesh072019.</script>", "e": 45653, "s": 43709, "text": null }, { "code": null, "e": 45655, "s": 45653, "text": "7" }, { "code": null, "e": 45759, "s": 45657, "text": "Time Complexity: O(n), where n is number of nodes. Auxiliary Space: O(n), function call stack size. " }, { "code": null, "e": 46592, "s": 45759, "text": "YouTubeGeeksforGeeks500K subscribersFind largest subtree sum in a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:59•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7opoOv7SVko\" 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": 46634, "s": 46592, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 46645, "s": 46634, "text": "andrew1234" }, { "code": null, "e": 46657, "s": 46645, "text": "shrikanth13" }, { "code": null, "e": 46673, "s": 46657, "text": "PranchalKatiyar" }, { "code": null, "e": 46687, "s": 46673, "text": "divyesh072019" }, { "code": null, "e": 46705, "s": 46687, "text": "Binary Trees Quiz" }, { "code": null, "e": 46710, "s": 46705, "text": "Tree" }, { "code": null, "e": 46715, "s": 46710, "text": "Tree" }, { "code": null, "e": 46813, "s": 46715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46822, "s": 46813, "text": "Comments" }, { "code": null, "e": 46835, "s": 46822, "text": "Old Comments" }, { "code": null, "e": 46885, "s": 46835, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 46920, "s": 46885, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 46949, "s": 46920, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 46983, "s": 46949, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 47024, "s": 46983, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 47067, "s": 47024, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 47129, "s": 47067, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 47162, "s": 47129, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 47212, "s": 47162, "text": "A program to check if a binary tree is BST or not" } ]
Perl | length() Function - GeeksforGeeks
25 Jun, 2019 length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Syntax:length(VAR) Parameter:VAR: String or a group of strings whose length is to be calculatedReturn:Returns the size of the string. Example 1: #!/usr/bin/perl # String whose length is to be calculated$orignal_string = "Geeks for Geeks"; # Function to calculate length$string_len = length($orignal_string); # Printing the Lengthprint "Length of String is: $string_len"; Output: Length of String is: 15 Example 2: #!/usr/bin/perl # String whose length is to be calculated$orignal_string = "123456 is Geeks Code"; # Function to calculate length$string_len = length($orignal_string); # Printing the Lengthprint "Length of String is: $string_len"; Output: Length of String is: 20 Note : Scalar context on an array or hash is used if the corresponding size is to be determined. Perl-function Perl-String Perl-String-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | Polymorphism in OOPs Perl | Arrays Perl | Arrays (push, pop, shift, unshift) Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | Subroutines or Functions Perl | Boolean Values Introduction to Perl Perl | join() Function Perl | sleep() Function
[ { "code": null, "e": 23679, "s": 23651, "text": "\n25 Jun, 2019" }, { "code": null, "e": 23784, "s": 23679, "text": "length() function in Perl finds length (number of characters) of a given string, or $_ if not specified." }, { "code": null, "e": 23803, "s": 23784, "text": "Syntax:length(VAR)" }, { "code": null, "e": 23918, "s": 23803, "text": "Parameter:VAR: String or a group of strings whose length is to be calculatedReturn:Returns the size of the string." }, { "code": null, "e": 23929, "s": 23918, "text": "Example 1:" }, { "code": "#!/usr/bin/perl # String whose length is to be calculated$orignal_string = \"Geeks for Geeks\"; # Function to calculate length$string_len = length($orignal_string); # Printing the Lengthprint \"Length of String is: $string_len\";", "e": 24158, "s": 23929, "text": null }, { "code": null, "e": 24166, "s": 24158, "text": "Output:" }, { "code": null, "e": 24190, "s": 24166, "text": "Length of String is: 15" }, { "code": null, "e": 24202, "s": 24190, "text": " Example 2:" }, { "code": "#!/usr/bin/perl # String whose length is to be calculated$orignal_string = \"123456 is Geeks Code\"; # Function to calculate length$string_len = length($orignal_string); # Printing the Lengthprint \"Length of String is: $string_len\";", "e": 24436, "s": 24202, "text": null }, { "code": null, "e": 24444, "s": 24436, "text": "Output:" }, { "code": null, "e": 24468, "s": 24444, "text": "Length of String is: 20" }, { "code": null, "e": 24565, "s": 24468, "text": "Note : Scalar context on an array or hash is used if the corresponding size is to be determined." }, { "code": null, "e": 24579, "s": 24565, "text": "Perl-function" }, { "code": null, "e": 24591, "s": 24579, "text": "Perl-String" }, { "code": null, "e": 24613, "s": 24591, "text": "Perl-String-Functions" }, { "code": null, "e": 24618, "s": 24613, "text": "Perl" }, { "code": null, "e": 24623, "s": 24618, "text": "Perl" }, { "code": null, "e": 24721, "s": 24623, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24730, "s": 24721, "text": "Comments" }, { "code": null, "e": 24743, "s": 24730, "text": "Old Comments" }, { "code": null, "e": 24771, "s": 24743, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 24785, "s": 24771, "text": "Perl | Arrays" }, { "code": null, "e": 24827, "s": 24785, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 24868, "s": 24827, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 24901, "s": 24868, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 24933, "s": 24901, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 24955, "s": 24933, "text": "Perl | Boolean Values" }, { "code": null, "e": 24976, "s": 24955, "text": "Introduction to Perl" }, { "code": null, "e": 24999, "s": 24976, "text": "Perl | join() Function" } ]
How do I write not greater than in a MySQL query?
The not greater than in a query can be written simply like less than or equal to ( <=). The syntax is as follows − select * from yourTableName where yourColumnName<=yourColumnName; Let us first create a table − mysql> create table DemoTable1480 -> ( -> StudentName varchar(40), -> StudentMarks int -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1480 values('Chris',78); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1480 values('Bob',45); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1480 values('John',67); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1480 values('Adam',56); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select * from DemoTable1480; This will produce the following output − +-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 78 | | Bob | 45 | | John | 67 | | Adam | 56 | +-------------+--------------+ 4 rows in set (0.00 sec) Following is the query to write not greater than in a MySQL query − mysql> select * from DemoTable1480 where StudentMarks <=65; This will produce the following output − +-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Bob | 45 | | Adam | 56 | +-------------+--------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1177, "s": 1062, "text": "The not greater than in a query can be written simply like less than or equal to ( <=). The syntax is as follows −" }, { "code": null, "e": 1243, "s": 1177, "text": "select * from yourTableName where yourColumnName<=yourColumnName;" }, { "code": null, "e": 1273, "s": 1243, "text": "Let us first create a table −" }, { "code": null, "e": 1415, "s": 1273, "text": "mysql> create table DemoTable1480\n -> (\n -> StudentName varchar(40),\n -> StudentMarks int\n -> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1471, "s": 1415, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1823, "s": 1471, "text": "mysql> insert into DemoTable1480 values('Chris',78);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1480 values('Bob',45);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1480 values('John',67);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1480 values('Adam',56);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1883, "s": 1823, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1919, "s": 1883, "text": "mysql> select * from DemoTable1480;" }, { "code": null, "e": 1960, "s": 1919, "text": "This will produce the following output −" }, { "code": null, "e": 2233, "s": 1960, "text": "+-------------+--------------+\n| StudentName | StudentMarks |\n+-------------+--------------+\n| Chris | 78 |\n| Bob | 45 |\n| John | 67 |\n| Adam | 56 |\n+-------------+--------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2301, "s": 2233, "text": "Following is the query to write not greater than in a MySQL query −" }, { "code": null, "e": 2361, "s": 2301, "text": "mysql> select * from DemoTable1480 where StudentMarks <=65;" }, { "code": null, "e": 2402, "s": 2361, "text": "This will produce the following output −" }, { "code": null, "e": 2613, "s": 2402, "text": "+-------------+--------------+\n| StudentName | StudentMarks |\n+-------------+--------------+\n| Bob | 45 |\n| Adam | 56 |\n+-------------+--------------+\n2 rows in set (0.00 sec)" } ]
Difference Between Properties and Indexers in C# - GeeksforGeeks
24 Jul, 2020 Properties in C# are named members that use access modifiers to set and retrieve values of fields declared in a secured manner. Properties are used for abstracting and encapsulating access to a field of a class by defining only important actions and hiding their implementation. Properties are invoked through a described name and can be declared as a static or an instance member. Syntax of declaring a property in C#: [access_modifier] [return_type] [PropertyName] { //body of property } Indexers in C# are data members that act as an array and allow you to access data within objects to be indexed in the same way. Indexers are always declared as instance members, never as static members. Indexers are implemented in the same way as properties, except that the declaration of an indexer must have at least one parameter. Syntax of creating an indexer in C#: [access_modifier] [return_type] this [parameter] { get { // return value } set { // return value } } CSharp-Indexers & Properties C# Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# Class method vs Static method in Python Difference between BFS and DFS Differences between TCP and UDP Difference between Process and Thread Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24012, "s": 23984, "text": "\n24 Jul, 2020" }, { "code": null, "e": 24394, "s": 24012, "text": "Properties in C# are named members that use access modifiers to set and retrieve values of fields declared in a secured manner. Properties are used for abstracting and encapsulating access to a field of a class by defining only important actions and hiding their implementation. Properties are invoked through a described name and can be declared as a static or an instance member." }, { "code": null, "e": 24432, "s": 24394, "text": "Syntax of declaring a property in C#:" }, { "code": null, "e": 24505, "s": 24432, "text": "[access_modifier] [return_type] [PropertyName] \n{\n//body of property\n}\n" }, { "code": null, "e": 24840, "s": 24505, "text": "Indexers in C# are data members that act as an array and allow you to access data within objects to be indexed in the same way. Indexers are always declared as instance members, never as static members. Indexers are implemented in the same way as properties, except that the declaration of an indexer must have at least one parameter." }, { "code": null, "e": 24877, "s": 24840, "text": "Syntax of creating an indexer in C#:" }, { "code": null, "e": 25002, "s": 24877, "text": "[access_modifier] [return_type] this [parameter]\n{\n get \n {\n // return value\n }\n set \n {\n // return value\n }\n}\n" }, { "code": null, "e": 25031, "s": 25002, "text": "CSharp-Indexers & Properties" }, { "code": null, "e": 25034, "s": 25031, "text": "C#" }, { "code": null, "e": 25053, "s": 25034, "text": "Difference Between" }, { "code": null, "e": 25151, "s": 25053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25160, "s": 25151, "text": "Comments" }, { "code": null, "e": 25173, "s": 25160, "text": "Old Comments" }, { "code": null, "e": 25201, "s": 25173, "text": "C# Dictionary with examples" }, { "code": null, "e": 25224, "s": 25201, "text": "C# | Method Overriding" }, { "code": null, "e": 25246, "s": 25224, "text": "C# | Class and Object" }, { "code": null, "e": 25286, "s": 25246, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 25309, "s": 25286, "text": "Extension Method in C#" }, { "code": null, "e": 25349, "s": 25309, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25380, "s": 25349, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25412, "s": 25380, "text": "Differences between TCP and UDP" }, { "code": null, "e": 25450, "s": 25412, "text": "Difference between Process and Thread" } ]
AWS DynamoDB - Working with Queries - GeeksforGeeks
13 Apr, 2021 Amazon DynamoDB is a NoSQL managed database service provided by Amazon that stores semi-structured data like key-value pairs. A DynamoDB table consists of items. Each item consists of one partition key and one or more attributes. An example of an item is given below: Example: { "MovieID": 101, "Name": "The Shawshank Redemption", "Rating": 9.2, "Year": 1994 } In the above example, MovieID is the partition key. A partition key is used to differentiate between items. A query operation in DynamoDB finds items based on primary key values. The name of the partition key attribute and a single value for that attribute must be provided. The query returns all items searched against that partition key value. A table say, Movies, with partition key as MovieID has been created already. No two items can have the same partition key. Add few items to query upon. A table has already been created with items in it. See the below image: To query upon items in the table, select Query from the dropdown in the items tab. By default, a query will always have a partition key as one of the search filters. We can add one or more attributes to refine the search. See the below image: In the above image we see that when we enter 50 for primary key MovieID, we obtain 1 record which is shown above in the image. To refine our search we can add one or more filters. In filter, we select an attribute and provide value against it. The query results returned is determined by a filter expression. All of the other results are discarded. A filter expression is applied before the results are returned, but after a Query finishes. Hence, a Query consumes the same amount of Read capacity, regardless of whether a filter expression is present or not. See the below image: In the above image, we see that in the filter, Rating has been provided and the condition is that it should be greater than or equal to 8. Thus, we get one search result. The Query operation allows you to limit the number of items that it reads. To do this, set the Limit parameter to the desired number of items that you want. For example, suppose that you Query a table, with a limit value of 8, and without a filter expression. The Query result contains the first eight items from the table that match the key condition expression from the request. The limit can only be used in Amazon Command Line Interface (CLI). Paging: This feature is available on Amazon CLI (Command Line Interface). When data retrieved is larger than 1 MB in the result set, then the result set is divided into pages, each page containing up to 1 MB. For instance, if 3 MB data is retrieved then there will be at least 3 pages. Counting Item in ResultSet: If the size of the Query result set is larger than 1 MB, ScannedCount and Count represent only a partial count of the total items. You need to perform multiple Query operations to retrieve all items in the result set. Capacity Units Consumed: A read capacity unit speaks for one strongly consistent read per second, or two eventually consistent reads per second, for an item up to the size of 4 KB. A scan operation does not return any data on how much the read capacity units are consumed. However, by specifying the ReturnConsumedCapacity parameter in a Scan request we can obtain this information or change the read capacity unit in the capacity tab of the table. See the below image: Read Consistency: By default, a scan operation performs eventually consistent reads. Meaning, the scan results might not include changes due to the recently completed PutItem or UpdateItem request. If required strong consistent reads, as of the time that the Scan begins, then set ConsistentRead parameter to true in the Scan request. By doing so, it ensures that all the write operations that completed before the Scan began are included in the Scan result set. AWS Cloud-Computing DynamoDB DynamoDB-Basics Picked Amazon Web Services DynamoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install Python3 on AWS EC2? Amazon S3 - Storage Classes Amazon RDS - Working with Read Replicas AWS DynamoDB - PartiQL Delete Statements For DynamoDB AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX) How to Mock AWS DynamoDB Services for Unit Testing? AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX) DynamoDB - Local Installation DynamoDB - Data Types DynamoDB - Using the Console
[ { "code": null, "e": 25240, "s": 25212, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25508, "s": 25240, "text": "Amazon DynamoDB is a NoSQL managed database service provided by Amazon that stores semi-structured data like key-value pairs. A DynamoDB table consists of items. Each item consists of one partition key and one or more attributes. An example of an item is given below:" }, { "code": null, "e": 25609, "s": 25508, "text": "Example:\n{\n \"MovieID\": 101,\n \"Name\": \"The Shawshank Redemption\",\n \"Rating\": 9.2,\n \"Year\": 1994\n}" }, { "code": null, "e": 25662, "s": 25609, "text": "In the above example, MovieID is the partition key. " }, { "code": null, "e": 25956, "s": 25662, "text": "A partition key is used to differentiate between items. A query operation in DynamoDB finds items based on primary key values. The name of the partition key attribute and a single value for that attribute must be provided. The query returns all items searched against that partition key value." }, { "code": null, "e": 26180, "s": 25956, "text": "A table say, Movies, with partition key as MovieID has been created already. No two items can have the same partition key. Add few items to query upon. A table has already been created with items in it. See the below image:" }, { "code": null, "e": 26423, "s": 26180, "text": "To query upon items in the table, select Query from the dropdown in the items tab. By default, a query will always have a partition key as one of the search filters. We can add one or more attributes to refine the search. See the below image:" }, { "code": null, "e": 26550, "s": 26423, "text": "In the above image we see that when we enter 50 for primary key MovieID, we obtain 1 record which is shown above in the image." }, { "code": null, "e": 27004, "s": 26550, "text": "To refine our search we can add one or more filters. In filter, we select an attribute and provide value against it. The query results returned is determined by a filter expression. All of the other results are discarded. A filter expression is applied before the results are returned, but after a Query finishes. Hence, a Query consumes the same amount of Read capacity, regardless of whether a filter expression is present or not. See the below image:" }, { "code": null, "e": 27175, "s": 27004, "text": "In the above image, we see that in the filter, Rating has been provided and the condition is that it should be greater than or equal to 8. Thus, we get one search result." }, { "code": null, "e": 27623, "s": 27175, "text": "The Query operation allows you to limit the number of items that it reads. To do this, set the Limit parameter to the desired number of items that you want. For example, suppose that you Query a table, with a limit value of 8, and without a filter expression. The Query result contains the first eight items from the table that match the key condition expression from the request. The limit can only be used in Amazon Command Line Interface (CLI)." }, { "code": null, "e": 27631, "s": 27623, "text": "Paging:" }, { "code": null, "e": 27909, "s": 27631, "text": "This feature is available on Amazon CLI (Command Line Interface). When data retrieved is larger than 1 MB in the result set, then the result set is divided into pages, each page containing up to 1 MB. For instance, if 3 MB data is retrieved then there will be at least 3 pages." }, { "code": null, "e": 27937, "s": 27909, "text": "Counting Item in ResultSet:" }, { "code": null, "e": 28156, "s": 27937, "text": "If the size of the Query result set is larger than 1 MB, ScannedCount and Count represent only a partial count of the total items. You need to perform multiple Query operations to retrieve all items in the result set. " }, { "code": null, "e": 28181, "s": 28156, "text": "Capacity Units Consumed:" }, { "code": null, "e": 28626, "s": 28181, "text": "A read capacity unit speaks for one strongly consistent read per second, or two eventually consistent reads per second, for an item up to the size of 4 KB. A scan operation does not return any data on how much the read capacity units are consumed. However, by specifying the ReturnConsumedCapacity parameter in a Scan request we can obtain this information or change the read capacity unit in the capacity tab of the table. See the below image:" }, { "code": null, "e": 28645, "s": 28626, "text": "Read Consistency: " }, { "code": null, "e": 29090, "s": 28645, "text": "By default, a scan operation performs eventually consistent reads. Meaning, the scan results might not include changes due to the recently completed PutItem or UpdateItem request. If required strong consistent reads, as of the time that the Scan begins, then set ConsistentRead parameter to true in the Scan request. By doing so, it ensures that all the write operations that completed before the Scan began are included in the Scan result set." }, { "code": null, "e": 29094, "s": 29090, "text": "AWS" }, { "code": null, "e": 29110, "s": 29094, "text": "Cloud-Computing" }, { "code": null, "e": 29119, "s": 29110, "text": "DynamoDB" }, { "code": null, "e": 29135, "s": 29119, "text": "DynamoDB-Basics" }, { "code": null, "e": 29142, "s": 29135, "text": "Picked" }, { "code": null, "e": 29162, "s": 29142, "text": "Amazon Web Services" }, { "code": null, "e": 29171, "s": 29162, "text": "DynamoDB" }, { "code": null, "e": 29269, "s": 29171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29278, "s": 29269, "text": "Comments" }, { "code": null, "e": 29291, "s": 29278, "text": "Old Comments" }, { "code": null, "e": 29326, "s": 29291, "text": "How to Install Python3 on AWS EC2?" }, { "code": null, "e": 29354, "s": 29326, "text": "Amazon S3 - Storage Classes" }, { "code": null, "e": 29394, "s": 29354, "text": "Amazon RDS - Working with Read Replicas" }, { "code": null, "e": 29448, "s": 29394, "text": "AWS DynamoDB - PartiQL Delete Statements For DynamoDB" }, { "code": null, "e": 29506, "s": 29448, "text": "AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX)" }, { "code": null, "e": 29558, "s": 29506, "text": "How to Mock AWS DynamoDB Services for Unit Testing?" }, { "code": null, "e": 29616, "s": 29558, "text": "AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX)" }, { "code": null, "e": 29646, "s": 29616, "text": "DynamoDB - Local Installation" }, { "code": null, "e": 29668, "s": 29646, "text": "DynamoDB - Data Types" } ]
How to find the difference in number of days between two date columns of an R data frame?
When dealing with date data, we often want to find the difference between dates if the data contains two or more date values. Same thing can be done for the two columns of an R data frame that contains dates but first we need to read those date columns in date format in case they are not recorded as date in R. The finding of difference in number of days can be done by using difftime function. Consider the below data − date1<-c("2020/02/02","2020/02/04","2020/02/05","2020/02/06","2020/02/08","2020/02/12","2020/02/13","2020/02/15","2020/02/16","2020/02/17","2020/02/18","2020/02/19","2020/02/20","2020/02/22","2020/02/23","2020/02/24","2020/02/25","2020/02/26","2020/02/27","2020/03/01") date1 [1] "2020/02/02" "2020/02/04" "2020/02/05" "2020/02/06" "2020/02/08" [6] "2020/02/12" "2020/02/13" "2020/02/15" "2020/02/16" "2020/02/17" [11] "2020/02/18" "2020/02/19" "2020/02/20" "2020/02/22" "2020/02/23" [16] "2020/02/24" "2020/02/25" "2020/02/26" "2020/02/27" "2020/03/01" date2<-c("2020/03/02","2020/03/03","2020/03/05","2020/03/06","2020/03/07","2020/03/08","2020/03/10","2020/03/13","2020/03/14","2020/03/15","2020/03/16","2020/03/17","2020/03/18","2020/03/20","2020/03/21","2020/03/22","2020/03/23","2020/03/24","2020/03/26","2020/03/27") date2 [1] "2020/03/02" "2020/03/03" "2020/03/05" "2020/03/06" "2020/03/07" [6] "2020/03/08" "2020/03/10" "2020/03/13" "2020/03/14" "2020/03/15" [11] "2020/03/16" "2020/03/17" "2020/03/18" "2020/03/20" "2020/03/21" [16] "2020/03/22" "2020/03/23" "2020/03/24" "2020/03/26" "2020/03/27" df<-data.frame(date1,date2) df date1 date2 1 2020/02/02 2020/03/02 2 2020/02/04 2020/03/03 3 2020/02/05 2020/03/05 4 2020/02/06 2020/03/06 5 2020/02/08 2020/03/07 6 2020/02/12 2020/03/08 7 2020/02/13 2020/03/10 8 2020/02/15 2020/03/13 9 2020/02/16 2020/03/14 10 2020/02/17 2020/03/15 11 2020/02/18 2020/03/16 12 2020/02/19 2020/03/17 13 2020/02/20 2020/03/18 14 2020/02/22 2020/03/20 15 2020/02/23 2020/03/21 16 2020/02/24 2020/03/22 17 2020/02/25 2020/03/23 18 2020/02/26 2020/03/24 19 2020/02/27 2020/03/26 20 2020/03/01 2020/03/27 Changing the format of date1 and date2 to date format − df$date1<-as.Date(df$date1,format="%Y/%m/%d") df$date2<-as.Date(df$date2,format="%Y/%m/%d") Finding the difference between two dates in number of days − df$Date_difference_in_days <-difftime(df$date1,df$date2,units=c("days")) df date1 date2 Date_difference_in_days 1 2020-02-02 2020-03-02 -29 days 2 2020-02-04 2020-03-03 -28 days 3 2020-02-05 2020-03-05 -29 days 4 2020-02-06 2020-03-06 -29 days 5 2020-02-08 2020-03-07 -28 days 6 2020-02-12 2020-03-08 -25 days 7 2020-02-13 2020-03-10 -26 days 8 2020-02-15 2020-03-13 -27 days 9 2020-02-16 2020-03-14 -27 days 10 2020-02-17 2020-03-15 -27 days 11 2020-02-18 2020-03-16 -27 days 12 2020-02-19 2020-03-17 -27 days 13 2020-02-20 2020-03-18 -27 days 14 2020-02-22 2020-03-20 -27 days 15 2020-02-23 2020-03-21 -27 days 16 2020-02-24 2020-03-22 -27 days 17 2020-02-25 2020-03-23 -27 days 18 2020-02-26 2020-03-24 -27 days 19 2020-02-27 2020-03-26 -28 days 20 2020-03-01 2020-03-27 -26 days
[ { "code": null, "e": 1458, "s": 1062, "text": "When dealing with date data, we often want to find the difference between dates if the data contains two or more date values. Same thing can be done for the two columns of an R data frame that contains dates but first we need to read those date columns in date format in case they are not recorded as date in R. The finding of difference in number of days can be done by using difftime function." }, { "code": null, "e": 1484, "s": 1458, "text": "Consider the below data −" }, { "code": null, "e": 2623, "s": 1484, "text": "date1<-c(\"2020/02/02\",\"2020/02/04\",\"2020/02/05\",\"2020/02/06\",\"2020/02/08\",\"2020/02/12\",\"2020/02/13\",\"2020/02/15\",\"2020/02/16\",\"2020/02/17\",\"2020/02/18\",\"2020/02/19\",\"2020/02/20\",\"2020/02/22\",\"2020/02/23\",\"2020/02/24\",\"2020/02/25\",\"2020/02/26\",\"2020/02/27\",\"2020/03/01\")\ndate1\n[1] \"2020/02/02\" \"2020/02/04\" \"2020/02/05\" \"2020/02/06\" \"2020/02/08\"\n[6] \"2020/02/12\" \"2020/02/13\" \"2020/02/15\" \"2020/02/16\" \"2020/02/17\"\n[11] \"2020/02/18\" \"2020/02/19\" \"2020/02/20\" \"2020/02/22\" \"2020/02/23\"\n[16] \"2020/02/24\" \"2020/02/25\" \"2020/02/26\" \"2020/02/27\" \"2020/03/01\"\ndate2<-c(\"2020/03/02\",\"2020/03/03\",\"2020/03/05\",\"2020/03/06\",\"2020/03/07\",\"2020/03/08\",\"2020/03/10\",\"2020/03/13\",\"2020/03/14\",\"2020/03/15\",\"2020/03/16\",\"2020/03/17\",\"2020/03/18\",\"2020/03/20\",\"2020/03/21\",\"2020/03/22\",\"2020/03/23\",\"2020/03/24\",\"2020/03/26\",\"2020/03/27\")\ndate2\n[1] \"2020/03/02\" \"2020/03/03\" \"2020/03/05\" \"2020/03/06\" \"2020/03/07\"\n[6] \"2020/03/08\" \"2020/03/10\" \"2020/03/13\" \"2020/03/14\" \"2020/03/15\"\n[11] \"2020/03/16\" \"2020/03/17\" \"2020/03/18\" \"2020/03/20\" \"2020/03/21\"\n[16] \"2020/03/22\" \"2020/03/23\" \"2020/03/24\" \"2020/03/26\" \"2020/03/27\"\ndf<-data.frame(date1,date2)\ndf" }, { "code": null, "e": 3126, "s": 2623, "text": "date1 date2\n1 2020/02/02 2020/03/02\n2 2020/02/04 2020/03/03\n3 2020/02/05 2020/03/05\n4 2020/02/06 2020/03/06\n5 2020/02/08 2020/03/07\n6 2020/02/12 2020/03/08\n7 2020/02/13 2020/03/10\n8 2020/02/15 2020/03/13\n9 2020/02/16 2020/03/14\n10 2020/02/17 2020/03/15\n11 2020/02/18 2020/03/16\n12 2020/02/19 2020/03/17\n13 2020/02/20 2020/03/18\n14 2020/02/22 2020/03/20\n15 2020/02/23 2020/03/21\n16 2020/02/24 2020/03/22\n17 2020/02/25 2020/03/23\n18 2020/02/26 2020/03/24\n19 2020/02/27 2020/03/26\n20 2020/03/01 2020/03/27" }, { "code": null, "e": 3182, "s": 3126, "text": "Changing the format of date1 and date2 to date format −" }, { "code": null, "e": 3274, "s": 3182, "text": "df$date1<-as.Date(df$date1,format=\"%Y/%m/%d\")\ndf$date2<-as.Date(df$date2,format=\"%Y/%m/%d\")" }, { "code": null, "e": 3335, "s": 3274, "text": "Finding the difference between two dates in number of days −" }, { "code": null, "e": 3411, "s": 3335, "text": "df$Date_difference_in_days <-difftime(df$date1,df$date2,units=c(\"days\"))\ndf" }, { "code": null, "e": 4118, "s": 3411, "text": "date1 date2 Date_difference_in_days\n1 2020-02-02 2020-03-02 -29 days\n2 2020-02-04 2020-03-03 -28 days\n3 2020-02-05 2020-03-05 -29 days\n4 2020-02-06 2020-03-06 -29 days\n5 2020-02-08 2020-03-07 -28 days\n6 2020-02-12 2020-03-08 -25 days\n7 2020-02-13 2020-03-10 -26 days\n8 2020-02-15 2020-03-13 -27 days\n9 2020-02-16 2020-03-14 -27 days\n10 2020-02-17 2020-03-15 -27 days\n11 2020-02-18 2020-03-16 -27 days\n12 2020-02-19 2020-03-17 -27 days\n13 2020-02-20 2020-03-18 -27 days\n14 2020-02-22 2020-03-20 -27 days\n15 2020-02-23 2020-03-21 -27 days\n16 2020-02-24 2020-03-22 -27 days\n17 2020-02-25 2020-03-23 -27 days\n18 2020-02-26 2020-03-24 -27 days\n19 2020-02-27 2020-03-26 -28 days\n20 2020-03-01 2020-03-27 -26 days" } ]
Temporal Fusion Transformer: Time Series Forecasting with Interpretability | by Nikos Kafritsas | Towards Data Science
First and foremost, let’s be clear: The era of tailoring a model to a single time series, either univariate or multivariate, is long gone. Nowadays, in the big data era, the creation of new data points is extremely cheap. Imagine a large electrical company having thousands of sensors that measure the power consumption of different entities (e.g. households, factories) or an investment portfolio with a large number of stocks, mutual funds, bonds and so on. In other words, time series could be multivariate, with different distributions and could be accompanied by additional exploratory variables. And of course don’t forget the usual suspects: missing data, trend, seasonality, volatility, drift and rare events! In order to create a competitive model in terms of forecasting power, all variables should be factored in, apart from historical data. Let’s take a step back and rethink what specifications a state-of-the-art, time series model should take into consideration: Obviously, the model should be applied on either single or multidimensional sequences.The model should account for multiple time series, ideally thousands of them. Do not confuse this with multivariate time series. It means time series with different distributions, trained on a single model.Apart from temporal data, the model should be able to use historical information which is unknown in the future. For example, if we are to create a model that forecasts air pollution level, we would like to be able to use humidity as an external time series, which is known only up to present time. For example, all autoregressive methods (e.g. ARIMA models) including Amazon’s DeepAR[1] suffer from this limitation.External static variables which are non-temporal should also be taken into account. For example, weather forecasting in different cities (city is the static variable).The model should be extremely adaptive. Time sequences can be fairly complex or noisy, while others can be simply modeled with seasonal naive predictors. Ideally, the model should be able to differentiate these cases.Multi-step prediction functionality is also a must. One-step ahead prediction models which recursively feed predictions could also work. However, keep in mind that for long range predictions the errors start to rack up.In many cases, a simple prediction of the target variable is not enough. The algorithm should be able to output prediction intervals as well, which reflect the prediction uncertainty.The ideal model is easy to use and can be deployed seamlessly in a production environment.Last but not least, the past few years ‘black box models’ have started losing popularity. Explainability has now become a top priority, especially in production. In some cases, explainability is favored over accuracy. Obviously, the model should be applied on either single or multidimensional sequences. The model should account for multiple time series, ideally thousands of them. Do not confuse this with multivariate time series. It means time series with different distributions, trained on a single model. Apart from temporal data, the model should be able to use historical information which is unknown in the future. For example, if we are to create a model that forecasts air pollution level, we would like to be able to use humidity as an external time series, which is known only up to present time. For example, all autoregressive methods (e.g. ARIMA models) including Amazon’s DeepAR[1] suffer from this limitation. External static variables which are non-temporal should also be taken into account. For example, weather forecasting in different cities (city is the static variable). The model should be extremely adaptive. Time sequences can be fairly complex or noisy, while others can be simply modeled with seasonal naive predictors. Ideally, the model should be able to differentiate these cases. Multi-step prediction functionality is also a must. One-step ahead prediction models which recursively feed predictions could also work. However, keep in mind that for long range predictions the errors start to rack up. In many cases, a simple prediction of the target variable is not enough. The algorithm should be able to output prediction intervals as well, which reflect the prediction uncertainty. The ideal model is easy to use and can be deployed seamlessly in a production environment. Last but not least, the past few years ‘black box models’ have started losing popularity. Explainability has now become a top priority, especially in production. In some cases, explainability is favored over accuracy. Temporal Fusion Transformer (TFT) is an attention-based Deep Neural Network, optimized for great performance and interpretability. Before delving into the specifics of this cool architecture, we briefly describe its advantages and novelties : Rich features: TFT supports 3 types of features: i) temporal data with known inputs into the future ii) temporal data known only up to the present and iii) exogenous categorical/static variables, also known as time-invariant features.Heterogeneous time series: Supports training on multiple time series, coming from different distributions. To achieve that, the TFT architecture splits processing into 2 parts: local processing which focuses on the characteristics of specific events and global processing which captures the collective characteristics of all time series.Multi-horizon forecasting: Supports multi-step predictions. Apart from the actual prediction, TFT also outputs prediction intervals, by using the quantile loss function.Interpretability: At its core, TFT is a transformer-based architecture. By taking advantage of self-attention, this model presents a novel Muti Head attention mechanism which when analyzed, provides extra insight on feature importances. For example, Multi-Horizon Quantile Recurrent Forecaster (MQRNN)[3] is another DNN implementation with good performance but does not provide any insight regarding feature interpretability.High Performance: During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM)[4].Documentation: Although it is a relatively new model, there are already open source implementations of TFT both in Tensorflow and Python. Rich features: TFT supports 3 types of features: i) temporal data with known inputs into the future ii) temporal data known only up to the present and iii) exogenous categorical/static variables, also known as time-invariant features. Heterogeneous time series: Supports training on multiple time series, coming from different distributions. To achieve that, the TFT architecture splits processing into 2 parts: local processing which focuses on the characteristics of specific events and global processing which captures the collective characteristics of all time series. Multi-horizon forecasting: Supports multi-step predictions. Apart from the actual prediction, TFT also outputs prediction intervals, by using the quantile loss function. Interpretability: At its core, TFT is a transformer-based architecture. By taking advantage of self-attention, this model presents a novel Muti Head attention mechanism which when analyzed, provides extra insight on feature importances. For example, Multi-Horizon Quantile Recurrent Forecaster (MQRNN)[3] is another DNN implementation with good performance but does not provide any insight regarding feature interpretability. High Performance: During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM)[4]. Documentation: Although it is a relatively new model, there are already open source implementations of TFT both in Tensorflow and Python. Figure 1 shows the top-level architecture of TFT: While this image may look intimidating, the model is actually quite easy to understand. For a given timestep t , a lookback window k , and a τmax step ahead window, where t⋹ [t-k..t+τmax], the model takes as input: i) Observed past inputs x in the time period [t-k..t], future known inputs x in the time period [t+1..t+τmax] and a set of static variables s (if exist). The target variable y also spans the time window [t+1..t+τmax]. Next, we are going to describe step-by-step all the individual components and how they work together. Gated Residual Network (GRN) Figure 2 shows a component proposed by the paper, called Gated Residual Network (GRN), which is used as a basic block numerous time throughout TFT. The key points for this network are the following: It has two dense layers and two types of activation functions called ELU (Exponential Linear Unit) and GLU (Gated Linear Units). GLU was first used in the Gated Convolutional Networks [5] architecture for selecting the most important features for predicting the next word. In fact, both of these activation functions help the network understand which input transformations are simple and which require more complex modeling. The final output passes through standard Layer Normalization. The GRN also contain a residual connection, meaning that the network could learn, if necessary, to skip the input entirely. In some cases, depending where the GRN is situated, the network can also make use of static variables. Variable Selection Network (VSN) This component is shown in Figure 3. As its name implies, it functions as a feature selection mechanism. Remember what we said earlier: Not all time series are complex. The model should be able to distinguish insightful features from the noisy ones. Also, since there are 3 types of inputs, TFT uses 3 instances of the Variable Selection Network. Thus, each instance has different weights (notice the different colors of each VSN unit in Figure 1). Naturally, the VSN utilizes GRN under the hood for its filtering capabilities. This is how it works: At time t the flattened vector of all past inputs (called Ξ_t) of the corresponding lookback period is fed through a GRN unit (in blue) and then a softmax function, producing a normalized vector of weights u. Moreover, each feature passes through its own GRN, which leads to the creation of a processed vector called ξ_t, one for every variable. Finally, an output is calculated as a linear combination of ξ_t and u. Note that the each feature has its own GRN, but the GRN for each feature is the same across all time steps during the same lookback period. The VSN for static variables does not take into account the context vector c LSTM Encoder Decoder Layer The LSTM Encoder Decoder Layer is part of many implementations, especially in NLP. It is displayed in Figure 1. This component serves two purposes: Up to this point, the input has passed through VSN and has properly encoded and weighted the features. However, since our input is time-series data, the model should also make sense of the time/sequential ordering. Consequently, the first goal of the LSTM Encoder Decoder module is to produce context-aware embeddings, which are called φ. This is similar to the positional encoding used in the classic Transformer where we add sine and cosine signals. But why the authors choose the LSTM Encoder Decoder instead? Because the model should account for all types of input. The known inputs are fed into the encoder, while the unknown future inputs are fed into the decoder. And what about the static information? Is it possible to just merge the context aware embeddings produced by LSTM Encoder Decoder with the context vectors c of static variables? Unfortunately, this would be inaccurate because we will mix temporal with static information. The correct way to do this is by applying a method used by [6] that correctly conditions the input based on exogenous data: Specifically, instead of setting the initial h_0 hidden state as well as the cell state c_0of the LSTM to 0, they are initialized with the c_h and c_c vectors respectively (which are produced from the static covariate encoder of TFT). As a consequence, the final context-aware embeddings φ will be properly conditioned on the exogenous information, without altering the temporal dynamics. Interpretable Multi-Head Attention This is the last part of the TFT architecture. In this step, the familiar self-attention mechanism[7] is applied which helps the model learn long range dependencies across different time steps. All Transformer-based architectures leverage Attention to learn complex dependencies among the input data. If you are not familiar with the Attention-based implementations, check this source[8] (this is the best online source for understanding the Transformer model). TFT proposes a novel interpretable Multi-Head Attention mechanism, which contrary to the standard implementation, provides feature interpretability. In the original architecture there are different ‘heads’ (Query/Key/Value weight matrices) in order to to project the input into different representation subspaces. The drawback of this approach is that the weight matrices have no common ground and thus cannot be interpreted. TFT’s multi-head attention adds a new matrix/grouping such that the different heads share some weights which then can be interpreted in terms seasonality analysis. Quantile Regression In numerous applications where time series forecasting is involved, the prediction of the target variable is not enough. It is equally important to estimate the uncertainty of the prediction(s). Usually, this comes in the form of prediction intervals. Should we decide to include prediction intervals in the output, linear regression and the mean square error become inapplicable. Standard linear regression uses the method of ordinary least squares (OLS) to calculate the conditional mean of the target variable across different values of the features. Prediction intervals from the OLS solution are based on the assumption that the residuals have constant variance, which is not always the case. On the other hand, quantile regression, which is an extension of Standard linear regression, estimates the conditional median of the target variable and can be used when assumptions of linear regression are not met. Apart from the median, quantile regression can also calculate the 0.25 and 0.75 quantiles (or any percentile for that matter) which means the model has the ability to output a prediction interval around the actual prediction. Figure 4 shows an example of how quantiles/percentiles look like in a regression problem: Given y and ŷ the actual value and the prediction respectively, and q a value for the quantile between 0 and 1, the quantile loss function is defined as: As the value of q increases, overestimations are penalized by a larger factor compared to underestimations. For instance, for q equal to 0.75, overestimations will be penalized by a factor of 0.75, and underestimations by a factor of 0.25. That’s how the prediction intervals are created. The TFT implementation is trained by minimizing the quantile loss summed across q ⋹ [0.1, 0.5, 0.9]. This is done for benchmarking purposes, in order to match the experimental configuration used by other popular models. Also, it goes without saying that the use of quantile loss is not exclusive -other types of loss functions can be used such MSE, MAPE and so on. In the original paper, the TFT model is compared against other popular time series models such as DeepAR, ARIMA and so on. Some of the datasets which the authors use for benchmarking are: Electricity Load Diagrams Dataset (UCI) [9] PEM-SF Traffic Dataset (UCI) [9] Favorita Grocery Sales (Kaggle) [10] For more information about which configurations/hyperparameters are used for each dataset, check the original paper[2]. During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM) Also, the authors kindly provide an open-source implementation of TFT in Tensorflow 1.x along with the corresponding hyperparameter configuration regarding each dataset for reproducibility purposes. Moreover, you can also find a modified version for Tensorflow 2.x here. Let’s create a minimum working example using the Electricity Load Diagrams Dataset, which we will refer to as electricity for short . This dataset contains the electrical consumption (in kW) of 370 consumers. The datapoints are sampled every 15 minutes. Before proceeding to forecasting, the dataset is first preprocessed: Time granularity becomes hourly.Using the date information, we create the following (numerical) features: hour, day of week, and hours from start.The categorical_id is an id for each consumer.The target variable is power_usage.The dataset is split into train, validation and test sets.The train dataset is normalized. Specifically, numerical variables (including the target variable) are standardized(z-normalization) and the single categorical feature is label-encoded. It is imperative to understand that normalization takes place separately for each time-series/consumer, because time-sequences have different characteristics (mean and variance). Scalers are also kept for reverting predictions back to their original values. Time granularity becomes hourly. Using the date information, we create the following (numerical) features: hour, day of week, and hours from start. The categorical_id is an id for each consumer. The target variable is power_usage. The dataset is split into train, validation and test sets. The train dataset is normalized. Specifically, numerical variables (including the target variable) are standardized(z-normalization) and the single categorical feature is label-encoded. It is imperative to understand that normalization takes place separately for each time-series/consumer, because time-sequences have different characteristics (mean and variance). Scalers are also kept for reverting predictions back to their original values. The goal is to forecast the power usage of the next day(1*24 hours), by using the past week (7*24 hours). For this example, we will use the updated version of TFT for Tensorflow 2.x. You could quickly setup a minimum working example in Conda: # Download TFT. Kudos to greatwhiz for making TFT compatible to TF # 2.x!!git clone https://github.com/greatwhiz/tft_tf2.git# Install any missing libraries in Conda environment!pip install pyunpack!pip install wget The implementation also contains scripts for downloading and preprocessing the aforementioned datasets: For the electricity dataset, execute: # The structure of the command is:# python3 -m script_download_data $EXPT $OUTPUT_FOLDER!python3 tft_tf2/script_download_data.py electricity electricity_dataset where electricity_dataset is the folder where the preprocessed data will be stored. This is what the preprocessed dataset looks like: Not all of these variables are considered for training though. The model will make use of the variables which we discussed above. Finally, execute the training script: # The structure of the command is:# python3 -m script_train_fixed_params $EXPT $OUTPUT_FOLDER $USE_GPU!python3 tft_tf2/script_train_fixed_params.py electricity electricity_dataset ‘yes’ By default, this script runs in testing mode, which means the model will train for only 1 epoch and use only 100 and 10 training and validation instances respectively. To initiate a complete training with the optimal hyperparameters found in the original paper, in the script_train_fixed_params.py set use_testing_mode=True. For a complete training, the model will take approximately 7–8 hours on Colab with GPU enabled. TFT is also available in PyTorch. Check this comprehensive tutorial for more info. One of the strongest points regarding TFT is explainability. In the context of a time series problem, explainability makes sense in many situations. Feature-Wise First of all, TFT attempts to calculate the impact of each feature by taking into account the robustness of predictions. Feature importance can be measured by analyzing the weights u of all Variable Selection Network modules across the entire test set. For the Electricity dataset in Table 1 we have: All feature scores take values between 0 and 1. The ID variable plays a major role since it distinguishes one time-series from another. Next is Hour of Day, which is expected since power consumption follows specific patterns throughout the day. Seasonality Using the interpretable Multi-Head Attention layer, we can take it one step further and calculate the ‘persistent temporal patterns’. More specifically, the attention weights from this layer can reveal which time-steps during the lookback period are the most important. As a consequence, visualization of those weights reveals the most prominent seasonalities. For instance, in Figure 5 we have: where a(t,n,1) is the attention score for horizon equal to 1 (same as one-step ahead) and n⋹[-(7*24)..0]. In other words, the plot clearly displays that the dataset exhibits a daily seasonal pattern. To sum up, Temporal Fusion Transformer is a versatile model with high performance. The architecture of TFT has incorporated numerous key advancements from the Deep Learning domain, while at the same time proposes some novelties of its own. The most fundamental of its features however is the ability to provide interpretable insights in terms of forecasting. Besides, this is one of the directions where Deep Learning is headed in the future, according to Gartner. [1] D. Salinas et al., DeepAR: Probabilistic forecasting with autoregressive recurrent networks, International Journal of Forecasting (2019). [2] Bryan Lim et al., Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting, September 2020 [3] R. Wen et al., A Multi-Horizon Quantile Recurrent Forecaster, NIPS, 2017 [4] S. S. Rangapuram, et al., Deep state space models for time series forecasting, NIPS, 2018. [5] Y. Dauphin et al., Language modeling with gated convolutional networks, ICML, 2017 [6] Andrej Karpathy, Li Fei-Fei, Deep Visual-Semantic Alignments for Generating Image Descriptions [7] A. Vaswani et al. Attention Is All You Need, Jun 2017 [8] J. Alammar, The Illustrated Transformer [9] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository . Irvine, CA: University of California, School of Information and Computer Science. [10] Favorita Grocery Sales Forecasting, Kaggle, Licence CC0: Public Domain
[ { "code": null, "e": 311, "s": 172, "text": "First and foremost, let’s be clear: The era of tailoring a model to a single time series, either univariate or multivariate, is long gone." }, { "code": null, "e": 1025, "s": 311, "text": "Nowadays, in the big data era, the creation of new data points is extremely cheap. Imagine a large electrical company having thousands of sensors that measure the power consumption of different entities (e.g. households, factories) or an investment portfolio with a large number of stocks, mutual funds, bonds and so on. In other words, time series could be multivariate, with different distributions and could be accompanied by additional exploratory variables. And of course don’t forget the usual suspects: missing data, trend, seasonality, volatility, drift and rare events! In order to create a competitive model in terms of forecasting power, all variables should be factored in, apart from historical data." }, { "code": null, "e": 1150, "s": 1025, "text": "Let’s take a step back and rethink what specifications a state-of-the-art, time series model should take into consideration:" }, { "code": null, "e": 2952, "s": 1150, "text": "Obviously, the model should be applied on either single or multidimensional sequences.The model should account for multiple time series, ideally thousands of them. Do not confuse this with multivariate time series. It means time series with different distributions, trained on a single model.Apart from temporal data, the model should be able to use historical information which is unknown in the future. For example, if we are to create a model that forecasts air pollution level, we would like to be able to use humidity as an external time series, which is known only up to present time. For example, all autoregressive methods (e.g. ARIMA models) including Amazon’s DeepAR[1] suffer from this limitation.External static variables which are non-temporal should also be taken into account. For example, weather forecasting in different cities (city is the static variable).The model should be extremely adaptive. Time sequences can be fairly complex or noisy, while others can be simply modeled with seasonal naive predictors. Ideally, the model should be able to differentiate these cases.Multi-step prediction functionality is also a must. One-step ahead prediction models which recursively feed predictions could also work. However, keep in mind that for long range predictions the errors start to rack up.In many cases, a simple prediction of the target variable is not enough. The algorithm should be able to output prediction intervals as well, which reflect the prediction uncertainty.The ideal model is easy to use and can be deployed seamlessly in a production environment.Last but not least, the past few years ‘black box models’ have started losing popularity. Explainability has now become a top priority, especially in production. In some cases, explainability is favored over accuracy." }, { "code": null, "e": 3039, "s": 2952, "text": "Obviously, the model should be applied on either single or multidimensional sequences." }, { "code": null, "e": 3246, "s": 3039, "text": "The model should account for multiple time series, ideally thousands of them. Do not confuse this with multivariate time series. It means time series with different distributions, trained on a single model." }, { "code": null, "e": 3663, "s": 3246, "text": "Apart from temporal data, the model should be able to use historical information which is unknown in the future. For example, if we are to create a model that forecasts air pollution level, we would like to be able to use humidity as an external time series, which is known only up to present time. For example, all autoregressive methods (e.g. ARIMA models) including Amazon’s DeepAR[1] suffer from this limitation." }, { "code": null, "e": 3831, "s": 3663, "text": "External static variables which are non-temporal should also be taken into account. For example, weather forecasting in different cities (city is the static variable)." }, { "code": null, "e": 4049, "s": 3831, "text": "The model should be extremely adaptive. Time sequences can be fairly complex or noisy, while others can be simply modeled with seasonal naive predictors. Ideally, the model should be able to differentiate these cases." }, { "code": null, "e": 4269, "s": 4049, "text": "Multi-step prediction functionality is also a must. One-step ahead prediction models which recursively feed predictions could also work. However, keep in mind that for long range predictions the errors start to rack up." }, { "code": null, "e": 4453, "s": 4269, "text": "In many cases, a simple prediction of the target variable is not enough. The algorithm should be able to output prediction intervals as well, which reflect the prediction uncertainty." }, { "code": null, "e": 4544, "s": 4453, "text": "The ideal model is easy to use and can be deployed seamlessly in a production environment." }, { "code": null, "e": 4762, "s": 4544, "text": "Last but not least, the past few years ‘black box models’ have started losing popularity. Explainability has now become a top priority, especially in production. In some cases, explainability is favored over accuracy." }, { "code": null, "e": 5005, "s": 4762, "text": "Temporal Fusion Transformer (TFT) is an attention-based Deep Neural Network, optimized for great performance and interpretability. Before delving into the specifics of this cool architecture, we briefly describe its advantages and novelties :" }, { "code": null, "e": 6489, "s": 5005, "text": "Rich features: TFT supports 3 types of features: i) temporal data with known inputs into the future ii) temporal data known only up to the present and iii) exogenous categorical/static variables, also known as time-invariant features.Heterogeneous time series: Supports training on multiple time series, coming from different distributions. To achieve that, the TFT architecture splits processing into 2 parts: local processing which focuses on the characteristics of specific events and global processing which captures the collective characteristics of all time series.Multi-horizon forecasting: Supports multi-step predictions. Apart from the actual prediction, TFT also outputs prediction intervals, by using the quantile loss function.Interpretability: At its core, TFT is a transformer-based architecture. By taking advantage of self-attention, this model presents a novel Muti Head attention mechanism which when analyzed, provides extra insight on feature importances. For example, Multi-Horizon Quantile Recurrent Forecaster (MQRNN)[3] is another DNN implementation with good performance but does not provide any insight regarding feature interpretability.High Performance: During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM)[4].Documentation: Although it is a relatively new model, there are already open source implementations of TFT both in Tensorflow and Python." }, { "code": null, "e": 6724, "s": 6489, "text": "Rich features: TFT supports 3 types of features: i) temporal data with known inputs into the future ii) temporal data known only up to the present and iii) exogenous categorical/static variables, also known as time-invariant features." }, { "code": null, "e": 7062, "s": 6724, "text": "Heterogeneous time series: Supports training on multiple time series, coming from different distributions. To achieve that, the TFT architecture splits processing into 2 parts: local processing which focuses on the characteristics of specific events and global processing which captures the collective characteristics of all time series." }, { "code": null, "e": 7232, "s": 7062, "text": "Multi-horizon forecasting: Supports multi-step predictions. Apart from the actual prediction, TFT also outputs prediction intervals, by using the quantile loss function." }, { "code": null, "e": 7658, "s": 7232, "text": "Interpretability: At its core, TFT is a transformer-based architecture. By taking advantage of self-attention, this model presents a novel Muti Head attention mechanism which when analyzed, provides extra insight on feature importances. For example, Multi-Horizon Quantile Recurrent Forecaster (MQRNN)[3] is another DNN implementation with good performance but does not provide any insight regarding feature interpretability." }, { "code": null, "e": 7840, "s": 7658, "text": "High Performance: During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM)[4]." }, { "code": null, "e": 7978, "s": 7840, "text": "Documentation: Although it is a relatively new model, there are already open source implementations of TFT both in Tensorflow and Python." }, { "code": null, "e": 8028, "s": 7978, "text": "Figure 1 shows the top-level architecture of TFT:" }, { "code": null, "e": 8116, "s": 8028, "text": "While this image may look intimidating, the model is actually quite easy to understand." }, { "code": null, "e": 8461, "s": 8116, "text": "For a given timestep t , a lookback window k , and a τmax step ahead window, where t⋹ [t-k..t+τmax], the model takes as input: i) Observed past inputs x in the time period [t-k..t], future known inputs x in the time period [t+1..t+τmax] and a set of static variables s (if exist). The target variable y also spans the time window [t+1..t+τmax]." }, { "code": null, "e": 8563, "s": 8461, "text": "Next, we are going to describe step-by-step all the individual components and how they work together." }, { "code": null, "e": 8592, "s": 8563, "text": "Gated Residual Network (GRN)" }, { "code": null, "e": 8791, "s": 8592, "text": "Figure 2 shows a component proposed by the paper, called Gated Residual Network (GRN), which is used as a basic block numerous time throughout TFT. The key points for this network are the following:" }, { "code": null, "e": 9216, "s": 8791, "text": "It has two dense layers and two types of activation functions called ELU (Exponential Linear Unit) and GLU (Gated Linear Units). GLU was first used in the Gated Convolutional Networks [5] architecture for selecting the most important features for predicting the next word. In fact, both of these activation functions help the network understand which input transformations are simple and which require more complex modeling." }, { "code": null, "e": 9505, "s": 9216, "text": "The final output passes through standard Layer Normalization. The GRN also contain a residual connection, meaning that the network could learn, if necessary, to skip the input entirely. In some cases, depending where the GRN is situated, the network can also make use of static variables." }, { "code": null, "e": 9538, "s": 9505, "text": "Variable Selection Network (VSN)" }, { "code": null, "e": 9987, "s": 9538, "text": "This component is shown in Figure 3. As its name implies, it functions as a feature selection mechanism. Remember what we said earlier: Not all time series are complex. The model should be able to distinguish insightful features from the noisy ones. Also, since there are 3 types of inputs, TFT uses 3 instances of the Variable Selection Network. Thus, each instance has different weights (notice the different colors of each VSN unit in Figure 1)." }, { "code": null, "e": 10088, "s": 9987, "text": "Naturally, the VSN utilizes GRN under the hood for its filtering capabilities. This is how it works:" }, { "code": null, "e": 10297, "s": 10088, "text": "At time t the flattened vector of all past inputs (called Ξ_t) of the corresponding lookback period is fed through a GRN unit (in blue) and then a softmax function, producing a normalized vector of weights u." }, { "code": null, "e": 10434, "s": 10297, "text": "Moreover, each feature passes through its own GRN, which leads to the creation of a processed vector called ξ_t, one for every variable." }, { "code": null, "e": 10505, "s": 10434, "text": "Finally, an output is calculated as a linear combination of ξ_t and u." }, { "code": null, "e": 10645, "s": 10505, "text": "Note that the each feature has its own GRN, but the GRN for each feature is the same across all time steps during the same lookback period." }, { "code": null, "e": 10722, "s": 10645, "text": "The VSN for static variables does not take into account the context vector c" }, { "code": null, "e": 10749, "s": 10722, "text": "LSTM Encoder Decoder Layer" }, { "code": null, "e": 10897, "s": 10749, "text": "The LSTM Encoder Decoder Layer is part of many implementations, especially in NLP. It is displayed in Figure 1. This component serves two purposes:" }, { "code": null, "e": 11410, "s": 10897, "text": "Up to this point, the input has passed through VSN and has properly encoded and weighted the features. However, since our input is time-series data, the model should also make sense of the time/sequential ordering. Consequently, the first goal of the LSTM Encoder Decoder module is to produce context-aware embeddings, which are called φ. This is similar to the positional encoding used in the classic Transformer where we add sine and cosine signals. But why the authors choose the LSTM Encoder Decoder instead?" }, { "code": null, "e": 11746, "s": 11410, "text": "Because the model should account for all types of input. The known inputs are fed into the encoder, while the unknown future inputs are fed into the decoder. And what about the static information? Is it possible to just merge the context aware embeddings produced by LSTM Encoder Decoder with the context vectors c of static variables?" }, { "code": null, "e": 12353, "s": 11746, "text": "Unfortunately, this would be inaccurate because we will mix temporal with static information. The correct way to do this is by applying a method used by [6] that correctly conditions the input based on exogenous data: Specifically, instead of setting the initial h_0 hidden state as well as the cell state c_0of the LSTM to 0, they are initialized with the c_h and c_c vectors respectively (which are produced from the static covariate encoder of TFT). As a consequence, the final context-aware embeddings φ will be properly conditioned on the exogenous information, without altering the temporal dynamics." }, { "code": null, "e": 12388, "s": 12353, "text": "Interpretable Multi-Head Attention" }, { "code": null, "e": 12582, "s": 12388, "text": "This is the last part of the TFT architecture. In this step, the familiar self-attention mechanism[7] is applied which helps the model learn long range dependencies across different time steps." }, { "code": null, "e": 12850, "s": 12582, "text": "All Transformer-based architectures leverage Attention to learn complex dependencies among the input data. If you are not familiar with the Attention-based implementations, check this source[8] (this is the best online source for understanding the Transformer model)." }, { "code": null, "e": 13440, "s": 12850, "text": "TFT proposes a novel interpretable Multi-Head Attention mechanism, which contrary to the standard implementation, provides feature interpretability. In the original architecture there are different ‘heads’ (Query/Key/Value weight matrices) in order to to project the input into different representation subspaces. The drawback of this approach is that the weight matrices have no common ground and thus cannot be interpreted. TFT’s multi-head attention adds a new matrix/grouping such that the different heads share some weights which then can be interpreted in terms seasonality analysis." }, { "code": null, "e": 13460, "s": 13440, "text": "Quantile Regression" }, { "code": null, "e": 13841, "s": 13460, "text": "In numerous applications where time series forecasting is involved, the prediction of the target variable is not enough. It is equally important to estimate the uncertainty of the prediction(s). Usually, this comes in the form of prediction intervals. Should we decide to include prediction intervals in the output, linear regression and the mean square error become inapplicable." }, { "code": null, "e": 14690, "s": 13841, "text": "Standard linear regression uses the method of ordinary least squares (OLS) to calculate the conditional mean of the target variable across different values of the features. Prediction intervals from the OLS solution are based on the assumption that the residuals have constant variance, which is not always the case. On the other hand, quantile regression, which is an extension of Standard linear regression, estimates the conditional median of the target variable and can be used when assumptions of linear regression are not met. Apart from the median, quantile regression can also calculate the 0.25 and 0.75 quantiles (or any percentile for that matter) which means the model has the ability to output a prediction interval around the actual prediction. Figure 4 shows an example of how quantiles/percentiles look like in a regression problem:" }, { "code": null, "e": 14845, "s": 14690, "text": "Given y and ŷ the actual value and the prediction respectively, and q a value for the quantile between 0 and 1, the quantile loss function is defined as:" }, { "code": null, "e": 15134, "s": 14845, "text": "As the value of q increases, overestimations are penalized by a larger factor compared to underestimations. For instance, for q equal to 0.75, overestimations will be penalized by a factor of 0.75, and underestimations by a factor of 0.25. That’s how the prediction intervals are created." }, { "code": null, "e": 15499, "s": 15134, "text": "The TFT implementation is trained by minimizing the quantile loss summed across q ⋹ [0.1, 0.5, 0.9]. This is done for benchmarking purposes, in order to match the experimental configuration used by other popular models. Also, it goes without saying that the use of quantile loss is not exclusive -other types of loss functions can be used such MSE, MAPE and so on." }, { "code": null, "e": 15687, "s": 15499, "text": "In the original paper, the TFT model is compared against other popular time series models such as DeepAR, ARIMA and so on. Some of the datasets which the authors use for benchmarking are:" }, { "code": null, "e": 15731, "s": 15687, "text": "Electricity Load Diagrams Dataset (UCI) [9]" }, { "code": null, "e": 15764, "s": 15731, "text": "PEM-SF Traffic Dataset (UCI) [9]" }, { "code": null, "e": 15801, "s": 15764, "text": "Favorita Grocery Sales (Kaggle) [10]" }, { "code": null, "e": 15921, "s": 15801, "text": "For more information about which configurations/hyperparameters are used for each dataset, check the original paper[2]." }, { "code": null, "e": 16081, "s": 15921, "text": "During benchmarks, TFT outperformed traditional statistical models (ARIMA) as well as DNN-based models such as DeepAR, MQRNN and Deep Space-State Models (DSSM)" }, { "code": null, "e": 16352, "s": 16081, "text": "Also, the authors kindly provide an open-source implementation of TFT in Tensorflow 1.x along with the corresponding hyperparameter configuration regarding each dataset for reproducibility purposes. Moreover, you can also find a modified version for Tensorflow 2.x here." }, { "code": null, "e": 16675, "s": 16352, "text": "Let’s create a minimum working example using the Electricity Load Diagrams Dataset, which we will refer to as electricity for short . This dataset contains the electrical consumption (in kW) of 370 consumers. The datapoints are sampled every 15 minutes. Before proceeding to forecasting, the dataset is first preprocessed:" }, { "code": null, "e": 17404, "s": 16675, "text": "Time granularity becomes hourly.Using the date information, we create the following (numerical) features: hour, day of week, and hours from start.The categorical_id is an id for each consumer.The target variable is power_usage.The dataset is split into train, validation and test sets.The train dataset is normalized. Specifically, numerical variables (including the target variable) are standardized(z-normalization) and the single categorical feature is label-encoded. It is imperative to understand that normalization takes place separately for each time-series/consumer, because time-sequences have different characteristics (mean and variance). Scalers are also kept for reverting predictions back to their original values." }, { "code": null, "e": 17437, "s": 17404, "text": "Time granularity becomes hourly." }, { "code": null, "e": 17552, "s": 17437, "text": "Using the date information, we create the following (numerical) features: hour, day of week, and hours from start." }, { "code": null, "e": 17599, "s": 17552, "text": "The categorical_id is an id for each consumer." }, { "code": null, "e": 17635, "s": 17599, "text": "The target variable is power_usage." }, { "code": null, "e": 17694, "s": 17635, "text": "The dataset is split into train, validation and test sets." }, { "code": null, "e": 18138, "s": 17694, "text": "The train dataset is normalized. Specifically, numerical variables (including the target variable) are standardized(z-normalization) and the single categorical feature is label-encoded. It is imperative to understand that normalization takes place separately for each time-series/consumer, because time-sequences have different characteristics (mean and variance). Scalers are also kept for reverting predictions back to their original values." }, { "code": null, "e": 18244, "s": 18138, "text": "The goal is to forecast the power usage of the next day(1*24 hours), by using the past week (7*24 hours)." }, { "code": null, "e": 18381, "s": 18244, "text": "For this example, we will use the updated version of TFT for Tensorflow 2.x. You could quickly setup a minimum working example in Conda:" }, { "code": null, "e": 18596, "s": 18381, "text": "# Download TFT. Kudos to greatwhiz for making TFT compatible to TF # 2.x!!git clone https://github.com/greatwhiz/tft_tf2.git# Install any missing libraries in Conda environment!pip install pyunpack!pip install wget" }, { "code": null, "e": 18738, "s": 18596, "text": "The implementation also contains scripts for downloading and preprocessing the aforementioned datasets: For the electricity dataset, execute:" }, { "code": null, "e": 18899, "s": 18738, "text": "# The structure of the command is:# python3 -m script_download_data $EXPT $OUTPUT_FOLDER!python3 tft_tf2/script_download_data.py electricity electricity_dataset" }, { "code": null, "e": 19033, "s": 18899, "text": "where electricity_dataset is the folder where the preprocessed data will be stored. This is what the preprocessed dataset looks like:" }, { "code": null, "e": 19163, "s": 19033, "text": "Not all of these variables are considered for training though. The model will make use of the variables which we discussed above." }, { "code": null, "e": 19201, "s": 19163, "text": "Finally, execute the training script:" }, { "code": null, "e": 19387, "s": 19201, "text": "# The structure of the command is:# python3 -m script_train_fixed_params $EXPT $OUTPUT_FOLDER $USE_GPU!python3 tft_tf2/script_train_fixed_params.py electricity electricity_dataset ‘yes’" }, { "code": null, "e": 19808, "s": 19387, "text": "By default, this script runs in testing mode, which means the model will train for only 1 epoch and use only 100 and 10 training and validation instances respectively. To initiate a complete training with the optimal hyperparameters found in the original paper, in the script_train_fixed_params.py set use_testing_mode=True. For a complete training, the model will take approximately 7–8 hours on Colab with GPU enabled." }, { "code": null, "e": 19891, "s": 19808, "text": "TFT is also available in PyTorch. Check this comprehensive tutorial for more info." }, { "code": null, "e": 20040, "s": 19891, "text": "One of the strongest points regarding TFT is explainability. In the context of a time series problem, explainability makes sense in many situations." }, { "code": null, "e": 20053, "s": 20040, "text": "Feature-Wise" }, { "code": null, "e": 20354, "s": 20053, "text": "First of all, TFT attempts to calculate the impact of each feature by taking into account the robustness of predictions. Feature importance can be measured by analyzing the weights u of all Variable Selection Network modules across the entire test set. For the Electricity dataset in Table 1 we have:" }, { "code": null, "e": 20599, "s": 20354, "text": "All feature scores take values between 0 and 1. The ID variable plays a major role since it distinguishes one time-series from another. Next is Hour of Day, which is expected since power consumption follows specific patterns throughout the day." }, { "code": null, "e": 20611, "s": 20599, "text": "Seasonality" }, { "code": null, "e": 21007, "s": 20611, "text": "Using the interpretable Multi-Head Attention layer, we can take it one step further and calculate the ‘persistent temporal patterns’. More specifically, the attention weights from this layer can reveal which time-steps during the lookback period are the most important. As a consequence, visualization of those weights reveals the most prominent seasonalities. For instance, in Figure 5 we have:" }, { "code": null, "e": 21207, "s": 21007, "text": "where a(t,n,1) is the attention score for horizon equal to 1 (same as one-step ahead) and n⋹[-(7*24)..0]. In other words, the plot clearly displays that the dataset exhibits a daily seasonal pattern." }, { "code": null, "e": 21672, "s": 21207, "text": "To sum up, Temporal Fusion Transformer is a versatile model with high performance. The architecture of TFT has incorporated numerous key advancements from the Deep Learning domain, while at the same time proposes some novelties of its own. The most fundamental of its features however is the ability to provide interpretable insights in terms of forecasting. Besides, this is one of the directions where Deep Learning is headed in the future, according to Gartner." }, { "code": null, "e": 21814, "s": 21672, "text": "[1] D. Salinas et al., DeepAR: Probabilistic forecasting with autoregressive recurrent networks, International Journal of Forecasting (2019)." }, { "code": null, "e": 21937, "s": 21814, "text": "[2] Bryan Lim et al., Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting, September 2020" }, { "code": null, "e": 22014, "s": 21937, "text": "[3] R. Wen et al., A Multi-Horizon Quantile Recurrent Forecaster, NIPS, 2017" }, { "code": null, "e": 22109, "s": 22014, "text": "[4] S. S. Rangapuram, et al., Deep state space models for time series forecasting, NIPS, 2018." }, { "code": null, "e": 22196, "s": 22109, "text": "[5] Y. Dauphin et al., Language modeling with gated convolutional networks, ICML, 2017" }, { "code": null, "e": 22295, "s": 22196, "text": "[6] Andrej Karpathy, Li Fei-Fei, Deep Visual-Semantic Alignments for Generating Image Descriptions" }, { "code": null, "e": 22353, "s": 22295, "text": "[7] A. Vaswani et al. Attention Is All You Need, Jun 2017" }, { "code": null, "e": 22397, "s": 22353, "text": "[8] J. Alammar, The Illustrated Transformer" }, { "code": null, "e": 22547, "s": 22397, "text": "[9] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository . Irvine, CA: University of California, School of Information and Computer Science." } ]
Parent and Child classes having same data member in Java
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java. Following is an example − Live Demo class Demo_base { int value = 1000; Demo_base() { System.out.println("This is the base class constructor"); } } class Demo_inherits extends Demo_base { int value = 10; Demo_inherits() { System.out.println("This is the inherited class constructor"); } } public class Demo { public static void main(String[] args) { Demo_inherits my_inherited_obj = new Demo_inherits(); System.out.println("In the main class, inherited class object has been created"); System.out.println("Reference of inherited class type :" + my_inherited_obj.value); Demo_base my_obj = my_inherited_obj; System.out.println("In the main class, parent class object has been created"); System.out.println("Reference of base class type : " + my_obj.value); } } This is the base class constructor This is the inherited class constructor In the main class, inherited class object has been created Reference of inherited class type :10 In the main class, parent class object has been created Reference of base class type : 1000 A class named ‘Demo_base’ contains an integer value and a constructor that prints relevant message. Another class named ‘Demo_inherits’ becomes the child class to parent class ‘Demo_base’. This means, the ‘Demo_inherits’ class extends to the base class ‘Demo_base’. In this class, another value for the same variable is defined, and a constructor of the child class is defined with relevant message to be printed on the screen. A class named Demo contains the main function, where an instance of the child class is created, and its associated integer value is printed on the screen. A similar process is done for the parent class, by creating an instance and accessing its associated value and printing it on the screen.
[ { "code": null, "e": 1374, "s": 1062, "text": "The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java." }, { "code": null, "e": 1400, "s": 1374, "text": "Following is an example −" }, { "code": null, "e": 1411, "s": 1400, "text": " Live Demo" }, { "code": null, "e": 2207, "s": 1411, "text": "class Demo_base {\n int value = 1000;\n Demo_base() {\n System.out.println(\"This is the base class constructor\");\n }\n}\nclass Demo_inherits extends Demo_base {\n int value = 10;\n Demo_inherits() {\n System.out.println(\"This is the inherited class constructor\");\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n Demo_inherits my_inherited_obj = new Demo_inherits();\n System.out.println(\"In the main class, inherited class object has been created\");\n System.out.println(\"Reference of inherited class type :\" + my_inherited_obj.value);\n Demo_base my_obj = my_inherited_obj;\n System.out.println(\"In the main class, parent class object has been created\");\n System.out.println(\"Reference of base class type : \" + my_obj.value);\n }\n}" }, { "code": null, "e": 2471, "s": 2207, "text": "This is the base class constructor\nThis is the inherited class constructor\nIn the main class, inherited class object has been created\nReference of inherited class type :10\nIn the main class, parent class object has been created\nReference of base class type : 1000" }, { "code": null, "e": 2737, "s": 2471, "text": "A class named ‘Demo_base’ contains an integer value and a constructor that prints relevant message. Another class named ‘Demo_inherits’ becomes the child class to parent class ‘Demo_base’. This means, the ‘Demo_inherits’ class extends to the base class ‘Demo_base’." }, { "code": null, "e": 3192, "s": 2737, "text": "In this class, another value for the same variable is defined, and a constructor of the child class is defined with relevant message to be printed on the screen. A class named Demo contains the main function, where an instance of the child class is created, and its associated integer value is printed on the screen. A similar process is done for the parent class, by creating an instance and accessing its associated value and printing it on the screen." } ]
How to get all property values of a JavaScript Object (without knowing the keys) ? - GeeksforGeeks
28 Nov, 2019 Method 1: Using Object.values() Method: The Object.values() method is used to return an array of the object’s own enumerable property values. The array can be looped using a for-loop to get all the values of the object. Therefore, the keys are not required to be known to get all the property values. Syntax: let valuesArray = Object.values(exampleObj); for (let value of valuesArray) { console.log(value);} Example: <!DOCTYPE html><html><head> <title> How to get all properties values of a Javascript Object (without knowing the keys)? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to get all properties values of a Javascript Object (without knowing the keys)? </b> <p> Click on the button to get all properties values. </p> <p> Check the console for the output </p> <button onclick="getValues()"> Get Property Values </button> <script type="text/javascript"> function getValues() { let exampleObj = { language: "C++", designedby: "Bjarne Stroustrup", year: "1979" }; let valuesArray = Object.values(exampleObj); for (let value of valuesArray) { console.log(value); } } </script></body></html> Output: Before clicking the button: After clicking the button: Method 2: Extracting the keys to access the properties: The Object.keys() method is used to return an array of objects own enumerable property names. The forEach() method is used on this array to access each of the keys. The value of each property can be accessed using the keys with an array notation of the object.Therefore, the keys are not required to be known beforehand to get all the property values. Syntax: let objKeys = Object.keys(exampleObj); objKeys.forEach(key => { let value = exampleObj[key]; console.log(value);}); Example: <!DOCTYPE html><html><head> <title> How to get all properties values of a Javascript Object (without knowing the keys)? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to get all properties values of a Javascript Object (without knowing the keys)? </b> <p> Click on the button to get all properties values. </p> <p> Check the console for the output </p> <button onclick="getValues()"> Get Property Values </button> <script type="text/javascript"> function getValues() { let exampleObj = { language: "C++", designedby: "Bjarne Stroustrup", year: "1979" }; let objKeys = Object.keys(exampleObj); objKeys.forEach(key => { let value = exampleObj[key]; console.log(value); }); } </script></body></html> Output: Before clicking the button: After clicking the button: 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. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux 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": 24780, "s": 24752, "text": "\n28 Nov, 2019" }, { "code": null, "e": 25081, "s": 24780, "text": "Method 1: Using Object.values() Method: The Object.values() method is used to return an array of the object’s own enumerable property values. The array can be looped using a for-loop to get all the values of the object. Therefore, the keys are not required to be known to get all the property values." }, { "code": null, "e": 25089, "s": 25081, "text": "Syntax:" }, { "code": "let valuesArray = Object.values(exampleObj); for (let value of valuesArray) { console.log(value);}", "e": 25192, "s": 25089, "text": null }, { "code": null, "e": 25201, "s": 25192, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to get all properties values of a Javascript Object (without knowing the keys)? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to get all properties values of a Javascript Object (without knowing the keys)? </b> <p> Click on the button to get all properties values. </p> <p> Check the console for the output </p> <button onclick=\"getValues()\"> Get Property Values </button> <script type=\"text/javascript\"> function getValues() { let exampleObj = { language: \"C++\", designedby: \"Bjarne Stroustrup\", year: \"1979\" }; let valuesArray = Object.values(exampleObj); for (let value of valuesArray) { console.log(value); } } </script></body></html>", "e": 26020, "s": 25201, "text": null }, { "code": null, "e": 26028, "s": 26020, "text": "Output:" }, { "code": null, "e": 26056, "s": 26028, "text": "Before clicking the button:" }, { "code": null, "e": 26083, "s": 26056, "text": "After clicking the button:" }, { "code": null, "e": 26491, "s": 26083, "text": "Method 2: Extracting the keys to access the properties: The Object.keys() method is used to return an array of objects own enumerable property names. The forEach() method is used on this array to access each of the keys. The value of each property can be accessed using the keys with an array notation of the object.Therefore, the keys are not required to be known beforehand to get all the property values." }, { "code": null, "e": 26499, "s": 26491, "text": "Syntax:" }, { "code": "let objKeys = Object.keys(exampleObj); objKeys.forEach(key => { let value = exampleObj[key]; console.log(value);});", "e": 26624, "s": 26499, "text": null }, { "code": null, "e": 26633, "s": 26624, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to get all properties values of a Javascript Object (without knowing the keys)? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to get all properties values of a Javascript Object (without knowing the keys)? </b> <p> Click on the button to get all properties values. </p> <p> Check the console for the output </p> <button onclick=\"getValues()\"> Get Property Values </button> <script type=\"text/javascript\"> function getValues() { let exampleObj = { language: \"C++\", designedby: \"Bjarne Stroustrup\", year: \"1979\" }; let objKeys = Object.keys(exampleObj); objKeys.forEach(key => { let value = exampleObj[key]; console.log(value); }); } </script></body></html>", "e": 27487, "s": 26633, "text": null }, { "code": null, "e": 27495, "s": 27487, "text": "Output:" }, { "code": null, "e": 27523, "s": 27495, "text": "Before clicking the button:" }, { "code": null, "e": 27550, "s": 27523, "text": "After clicking the button:" }, { "code": null, "e": 27566, "s": 27550, "text": "JavaScript-Misc" }, { "code": null, "e": 27573, "s": 27566, "text": "Picked" }, { "code": null, "e": 27584, "s": 27573, "text": "JavaScript" }, { "code": null, "e": 27601, "s": 27584, "text": "Web Technologies" }, { "code": null, "e": 27628, "s": 27601, "text": "Web technologies Questions" }, { "code": null, "e": 27726, "s": 27628, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27771, "s": 27726, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27832, "s": 27771, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27904, "s": 27832, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27956, "s": 27904, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28002, "s": 27956, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28044, "s": 28002, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28077, "s": 28044, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28120, "s": 28077, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28182, "s": 28120, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
ML | Rainfall prediction using Linear regression - GeeksforGeeks
12 Jun, 2019 Prerequisites: Linear regression Rainfall Prediction is the application of science and technology to predict the amount of rainfall over a region. It is important to exactly determine the rainfall for effective use of water resources, crop productivity and pre-planning of water structures. In this article, we will use Linear Regression to predict the amount of rainfall. Linear Regression tells us how many inches of rainfall we can expect. The dataset is a public weather dataset from Austin, Texas available on Kaggle. The dataset can be found here. Data Cleaning:Data comes in all forms, most of it being very messy and unstructured. They rarely come ready to use. Datasets, large and small, come with a variety of issues- invalid fields, missing and additional values, and values that are in forms different from the one we require. In order to bring it to workable or structured form, we need to “clean” our data, and make it ready to use. Some common cleaning includes parsing, converting to one-hot, removing unnecessary data, etc. In our case, our data has some days where some factors weren’t recorded. And the rainfall in cm was marked as T if there was trace precipitation. Our algorithm requires numbers, so we can’t work with alphabets popping up in our data. so we need to clean the data before applying it on our model Cleaning the data in Python: # importing librariesimport pandas as pdimport numpy as np # read the data in a pandas dataframedata = pd.read_csv("austin_weather.csv") # drop or delete the unnecessary columns in the data.data = data.drop(['Events', 'Date', 'SeaLevelPressureHighInches', 'SeaLevelPressureLowInches'], axis = 1) # some values have 'T' which denotes trace rainfall# we need to replace all occurrences of T with 0# so that we can use the data in our modeldata = data.replace('T', 0.0) # the data also contains '-' which indicates no # or NIL. This means that data is not available# we need to replace these values as well.data = data.replace('-', 0.0) # save the data in a csv filedata.to_csv('austin_final.csv') Once the data is cleaned, it can be used as an input to our Linear regression model. Linear regression is a linear approach to form a relationship between a dependent variable and many independent explanatory variables. This is done by plotting a line that fits our scatter plot the best, ie, with the least errors. This gives value predictions, ie, how much, by substituting the independent values in the line equation. We will use Scikit-learn’s linear regression model to train our dataset. Once the model is trained, we can give our own inputs for the various columns such as temperature, dew point, pressure, etc. to predict the weather based on these attributes. # importing librariesimport pandas as pdimport numpy as npimport sklearn as skfrom sklearn.linear_model import LinearRegressionimport matplotlib.pyplot as plt # read the cleaned datadata = pd.read_csv("austin_final.csv") # the features or the 'x' values of the data# these columns are used to train the model# the last column, i.e, precipitation column # will serve as the label X = data.drop(['PrecipitationSumInches'], axis = 1) # the output or the label.Y = data['PrecipitationSumInches']# reshaping it into a 2-D vectorY = Y.values.reshape(-1, 1) # consider a random day in the dataset# we shall plot a graph and observe this# dayday_index = 798days = [i for i in range(Y.size)] # initialize a linear regression classifierclf = LinearRegression()# train the classifier with our # input data.clf.fit(X, Y) # give a sample input to test our model# this is a 2-D vector that contains values# for each column in the dataset.inp = np.array([[74], [60], [45], [67], [49], [43], [33], [45], [57], [29.68], [10], [7], [2], [0], [20], [4], [31]])inp = inp.reshape(1, -1) # print the output.print('The precipitation in inches for the input is:', clf.predict(inp)) # plot a graph of the precipitation levels# versus the total number of days.# one day, which is in red, is# tracked here. It has a precipitation# of approx. 2 inches.print("the precipitation trend graph: ")plt.scatter(days, Y, color = 'g')plt.scatter(days[day_index], Y[day_index], color ='r')plt.title("Precipitation level")plt.xlabel("Days")plt.ylabel("Precipitation in inches") plt.show()x_vis = X.filter(['TempAvgF', 'DewPointAvgF', 'HumidityAvgPercent', 'SeaLevelPressureAvgInches', 'VisibilityAvgMiles', 'WindAvgMPH'], axis = 1) # plot a graph with a few features (x values)# against the precipitation or rainfall to observe# the trends print("Precipitation vs selected attributes graph: ") for i in range(x_vis.columns.size): plt.subplot(3, 2, i + 1) plt.scatter(days, x_vis[x_vis.columns.values[i][:100]], color = 'g') plt.scatter(days[day_index], x_vis[x_vis.columns.values[i]][day_index], color ='r') plt.title(x_vis.columns.values[i]) plt.show() Output : The precipitation in inches for the input is: [[1.33868402]] The precipitation trend graph: Precipitation vs selected attributes graph: A day (in red) having precipitation of about 2 inches is tracked across multiple parameters (the same day is tracker across multiple features such as temperature, pressure, etc). The x-axis denotes the days and the y-axis denotes the magnitude of the feature such as temperature, pressure, etc. From the graph, it can be observed that rainfall can be expected to be high when the temperature is high and humidity is high. data-science Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Decision tree implementation Search Algorithms in AI Decision Tree Introduction with example ML | Underfitting and Overfitting Elbow Method for optimal value of k in KMeans Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24674, "s": 24646, "text": "\n12 Jun, 2019" }, { "code": null, "e": 24707, "s": 24674, "text": "Prerequisites: Linear regression" }, { "code": null, "e": 24965, "s": 24707, "text": "Rainfall Prediction is the application of science and technology to predict the amount of rainfall over a region. It is important to exactly determine the rainfall for effective use of water resources, crop productivity and pre-planning of water structures." }, { "code": null, "e": 25117, "s": 24965, "text": "In this article, we will use Linear Regression to predict the amount of rainfall. Linear Regression tells us how many inches of rainfall we can expect." }, { "code": null, "e": 25228, "s": 25117, "text": "The dataset is a public weather dataset from Austin, Texas available on Kaggle. The dataset can be found here." }, { "code": null, "e": 25715, "s": 25228, "text": "Data Cleaning:Data comes in all forms, most of it being very messy and unstructured. They rarely come ready to use. Datasets, large and small, come with a variety of issues- invalid fields, missing and additional values, and values that are in forms different from the one we require. In order to bring it to workable or structured form, we need to “clean” our data, and make it ready to use. Some common cleaning includes parsing, converting to one-hot, removing unnecessary data, etc." }, { "code": null, "e": 26010, "s": 25715, "text": "In our case, our data has some days where some factors weren’t recorded. And the rainfall in cm was marked as T if there was trace precipitation. Our algorithm requires numbers, so we can’t work with alphabets popping up in our data. so we need to clean the data before applying it on our model" }, { "code": null, "e": 26039, "s": 26010, "text": "Cleaning the data in Python:" }, { "code": "# importing librariesimport pandas as pdimport numpy as np # read the data in a pandas dataframedata = pd.read_csv(\"austin_weather.csv\") # drop or delete the unnecessary columns in the data.data = data.drop(['Events', 'Date', 'SeaLevelPressureHighInches', 'SeaLevelPressureLowInches'], axis = 1) # some values have 'T' which denotes trace rainfall# we need to replace all occurrences of T with 0# so that we can use the data in our modeldata = data.replace('T', 0.0) # the data also contains '-' which indicates no # or NIL. This means that data is not available# we need to replace these values as well.data = data.replace('-', 0.0) # save the data in a csv filedata.to_csv('austin_final.csv')", "e": 26757, "s": 26039, "text": null }, { "code": null, "e": 27179, "s": 26757, "text": "Once the data is cleaned, it can be used as an input to our Linear regression model. Linear regression is a linear approach to form a relationship between a dependent variable and many independent explanatory variables. This is done by plotting a line that fits our scatter plot the best, ie, with the least errors. This gives value predictions, ie, how much, by substituting the independent values in the line equation." }, { "code": null, "e": 27427, "s": 27179, "text": "We will use Scikit-learn’s linear regression model to train our dataset. Once the model is trained, we can give our own inputs for the various columns such as temperature, dew point, pressure, etc. to predict the weather based on these attributes." }, { "code": "# importing librariesimport pandas as pdimport numpy as npimport sklearn as skfrom sklearn.linear_model import LinearRegressionimport matplotlib.pyplot as plt # read the cleaned datadata = pd.read_csv(\"austin_final.csv\") # the features or the 'x' values of the data# these columns are used to train the model# the last column, i.e, precipitation column # will serve as the label X = data.drop(['PrecipitationSumInches'], axis = 1) # the output or the label.Y = data['PrecipitationSumInches']# reshaping it into a 2-D vectorY = Y.values.reshape(-1, 1) # consider a random day in the dataset# we shall plot a graph and observe this# dayday_index = 798days = [i for i in range(Y.size)] # initialize a linear regression classifierclf = LinearRegression()# train the classifier with our # input data.clf.fit(X, Y) # give a sample input to test our model# this is a 2-D vector that contains values# for each column in the dataset.inp = np.array([[74], [60], [45], [67], [49], [43], [33], [45], [57], [29.68], [10], [7], [2], [0], [20], [4], [31]])inp = inp.reshape(1, -1) # print the output.print('The precipitation in inches for the input is:', clf.predict(inp)) # plot a graph of the precipitation levels# versus the total number of days.# one day, which is in red, is# tracked here. It has a precipitation# of approx. 2 inches.print(\"the precipitation trend graph: \")plt.scatter(days, Y, color = 'g')plt.scatter(days[day_index], Y[day_index], color ='r')plt.title(\"Precipitation level\")plt.xlabel(\"Days\")plt.ylabel(\"Precipitation in inches\") plt.show()x_vis = X.filter(['TempAvgF', 'DewPointAvgF', 'HumidityAvgPercent', 'SeaLevelPressureAvgInches', 'VisibilityAvgMiles', 'WindAvgMPH'], axis = 1) # plot a graph with a few features (x values)# against the precipitation or rainfall to observe# the trends print(\"Precipitation vs selected attributes graph: \") for i in range(x_vis.columns.size): plt.subplot(3, 2, i + 1) plt.scatter(days, x_vis[x_vis.columns.values[i][:100]], color = 'g') plt.scatter(days[day_index], x_vis[x_vis.columns.values[i]][day_index], color ='r') plt.title(x_vis.columns.values[i]) plt.show()", "e": 29699, "s": 27427, "text": null }, { "code": null, "e": 29708, "s": 29699, "text": "Output :" }, { "code": null, "e": 29801, "s": 29708, "text": "The precipitation in inches for the input is: [[1.33868402]]\n\nThe precipitation trend graph:" }, { "code": null, "e": 29845, "s": 29801, "text": "Precipitation vs selected attributes graph:" }, { "code": null, "e": 30267, "s": 29845, "text": "A day (in red) having precipitation of about 2 inches is tracked across multiple parameters (the same day is tracker across multiple features such as temperature, pressure, etc). The x-axis denotes the days and the y-axis denotes the magnitude of the feature such as temperature, pressure, etc. From the graph, it can be observed that rainfall can be expected to be high when the temperature is high and humidity is high." }, { "code": null, "e": 30280, "s": 30267, "text": "data-science" }, { "code": null, "e": 30297, "s": 30280, "text": "Machine Learning" }, { "code": null, "e": 30304, "s": 30297, "text": "Python" }, { "code": null, "e": 30321, "s": 30304, "text": "Machine Learning" }, { "code": null, "e": 30419, "s": 30321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30457, "s": 30419, "text": "Python | Decision tree implementation" }, { "code": null, "e": 30481, "s": 30457, "text": "Search Algorithms in AI" }, { "code": null, "e": 30521, "s": 30481, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 30555, "s": 30521, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 30601, "s": 30555, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 30629, "s": 30601, "text": "Read JSON file using Python" }, { "code": null, "e": 30679, "s": 30629, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30701, "s": 30679, "text": "Python map() function" } ]
Conflict Serializability in DBMS - GeeksforGeeks
28 Jun, 2021 As discussed in Concurrency control, serial schedules have less resource utilization and low throughput. To improve it, two or more transactions are run concurrently. But concurrency of transactions may lead to inconsistency in database. To avoid this, we need to check whether these concurrent schedules are serializable or not. Conflict Serializable: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Conflicting operations: Two operations are said to be conflicting if all conditions satisfy: They belong to different transactions They operate on the same data item At Least one of them is a write operation Example: – Conflicting operations pair (R1(A), W2(A)) because they belong to two different transactions on same data item A and one of them is write operation. Similarly, (W1(A), W2(A)) and (W1(A), R2(A)) pairs are also conflicting. On the other hand, (R1(A), W2(B)) pair is non-conflicting because they operate on different data item. Similarly, ((W1(A), W2(B)) pair is non-conflicting. Consider the following schedule: S1: R1(A), W1(A), R2(A), W2(A), R1(B), W1(B), R2(B), W2(B) If Oi and Oj are two operations in a transaction and Oi< Oj (Oi is executed before Oj), same order will follow in the schedule as well. Using this property, we can get two transactions of schedule S1 as: T1: R1(A), W1(A), R1(B), W1(B) T2: R2(A), W2(A), R2(B), W2(B) Possible Serial Schedules are: T1->T2 or T2->T1 -> Swapping non-conflicting operations R2(A) and R1(B) in S1, the schedule becomes, S11: R1(A), W1(A), R1(B), W2(A), R2(A), W1(B), R2(B), W2(B) -> Similarly, swapping non-conflicting operations W2(A) and W1(B) in S11, the schedule becomes, S12: R1(A), W1(A), R1(B), W1(B), R2(A), W2(A), R2(B), W2(B) S12 is a serial schedule in which all operations of T1 are performed before starting any operation of T2. Since S has been transformed into a serial schedule S12 by swapping non-conflicting operations of S1, S1 is conflict serializable. Let us take another Schedule: S2: R2(A), W2(A), R1(A), W1(A), R1(B), W1(B), R2(B), W2(B) Two transactions will be: T1: R1(A), W1(A), R1(B), W1(B) T2: R2(A), W2(A), R2(B), W2(B) Possible Serial Schedules are: T1->T2 or T2->T1 Original Schedule is: S2: R2(A), W2(A), R1(A), W1(A), R1(B), W1(B), R2(B), W2(B) Swapping non-conflicting operations R1(A) and R2(B) in S2, the schedule becomes, S21: R2(A), W2(A), R2(B), W1(A), R1(B), W1(B), R1(A), W2(B) Similarly, swapping non-conflicting operations W1(A) and W2(B) in S21, the schedule becomes, S22: R2(A), W2(A), R2(B), W2(B), R1(B), W1(B), R1(A), W1(A) In schedule S22, all operations of T2 are performed first, but operations of T1 are not in order (order should be R1(A), W1(A), R1(B), W1(B)). So S2 is not conflict serializable. Conflict Equivalent: Two schedules are said to be conflict equivalent when one can be transformed to another by swapping non-conflicting operations. In the example discussed above, S11 is conflict equivalent to S1 (S1 can be converted to S11 by swapping non-conflicting operations). Similarly, S11 is conflict equivalent to S12 and so on. Note 1: Although S2 is not conflict serializable, but still it is conflict equivalent to S21 and S21 because S2 can be converted to S21 and S22 by swapping non-conflicting operations. Note 2: The schedule which is conflict serializable is always conflict equivalent to one of the serial schedule. S1 schedule discussed above (which is conflict serializable) is equivalent to serial schedule (T1->T2). Question: Consider the following schedules involving two transactions. Which one of the following statement is true? S1: R1(X) R1(Y) R2(X) R2(Y) W2(Y) W1(X) S2: R1(X) R2(X) R2(Y) W2(Y) R1(Y) W1(X) Both S1 and S2 are conflict serializable Only S1 is conflict serializable Only S2 is conflict serializable None [GATE 2007] Solution: Two transactions of given schedules are: T1: R1(X) R1(Y) W1(X) T2: R2(X) R2(Y) W2(Y) Let us first check serializability of S1: S1: R1(X) R1(Y) R2(X) R2(Y) W2(Y) W1(X) To convert it to a serial schedule, we have to swap non-conflicting operations so that S1 becomes equivalent to serial schedule T1->T2 or T2->T1. In this case, to convert it to a serial schedule, we must have to swap R2(X) and W1(X) but they are conflicting. So S1 can’t be converted to a serial schedule. Now, let us check serializability of S2: S2: R1(X) R2(X) R2(Y) W2(Y) R1(Y) W1(X) Swapping non conflicting operations R1(X) and R2(X) of S2, we get S2’: R2(X) R1(X) R2(Y) W2(Y) R1(Y) W1(X) Again, swapping non conflicting operations R1(X) and R2(Y) of S2’, we get S2’’: R2(X) R2(Y) R1(X) W2(Y) R1(Y) W1(X) Again, swapping non conflicting operations R1(X) and W2(Y) of S2’’, we get S2’’’: R2(X) R2(Y) W2(Y) R1(X) R1(Y) W1(X) which is equivalent to a serial schedule T2->T1. So, correct option is C. Only S2 is conflict serializable. Related Article: View Serializability Precedence Graph For Testing Conflict Serializability Article contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SonalSrivastava02 harshit kumar 6 DBMS-Transactions and Concurrency Control DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? SQL Trigger | Student Database Difference between Clustered and Non-clustered index SQL | Views CTE in SQL Difference between DDL and DML in DBMS Third Normal Form (3NF) SQL Interview Questions
[ { "code": null, "e": 29626, "s": 29598, "text": "\n28 Jun, 2021" }, { "code": null, "e": 29956, "s": 29626, "text": "As discussed in Concurrency control, serial schedules have less resource utilization and low throughput. To improve it, two or more transactions are run concurrently. But concurrency of transactions may lead to inconsistency in database. To avoid this, we need to check whether these concurrent schedules are serializable or not." }, { "code": null, "e": 30110, "s": 29956, "text": "Conflict Serializable: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations." }, { "code": null, "e": 30204, "s": 30110, "text": "Conflicting operations: Two operations are said to be conflicting if all conditions satisfy: " }, { "code": null, "e": 30242, "s": 30204, "text": "They belong to different transactions" }, { "code": null, "e": 30277, "s": 30242, "text": "They operate on the same data item" }, { "code": null, "e": 30319, "s": 30277, "text": "At Least one of them is a write operation" }, { "code": null, "e": 30330, "s": 30319, "text": "Example: –" }, { "code": null, "e": 30479, "s": 30330, "text": "Conflicting operations pair (R1(A), W2(A)) because they belong to two different transactions on same data item A and one of them is write operation." }, { "code": null, "e": 30552, "s": 30479, "text": "Similarly, (W1(A), W2(A)) and (W1(A), R2(A)) pairs are also conflicting." }, { "code": null, "e": 30655, "s": 30552, "text": "On the other hand, (R1(A), W2(B)) pair is non-conflicting because they operate on different data item." }, { "code": null, "e": 30707, "s": 30655, "text": "Similarly, ((W1(A), W2(B)) pair is non-conflicting." }, { "code": null, "e": 30741, "s": 30707, "text": "Consider the following schedule: " }, { "code": null, "e": 30802, "s": 30741, "text": "S1: R1(A), W1(A), R2(A), W2(A), R1(B), W1(B), R2(B), W2(B)\n\n" }, { "code": null, "e": 31008, "s": 30802, "text": "If Oi and Oj are two operations in a transaction and Oi< Oj (Oi is executed before Oj), same order will follow in the schedule as well. Using this property, we can get two transactions of schedule S1 as: " }, { "code": null, "e": 31072, "s": 31008, "text": "T1: R1(A), W1(A), R1(B), W1(B)\nT2: R2(A), W2(A), R2(B), W2(B)\n\n" }, { "code": null, "e": 31121, "s": 31072, "text": "Possible Serial Schedules are: T1->T2 or T2->T1 " }, { "code": null, "e": 31206, "s": 31121, "text": "-> Swapping non-conflicting operations R2(A) and R1(B) in S1, the schedule becomes, " }, { "code": null, "e": 31268, "s": 31206, "text": "S11: R1(A), W1(A), R1(B), W2(A), R2(A), W1(B), R2(B), W2(B)\n\n" }, { "code": null, "e": 31365, "s": 31268, "text": "-> Similarly, swapping non-conflicting operations W2(A) and W1(B) in S11, the schedule becomes, " }, { "code": null, "e": 31427, "s": 31365, "text": "S12: R1(A), W1(A), R1(B), W1(B), R2(A), W2(A), R2(B), W2(B)\n\n" }, { "code": null, "e": 31664, "s": 31427, "text": "S12 is a serial schedule in which all operations of T1 are performed before starting any operation of T2. Since S has been transformed into a serial schedule S12 by swapping non-conflicting operations of S1, S1 is conflict serializable." }, { "code": null, "e": 31695, "s": 31664, "text": "Let us take another Schedule: " }, { "code": null, "e": 31756, "s": 31695, "text": "S2: R2(A), W2(A), R1(A), W1(A), R1(B), W1(B), R2(B), W2(B)\n\n" }, { "code": null, "e": 31784, "s": 31756, "text": "Two transactions will be: " }, { "code": null, "e": 31848, "s": 31784, "text": "T1: R1(A), W1(A), R1(B), W1(B)\nT2: R2(A), W2(A), R2(B), W2(B)\n\n" }, { "code": null, "e": 31897, "s": 31848, "text": "Possible Serial Schedules are: T1->T2 or T2->T1 " }, { "code": null, "e": 31921, "s": 31897, "text": "Original Schedule is: " }, { "code": null, "e": 31982, "s": 31921, "text": "S2: R2(A), W2(A), R1(A), W1(A), R1(B), W1(B), R2(B), W2(B)\n\n" }, { "code": null, "e": 32064, "s": 31982, "text": "Swapping non-conflicting operations R1(A) and R2(B) in S2, the schedule becomes, " }, { "code": null, "e": 32126, "s": 32064, "text": "S21: R2(A), W2(A), R2(B), W1(A), R1(B), W1(B), R1(A), W2(B)\n\n" }, { "code": null, "e": 32221, "s": 32126, "text": "Similarly, swapping non-conflicting operations W1(A) and W2(B) in S21, the schedule becomes, " }, { "code": null, "e": 32283, "s": 32221, "text": "S22: R2(A), W2(A), R2(B), W2(B), R1(B), W1(B), R1(A), W1(A)\n\n" }, { "code": null, "e": 32462, "s": 32283, "text": "In schedule S22, all operations of T2 are performed first, but operations of T1 are not in order (order should be R1(A), W1(A), R1(B), W1(B)). So S2 is not conflict serializable." }, { "code": null, "e": 32801, "s": 32462, "text": "Conflict Equivalent: Two schedules are said to be conflict equivalent when one can be transformed to another by swapping non-conflicting operations. In the example discussed above, S11 is conflict equivalent to S1 (S1 can be converted to S11 by swapping non-conflicting operations). Similarly, S11 is conflict equivalent to S12 and so on." }, { "code": null, "e": 32985, "s": 32801, "text": "Note 1: Although S2 is not conflict serializable, but still it is conflict equivalent to S21 and S21 because S2 can be converted to S21 and S22 by swapping non-conflicting operations." }, { "code": null, "e": 33202, "s": 32985, "text": "Note 2: The schedule which is conflict serializable is always conflict equivalent to one of the serial schedule. S1 schedule discussed above (which is conflict serializable) is equivalent to serial schedule (T1->T2)." }, { "code": null, "e": 33320, "s": 33202, "text": "Question: Consider the following schedules involving two transactions. Which one of the following statement is true? " }, { "code": null, "e": 33401, "s": 33320, "text": "S1: R1(X) R1(Y) R2(X) R2(Y) W2(Y) W1(X) S2: R1(X) R2(X) R2(Y) W2(Y) R1(Y) W1(X) " }, { "code": null, "e": 33442, "s": 33401, "text": "Both S1 and S2 are conflict serializable" }, { "code": null, "e": 33475, "s": 33442, "text": "Only S1 is conflict serializable" }, { "code": null, "e": 33508, "s": 33475, "text": "Only S2 is conflict serializable" }, { "code": null, "e": 33513, "s": 33508, "text": "None" }, { "code": null, "e": 33525, "s": 33513, "text": "[GATE 2007]" }, { "code": null, "e": 33577, "s": 33525, "text": "Solution: Two transactions of given schedules are: " }, { "code": null, "e": 33625, "s": 33577, "text": " T1: R1(X) R1(Y) W1(X)\n T2: R2(X) R2(Y) W2(Y)\n\n" }, { "code": null, "e": 33668, "s": 33625, "text": "Let us first check serializability of S1: " }, { "code": null, "e": 33710, "s": 33668, "text": "S1: R1(X) R1(Y) R2(X) R2(Y) W2(Y) W1(X)\n\n" }, { "code": null, "e": 34017, "s": 33710, "text": "To convert it to a serial schedule, we have to swap non-conflicting operations so that S1 becomes equivalent to serial schedule T1->T2 or T2->T1. In this case, to convert it to a serial schedule, we must have to swap R2(X) and W1(X) but they are conflicting. So S1 can’t be converted to a serial schedule. " }, { "code": null, "e": 34059, "s": 34017, "text": "Now, let us check serializability of S2: " }, { "code": null, "e": 34101, "s": 34059, "text": "S2: R1(X) R2(X) R2(Y) W2(Y) R1(Y) W1(X)\n\n" }, { "code": null, "e": 34168, "s": 34101, "text": "Swapping non conflicting operations R1(X) and R2(X) of S2, we get " }, { "code": null, "e": 34211, "s": 34168, "text": "S2’: R2(X) R1(X) R2(Y) W2(Y) R1(Y) W1(X)\n\n" }, { "code": null, "e": 34286, "s": 34211, "text": "Again, swapping non conflicting operations R1(X) and R2(Y) of S2’, we get " }, { "code": null, "e": 34330, "s": 34286, "text": "S2’’: R2(X) R2(Y) R1(X) W2(Y) R1(Y) W1(X)\n\n" }, { "code": null, "e": 34406, "s": 34330, "text": "Again, swapping non conflicting operations R1(X) and W2(Y) of S2’’, we get " }, { "code": null, "e": 34451, "s": 34406, "text": "S2’’’: R2(X) R2(Y) W2(Y) R1(X) R1(Y) W1(X)\n\n" }, { "code": null, "e": 34501, "s": 34451, "text": "which is equivalent to a serial schedule T2->T1. " }, { "code": null, "e": 34561, "s": 34501, "text": "So, correct option is C. Only S2 is conflict serializable. " }, { "code": null, "e": 34654, "s": 34561, "text": "Related Article: View Serializability Precedence Graph For Testing Conflict Serializability " }, { "code": null, "e": 34816, "s": 34654, "text": "Article contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34834, "s": 34816, "text": "SonalSrivastava02" }, { "code": null, "e": 34850, "s": 34834, "text": "harshit kumar 6" }, { "code": null, "e": 34892, "s": 34850, "text": "DBMS-Transactions and Concurrency Control" }, { "code": null, "e": 34897, "s": 34892, "text": "DBMS" }, { "code": null, "e": 34902, "s": 34897, "text": "DBMS" }, { "code": null, "e": 35000, "s": 34902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35009, "s": 35000, "text": "Comments" }, { "code": null, "e": 35022, "s": 35009, "text": "Old Comments" }, { "code": null, "e": 35069, "s": 35022, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 35087, "s": 35069, "text": "SQL | WITH clause" }, { "code": null, "e": 35128, "s": 35087, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 35159, "s": 35128, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 35212, "s": 35159, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 35224, "s": 35212, "text": "SQL | Views" }, { "code": null, "e": 35235, "s": 35224, "text": "CTE in SQL" }, { "code": null, "e": 35274, "s": 35235, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 35298, "s": 35274, "text": "Third Normal Form (3NF)" } ]
How to hide the colorbar of a Seaborn heatmap?
To hide the colorbar of a Seaborn heatmap, we can use cbar=False in heatmap() method. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a dataframe using 4 columns. Make a dataframe using 4 columns. Use heatmap() method to plot rectangular data as a color-encoded matrix. Use heatmap() method to plot rectangular data as a color-encoded matrix. To display the figure, use show() method. To display the figure, use show() method. import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(np.random.random((4, 4)), columns=["a", "b", "c", "d"]) sns.heatmap(df, cbar=False) plt.show()
[ { "code": null, "e": 1148, "s": 1062, "text": "To hide the colorbar of a Seaborn heatmap, we can use cbar=False in heatmap() method." }, { "code": null, "e": 1224, "s": 1148, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1300, "s": 1224, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1334, "s": 1300, "text": "Make a dataframe using 4 columns." }, { "code": null, "e": 1368, "s": 1334, "text": "Make a dataframe using 4 columns." }, { "code": null, "e": 1441, "s": 1368, "text": "Use heatmap() method to plot rectangular data as a color-encoded matrix." }, { "code": null, "e": 1514, "s": 1441, "text": "Use heatmap() method to plot rectangular data as a color-encoded matrix." }, { "code": null, "e": 1556, "s": 1514, "text": "To display the figure, use show() method." }, { "code": null, "e": 1598, "s": 1556, "text": "To display the figure, use show() method." }, { "code": null, "e": 1894, "s": 1598, "text": "import seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame(np.random.random((4, 4)), columns=[\"a\", \"b\", \"c\", \"d\"])\nsns.heatmap(df, cbar=False)\n\nplt.show()" } ]
Struts 2 - The Action Tag
The action tag allows the programmers to execute an action from the view page. They can achieve this by specifying the action name. They can set the "executeResult" parameter to "true" to render the result directly in the view. Or, they can set this parameter to "false", but make use of the request attributes exposed by the action method. package com.tutorialspoint.struts2; public class HelloWorldAction { private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Let us have HelloWorld.jsp to demonstrate the use of the generator tag − <%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> <h2>Example of Generator Tag</h2> <h3>The colours of rainbow:</h3> <s:generator val = "%{'Violet,Indigo,Blue, Green,Yellow,Orange,Red '}" count = "7" separator = ","> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> </body> </html> Next let us have employees.jsp with the following content − <%@ page contentType = "text/html; charset = UTF-8"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <html> <head> <title>Employees</title> </head> <body> <s:action name = "hello" executeresult = "true"> Output from Hello: <br /> </s:action> </body> </html> Your struts.xml should look like − <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "hello" class = "com.tutorialspoint.struts2.HelloWorldAction" method = "execute"> <result name = "success">/HelloWorld.jsp</result> </action> <action name = "employee" class = "com.tutorialspoint.struts2.Employee" method = "execute"> <result name = "success">/employee.jsp</result> </action> </package> </struts> Your web.xml should look like − <?xml version = "1.0" Encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen − As you can see in this example, we have specified the value of executeResult to "true". Therefore the outcome of the hello.action is rendered directly in the page. The HelloWorld.jsp prints the colors of the rainbow - which is now rendered within employee.jsp Now, let us modify the HelloWorldAction.java slightly − package com.tutorialspoint.struts2; import java.util.ArrayList; import java.util.List; import org.apache.struts2.ServletActionContext; public class HelloWorldAction { private String name; public String execute() { List names = new ArrayList(); names.add("Robert"); names.add("Page"); names.add("Kate"); ServletActionContext.getRequest().setAttribute("names", names); return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Finally, modify the employee.jsp as follows − <%@ page contentType = "text/html; charset = UTF-8"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <html> <head> <title>Employees</title> </head> <body> <s:action name = "hello" executeresult = "false"> Output from Hello: <br /> </s:action> <s:iterator value = "#attr.names"> <s:property /><br /> </s:iterator> </body> </html> Again, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen − Print Add Notes Bookmark this page
[ { "code": null, "e": 2587, "s": 2246, "text": "The action tag allows the programmers to execute an action from the view page. They can achieve this by specifying the action name. They can set the \"executeResult\" parameter to \"true\" to render the result directly in the view. Or, they can set this parameter to \"false\", but make use of the request attributes exposed by the action method." }, { "code": null, "e": 2883, "s": 2587, "text": "package com.tutorialspoint.struts2;\n\npublic class HelloWorldAction {\n private String name;\n\n public String execute() throws Exception {\n return \"success\";\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 2956, "s": 2883, "text": "Let us have HelloWorld.jsp to demonstrate the use of the generator tag −" }, { "code": null, "e": 3458, "s": 2956, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\" %>\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <h2>Example of Generator Tag</h2>\n <h3>The colours of rainbow:</h3>\n\n <s:generator val = \"%{'Violet,Indigo,Blue,\n Green,Yellow,Orange,Red '}\" count = \"7\" separator = \",\">\n \n <s:iterator>\n <s:property /><br/>\n </s:iterator>\n </s:generator>\t\n </body>\n</html>" }, { "code": null, "e": 3518, "s": 3458, "text": "Next let us have employees.jsp with the following content −" }, { "code": null, "e": 3821, "s": 3518, "text": "<%@ page contentType = \"text/html; charset = UTF-8\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n\n<html>\n <head>\n <title>Employees</title>\n </head>\n \n <body>\n <s:action name = \"hello\" executeresult = \"true\">\n Output from Hello: <br />\n </s:action>\n </body>\n</html>" }, { "code": null, "e": 3856, "s": 3821, "text": "Your struts.xml should look like −" }, { "code": null, "e": 4589, "s": 3856, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\" \n method = \"execute\">\n <result name = \"success\">/HelloWorld.jsp</result>\n </action>\n \n <action name = \"employee\" \n class = \"com.tutorialspoint.struts2.Employee\" \n method = \"execute\">\n <result name = \"success\">/employee.jsp</result>\n </action>\n\n </package>\n</struts>" }, { "code": null, "e": 4621, "s": 4589, "text": "Your web.xml should look like −" }, { "code": null, "e": 5435, "s": 4621, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n \n <display-name>Struts 2</display-name>\n \n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n \n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</web-app>" }, { "code": null, "e": 5723, "s": 5435, "text": "Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen −" }, { "code": null, "e": 5983, "s": 5723, "text": "As you can see in this example, we have specified the value of executeResult to \"true\". Therefore the outcome of the hello.action is rendered directly in the page. The HelloWorld.jsp prints the colors of the rainbow - which is now rendered within employee.jsp" }, { "code": null, "e": 6039, "s": 5983, "text": "Now, let us modify the HelloWorldAction.java slightly −" }, { "code": null, "e": 6604, "s": 6039, "text": "package com.tutorialspoint.struts2;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.struts2.ServletActionContext;\n\npublic class HelloWorldAction {\n private String name;\n public String execute() {\n List names = new ArrayList();\n names.add(\"Robert\");\n names.add(\"Page\");\n names.add(\"Kate\");\n ServletActionContext.getRequest().setAttribute(\"names\", names);\n return \"success\";\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 6650, "s": 6604, "text": "Finally, modify the employee.jsp as follows −" }, { "code": null, "e": 7060, "s": 6650, "text": "<%@ page contentType = \"text/html; charset = UTF-8\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n\n<html>\n <head>\n <title>Employees</title>\n </head>\n \n <body>\n \n <s:action name = \"hello\" executeresult = \"false\">\n Output from Hello: <br />\n </s:action>\n \n <s:iterator value = \"#attr.names\">\n <s:property /><br />\n </s:iterator>\n\n </body>\n</html>" }, { "code": null, "e": 7355, "s": 7060, "text": "Again, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen −" }, { "code": null, "e": 7362, "s": 7355, "text": " Print" }, { "code": null, "e": 7373, "s": 7362, "text": " Add Notes" } ]
Overloading function templates in C++ - GeeksforGeeks
18 Jan, 2021 Template: A template is a tool that reduces the efforts in writing the same code as templates can be used at those places. A template function can be overloaded either by a non-template function or using an ordinary function template. Function Overloading: In function overloading, the function may have the same definition, but with different arguments. Below is the C++ program to illustrate function overloading: C++ // C++ program to demonstrate the// function overloading#include <bits/stdc++.h>using namespace std; // Function to calculate squarevoid square(int a){ cout << "Square of " << a << " is " << a * a << endl;} // Function to calculate squarevoid square(double a){ cout << "Square of " << a << " is " << a * a << endl;} // Driver Codeint main(){ // Function Call for side as // 9 i.e., integer square(9); // Function Call for side as // 2.25 i.e., double square(2.25); return 0;} Square of 9 is 81 Square of 2.25 is 5.0625 Explanation: In the above code, the square is overloaded with different parameters. The function square can be overloaded with other arguments too, which requires the same name and different arguments every time. To reduce these efforts, C++ has introduced a generic type called function template. Function Template: The function template has the same syntax as a regular function, but it starts with a keyword template followed by template parameters enclosed inside angular brackets <>. template <class T> T functionName(T arguments){ // Function definition .......... ...... ..... .......}where, T is template argument accepting different arguments and class is a keyword. Template Function Overloading: The name of the function templates are the same but called with different arguments is known as function template overloading. If the function template is with the ordinary template, the name of the function remains the same but the number of parameters differs. When a function template is overloaded with a non-template function, the function name remains the same but the function’s arguments are unlike. Below is the program to illustrate overloading of template function using an explicit function: C++ // C++ program to illustrate overloading// of template function using an// explicit function#include <bits/stdc++.h>using namespace std; // Template declarationtemplate <class T> // Template overloading of functionvoid display(T t1){ cout << "Displaying Template: " << t1 << "\n";} // Template overloading of functionvoid display(int t1){ cout << "Explicitly display: " << t1 << "\n";} // Driver Codeint main(){ // Function Call with a // different arguments display(200); display(12.40); display('G'); return 0;} Explicitly display: 200 Displaying Template: 12.4 Displaying Template: G C-Data Types CPP-Basics Data Types C++ C++ Programs Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character Sorting a Map by value in C++ STL
[ { "code": null, "e": 24122, "s": 24094, "text": "\n18 Jan, 2021" }, { "code": null, "e": 24132, "s": 24122, "text": "Template:" }, { "code": null, "e": 24245, "s": 24132, "text": "A template is a tool that reduces the efforts in writing the same code as templates can be used at those places." }, { "code": null, "e": 24357, "s": 24245, "text": "A template function can be overloaded either by a non-template function or using an ordinary function template." }, { "code": null, "e": 24538, "s": 24357, "text": "Function Overloading: In function overloading, the function may have the same definition, but with different arguments. Below is the C++ program to illustrate function overloading:" }, { "code": null, "e": 24542, "s": 24538, "text": "C++" }, { "code": "// C++ program to demonstrate the// function overloading#include <bits/stdc++.h>using namespace std; // Function to calculate squarevoid square(int a){ cout << \"Square of \" << a << \" is \" << a * a << endl;} // Function to calculate squarevoid square(double a){ cout << \"Square of \" << a << \" is \" << a * a << endl;} // Driver Codeint main(){ // Function Call for side as // 9 i.e., integer square(9); // Function Call for side as // 2.25 i.e., double square(2.25); return 0;}", "e": 25082, "s": 24542, "text": null }, { "code": null, "e": 25126, "s": 25082, "text": "Square of 9 is 81\nSquare of 2.25 is 5.0625\n" }, { "code": null, "e": 25139, "s": 25126, "text": "Explanation:" }, { "code": null, "e": 25210, "s": 25139, "text": "In the above code, the square is overloaded with different parameters." }, { "code": null, "e": 25339, "s": 25210, "text": "The function square can be overloaded with other arguments too, which requires the same name and different arguments every time." }, { "code": null, "e": 25425, "s": 25339, "text": "To reduce these efforts, C++ has introduced a generic type called function template. " }, { "code": null, "e": 25616, "s": 25425, "text": "Function Template: The function template has the same syntax as a regular function, but it starts with a keyword template followed by template parameters enclosed inside angular brackets <>." }, { "code": null, "e": 25635, "s": 25616, "text": "template <class T>" }, { "code": null, "e": 25815, "s": 25635, "text": "T functionName(T arguments){ // Function definition .......... ...... ..... .......}where, T is template argument accepting different arguments and class is a keyword. " }, { "code": null, "e": 25846, "s": 25815, "text": "Template Function Overloading:" }, { "code": null, "e": 25973, "s": 25846, "text": "The name of the function templates are the same but called with different arguments is known as function template overloading." }, { "code": null, "e": 26109, "s": 25973, "text": "If the function template is with the ordinary template, the name of the function remains the same but the number of parameters differs." }, { "code": null, "e": 26254, "s": 26109, "text": "When a function template is overloaded with a non-template function, the function name remains the same but the function’s arguments are unlike." }, { "code": null, "e": 26350, "s": 26254, "text": "Below is the program to illustrate overloading of template function using an explicit function:" }, { "code": null, "e": 26354, "s": 26350, "text": "C++" }, { "code": "// C++ program to illustrate overloading// of template function using an// explicit function#include <bits/stdc++.h>using namespace std; // Template declarationtemplate <class T> // Template overloading of functionvoid display(T t1){ cout << \"Displaying Template: \" << t1 << \"\\n\";} // Template overloading of functionvoid display(int t1){ cout << \"Explicitly display: \" << t1 << \"\\n\";} // Driver Codeint main(){ // Function Call with a // different arguments display(200); display(12.40); display('G'); return 0;}", "e": 26914, "s": 26354, "text": null }, { "code": null, "e": 26988, "s": 26914, "text": "Explicitly display: 200\nDisplaying Template: 12.4\nDisplaying Template: G\n" }, { "code": null, "e": 27001, "s": 26988, "text": "C-Data Types" }, { "code": null, "e": 27012, "s": 27001, "text": "CPP-Basics" }, { "code": null, "e": 27023, "s": 27012, "text": "Data Types" }, { "code": null, "e": 27027, "s": 27023, "text": "C++" }, { "code": null, "e": 27040, "s": 27027, "text": "C++ Programs" }, { "code": null, "e": 27061, "s": 27040, "text": "Programming Language" }, { "code": null, "e": 27065, "s": 27061, "text": "CPP" }, { "code": null, "e": 27163, "s": 27065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27191, "s": 27163, "text": "Operator Overloading in C++" }, { "code": null, "e": 27211, "s": 27191, "text": "Polymorphism in C++" }, { "code": null, "e": 27235, "s": 27211, "text": "Sorting a vector in C++" }, { "code": null, "e": 27268, "s": 27235, "text": "Friend class and function in C++" }, { "code": null, "e": 27312, "s": 27268, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27347, "s": 27312, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27406, "s": 27347, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27432, "s": 27406, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27476, "s": 27432, "text": "Program to print ASCII Value of a character" } ]
Geolocation clearWatch() API
The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device. Here is the syntax of this method − clearWatch(watchId); Here is the detail of parameters − watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call. watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call. The clearWatch method does not return a value. <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> var watchID; var geoLoc; function showLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; alert("Latitude : " + latitude + " Longitude: " + longitude); } function errorHandler(err) { if(err.code == 1) { alert("Error: Access is denied!"); } else if( err.code == 2) { alert("Error: Position is unavailable!"); } } function getLocationUpdate(){ if(navigator.geolocation){ // timeout at 60000 milliseconds (60 seconds) var options = {timeout:60000}; geoLoc = navigator.geolocation; watchID = geoLoc.watchPosition(showLocation, errorHandler, options); } else { alert("Sorry, browser does not support geolocation!"); } } function stopWatch() { geoLoc.clearWatch(watchID); } </script> </head> <body> <form> <input type = "button" onclick = "getLocationUpdate();" value = "Watch Update"/> <input type = "button" onclick = "stopWatch();" value = "Stop Watch"/> </form> </body> </html> This will produce following result − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2786, "s": 2608, "text": "The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device." }, { "code": null, "e": 2822, "s": 2786, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2844, "s": 2822, "text": "clearWatch(watchId);\n" }, { "code": null, "e": 2879, "s": 2844, "text": "Here is the detail of parameters −" }, { "code": null, "e": 3001, "s": 2879, "text": "watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call." }, { "code": null, "e": 3123, "s": 3001, "text": "watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call." }, { "code": null, "e": 3170, "s": 3123, "text": "The clearWatch method does not return a value." }, { "code": null, "e": 4624, "s": 3170, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n var watchID;\n var geoLoc;\n \n function showLocation(position) {\n var latitude = position.coords.latitude;\n var longitude = position.coords.longitude;\n alert(\"Latitude : \" + latitude + \" Longitude: \" + longitude);\n }\n \n function errorHandler(err) {\n if(err.code == 1) {\n alert(\"Error: Access is denied!\");\n } else if( err.code == 2) {\n alert(\"Error: Position is unavailable!\");\n }\n }\n \n function getLocationUpdate(){\n \n if(navigator.geolocation){\n \n // timeout at 60000 milliseconds (60 seconds)\n var options = {timeout:60000};\n geoLoc = navigator.geolocation;\n watchID = geoLoc.watchPosition(showLocation, errorHandler, options);\n } else {\n alert(\"Sorry, browser does not support geolocation!\");\n }\n }\n \n function stopWatch() {\n geoLoc.clearWatch(watchID);\n }\n </script>\n </head>\n \n <body>\n \n <form>\n <input type = \"button\" onclick = \"getLocationUpdate();\" value = \"Watch Update\"/>\n <input type = \"button\" onclick = \"stopWatch();\" value = \"Stop Watch\"/>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 4661, "s": 4624, "text": "This will produce following result −" }, { "code": null, "e": 4694, "s": 4661, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 4708, "s": 4694, "text": " Anadi Sharma" }, { "code": null, "e": 4743, "s": 4708, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4757, "s": 4743, "text": " Anadi Sharma" }, { "code": null, "e": 4792, "s": 4757, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4809, "s": 4792, "text": " Frahaan Hussain" }, { "code": null, "e": 4844, "s": 4809, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4875, "s": 4844, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4908, "s": 4875, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4939, "s": 4908, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4974, "s": 4939, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5005, "s": 4974, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5012, "s": 5005, "text": " Print" }, { "code": null, "e": 5023, "s": 5012, "text": " Add Notes" } ]
First Order Motion Model. An efficient framework by Aliaksandr... | by Merzmensch | Towards Data Science
Seeing used to be believing. Thank AI, we finally have to farewell this cute and naive, but dangerous faith. Because it actually never was. In the XXth century, photos were retouched by repressive regimes. With Deep Learning, we experience new ways to re-illustrate reality. It is not a danger; it’s a chance. Among various methods, the framework and paper “First Order Motion Model for Image Animation” by Aliaksandr Siarohin et al. captivates through its brilliant idea: Image animation consists of generating a video sequence so that an object in a source image is animated according to the motion of a driving video. Our framework addresses this problem without using any annotation or prior information about the specific object to animate. Once trained on a set of videos depicting objects of the same category (e.g. faces, human bodies), our method can be applied to any object of this class. (Source, my emphasis) The key points are set along with transformations (similar to a puppet tool in Photoshop, or like sensors on motion capture suit) — and so the trained movement can be transferred to a target image. The requirement is the same object category. Shortly put, the unsupervised learning approach analyzes the motion data in source footage, universalizes it and, applies to target footage. It also allows face-swap in quite a different way than face2face-approach. While face2face engages the face detector and applies the facial features on the target image, the framework “First Order Motion Model” goes another way: Motion is described as a set of keypoints displacements and local affine transformations. A generator network combines the appearance of the source image and the motion representation of the driving video. In addition, we proposed to explicitly model occlusions in order to indicate to the generator network which image parts should be inpainted (source). And it works astonishingly well. You can try it out either using the GitHub repository or Colab Notebook. I tried my luck on Nefertiti using the footage of AI pioneer Geoffrey Hinton. This footage is delivered with Notebook. You can use another video material. It has to fit into specific requirements and sizes. The result was more than convincing: In opposite, applying my own photo delivers some glitches, especially regarding glasses. I suppose, these patterns are missing in the footage and so the allocation of keypoints sometimes fails: Using a painting by Arcimboldo, we can see how the motion assignment works — some of the graphical features are still detected as background and are not animated. The most interesting effect happens if we use an image without physiognomical patterns — or even abstract art. I used work by Pollock: Here we can observe how the model is trying to orient itself in the chaos of structures — and gets it up to a certain point. Paper demonstrates other face-swap experiments: Probably if we combine this method with StyleTransfer — or even with Deep Painterly Harmonization, we will achieve even more coherent results. The first thought coming to your mind if you see such models is surely: DeepFake. We are already too biased (and keep biasing our Neural Networks). Can we still believe in visuals? Can we distinguish between real and fake in the Digital Age? The answer is: “we cannot anymore”. But: the answer still does not end on that point. This naive belief in the truth behind an image — so seductive because so simple — is a dangerous deception. There are zillions of truths behind an image. Even a raw image without any traces of post-production is not a truth, but a particularly chosen perspective. A glimpse of the unknown ontology. Pars pro toto — and we should take care of its semantical fragility. We have to re-think our relationship with concepts of truth. Because there are so many truths like people. Sure, it’s easy to deceive somebody, faking an image or video footage and presenting it as a real thing. And people do it already — from friendly pranks till presidential uses. But it’s up to us to believe it or not. It’s up to us to research and to analyze more than before. Sure, it’s more work for our brain and perception, but that’s the reality. Understanding the world is not that easy as we used to believe in all the past centuries. Believing in images is a comfortable self-deception. And I am thankful to all AI efforts to disrupt this belief. Sources: Framework scheme and GIF demonstrations, marked with 1) :Website // Paper Framework scheme and GIF demonstrations, marked with 1) :Website // Paper @InProceedings{Siarohin_2019_NeurIPS, author={Siarohin, Aliaksandr and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu}, title={First Order Motion Model for Image Animation}, booktitle = {Conference on Neural Information Processing Systems (NeurIPS)}, month = {December}, year = {2019}} 2. Video footage. Interview with Geoffrey Hinton: https://www.youtube.com/watch?v=XG-dwZMc7Ng
[ { "code": null, "e": 482, "s": 172, "text": "Seeing used to be believing. Thank AI, we finally have to farewell this cute and naive, but dangerous faith. Because it actually never was. In the XXth century, photos were retouched by repressive regimes. With Deep Learning, we experience new ways to re-illustrate reality. It is not a danger; it’s a chance." }, { "code": null, "e": 645, "s": 482, "text": "Among various methods, the framework and paper “First Order Motion Model for Image Animation” by Aliaksandr Siarohin et al. captivates through its brilliant idea:" }, { "code": null, "e": 1094, "s": 645, "text": "Image animation consists of generating a video sequence so that an object in a source image is animated according to the motion of a driving video. Our framework addresses this problem without using any annotation or prior information about the specific object to animate. Once trained on a set of videos depicting objects of the same category (e.g. faces, human bodies), our method can be applied to any object of this class. (Source, my emphasis)" }, { "code": null, "e": 1292, "s": 1094, "text": "The key points are set along with transformations (similar to a puppet tool in Photoshop, or like sensors on motion capture suit) — and so the trained movement can be transferred to a target image." }, { "code": null, "e": 1337, "s": 1292, "text": "The requirement is the same object category." }, { "code": null, "e": 1478, "s": 1337, "text": "Shortly put, the unsupervised learning approach analyzes the motion data in source footage, universalizes it and, applies to target footage." }, { "code": null, "e": 1707, "s": 1478, "text": "It also allows face-swap in quite a different way than face2face-approach. While face2face engages the face detector and applies the facial features on the target image, the framework “First Order Motion Model” goes another way:" }, { "code": null, "e": 2063, "s": 1707, "text": "Motion is described as a set of keypoints displacements and local affine transformations. A generator network combines the appearance of the source image and the motion representation of the driving video. In addition, we proposed to explicitly model occlusions in order to indicate to the generator network which image parts should be inpainted (source)." }, { "code": null, "e": 2096, "s": 2063, "text": "And it works astonishingly well." }, { "code": null, "e": 2169, "s": 2096, "text": "You can try it out either using the GitHub repository or Colab Notebook." }, { "code": null, "e": 2376, "s": 2169, "text": "I tried my luck on Nefertiti using the footage of AI pioneer Geoffrey Hinton. This footage is delivered with Notebook. You can use another video material. It has to fit into specific requirements and sizes." }, { "code": null, "e": 2413, "s": 2376, "text": "The result was more than convincing:" }, { "code": null, "e": 2607, "s": 2413, "text": "In opposite, applying my own photo delivers some glitches, especially regarding glasses. I suppose, these patterns are missing in the footage and so the allocation of keypoints sometimes fails:" }, { "code": null, "e": 2770, "s": 2607, "text": "Using a painting by Arcimboldo, we can see how the motion assignment works — some of the graphical features are still detected as background and are not animated." }, { "code": null, "e": 2905, "s": 2770, "text": "The most interesting effect happens if we use an image without physiognomical patterns — or even abstract art. I used work by Pollock:" }, { "code": null, "e": 3030, "s": 2905, "text": "Here we can observe how the model is trying to orient itself in the chaos of structures — and gets it up to a certain point." }, { "code": null, "e": 3078, "s": 3030, "text": "Paper demonstrates other face-swap experiments:" }, { "code": null, "e": 3221, "s": 3078, "text": "Probably if we combine this method with StyleTransfer — or even with Deep Painterly Harmonization, we will achieve even more coherent results." }, { "code": null, "e": 3369, "s": 3221, "text": "The first thought coming to your mind if you see such models is surely: DeepFake. We are already too biased (and keep biasing our Neural Networks)." }, { "code": null, "e": 3549, "s": 3369, "text": "Can we still believe in visuals? Can we distinguish between real and fake in the Digital Age? The answer is: “we cannot anymore”. But: the answer still does not end on that point." }, { "code": null, "e": 3917, "s": 3549, "text": "This naive belief in the truth behind an image — so seductive because so simple — is a dangerous deception. There are zillions of truths behind an image. Even a raw image without any traces of post-production is not a truth, but a particularly chosen perspective. A glimpse of the unknown ontology. Pars pro toto — and we should take care of its semantical fragility." }, { "code": null, "e": 4201, "s": 3917, "text": "We have to re-think our relationship with concepts of truth. Because there are so many truths like people. Sure, it’s easy to deceive somebody, faking an image or video footage and presenting it as a real thing. And people do it already — from friendly pranks till presidential uses." }, { "code": null, "e": 4465, "s": 4201, "text": "But it’s up to us to believe it or not. It’s up to us to research and to analyze more than before. Sure, it’s more work for our brain and perception, but that’s the reality. Understanding the world is not that easy as we used to believe in all the past centuries." }, { "code": null, "e": 4578, "s": 4465, "text": "Believing in images is a comfortable self-deception. And I am thankful to all AI efforts to disrupt this belief." }, { "code": null, "e": 4587, "s": 4578, "text": "Sources:" }, { "code": null, "e": 4661, "s": 4587, "text": "Framework scheme and GIF demonstrations, marked with 1) :Website // Paper" }, { "code": null, "e": 4735, "s": 4661, "text": "Framework scheme and GIF demonstrations, marked with 1) :Website // Paper" }, { "code": null, "e": 5056, "s": 4735, "text": "@InProceedings{Siarohin_2019_NeurIPS, author={Siarohin, Aliaksandr and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu}, title={First Order Motion Model for Image Animation}, booktitle = {Conference on Neural Information Processing Systems (NeurIPS)}, month = {December}, year = {2019}}" } ]
sizeof operator in C
14 Jun, 2022 Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc.Usage sizeof() operator is used in different way according to the operand type. 1. When operand is a Data Type. When sizeof() is used with the data types such as int, float, char... etc it simply returns the amount of memory is allocated to that data types.Let’s see example: C C++ #include <stdio.h>int main(){ printf("%lu\n", sizeof(char)); printf("%lu\n", sizeof(int)); printf("%lu\n", sizeof(float)); printf("%lu", sizeof(double)); return 0;} #include <iostream>using namespace std; int main(){ cout << sizeof(char)<<"\n"; cout << sizeof(int)<<"\n"; cout << sizeof(float)<<"\n"; cout << sizeof(double)<<"\n"; return 0;} 1 4 4 8 Note: sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler. 2. When operand is an expression. When sizeof() is used with the expression, it returns size of the expression. Let see example: C C++ #include <stdio.h>int main(){ int a = 0; double d = 10.21; printf("%lu", sizeof(a + d)); return 0;} #include <iostream>using namespace std;int main(){ int a = 0; double d = 10.21; cout << sizeof(a + d); return 0;} 8 As we know from first case size of int and double is 4 and 8 respectively, a is int variable while d is a double variable. The final result will be a double, Hence the output of our program is 8 bytes. Type of operator sizeof() is a compile time operator. compile time refers to the time at which the source code is converted to a binary code. It doesn’t execute (run) the code inside (). Lets see an example. C++ C #include <iostream> using namespace std;int main() { int y; int x = 11; y = sizeof(x++); //value of x doesn't change cout<<y<<" "<<x;// prints 4 11 } // C Program to illustrate that the 'sizeof' operator// is a 'compile time operator' #include <stdio.h> int main(void){ int y; int x = 11; y = sizeof(x++); //value of x doesn't change printf("%i %i", y, x); // prints 4 and 11 return (0); } // This code is contributed by sarajadhav12052009 4 11 If we try to increment the value of x, it remains the same. This is because, x is incremented inside the parentheses and sizeof() is a compile time operator. Need of Sizeof 1. To find out number of elements in a array. Sizeof can be used to calculate number of elements of the array automatically. Let see Example : C C++ #include <stdio.h>int main(){ int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 }; printf("Number of elements:%lu ", sizeof(arr) / sizeof(arr[0])); return 0;} #include <iostream>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 }; cout << "Number of elements: " <<(sizeof(arr) / sizeof(arr[0])); return 0;} Number of elements:11 2. To allocate a block of memory dynamically. sizeof is greatly used in dynamic memory allocation. For example, if we want to allocate memory for which is sufficient to hold 10 integers and we don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof. C int* ptr = (int*)malloc(10 * sizeof(int)); References https://en.wikipedia.org/wiki/SizeofPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above dominicsavio abhinavk03 manshu1046 sarajadhav12052009 C Basics C-Operators cpp-operator C Language cpp-operator Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 532, "s": 52, "text": "Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc.Usage sizeof() operator is used in different way according to the operand type. " }, { "code": null, "e": 730, "s": 532, "text": "1. When operand is a Data Type. When sizeof() is used with the data types such as int, float, char... etc it simply returns the amount of memory is allocated to that data types.Let’s see example: " }, { "code": null, "e": 732, "s": 730, "text": "C" }, { "code": null, "e": 736, "s": 732, "text": "C++" }, { "code": "#include <stdio.h>int main(){ printf(\"%lu\\n\", sizeof(char)); printf(\"%lu\\n\", sizeof(int)); printf(\"%lu\\n\", sizeof(float)); printf(\"%lu\", sizeof(double)); return 0;}", "e": 916, "s": 736, "text": null }, { "code": "#include <iostream>using namespace std; int main(){ cout << sizeof(char)<<\"\\n\"; cout << sizeof(int)<<\"\\n\"; cout << sizeof(float)<<\"\\n\"; cout << sizeof(double)<<\"\\n\"; return 0;}", "e": 1108, "s": 916, "text": null }, { "code": null, "e": 1116, "s": 1108, "text": "1\n4\n4\n8" }, { "code": null, "e": 1227, "s": 1116, "text": "Note: sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler." }, { "code": null, "e": 1358, "s": 1227, "text": "2. When operand is an expression. When sizeof() is used with the expression, it returns size of the expression. Let see example: " }, { "code": null, "e": 1360, "s": 1358, "text": "C" }, { "code": null, "e": 1364, "s": 1360, "text": "C++" }, { "code": "#include <stdio.h>int main(){ int a = 0; double d = 10.21; printf(\"%lu\", sizeof(a + d)); return 0;}", "e": 1476, "s": 1364, "text": null }, { "code": "#include <iostream>using namespace std;int main(){ int a = 0; double d = 10.21; cout << sizeof(a + d); return 0;}", "e": 1602, "s": 1476, "text": null }, { "code": null, "e": 1604, "s": 1602, "text": "8" }, { "code": null, "e": 1806, "s": 1604, "text": "As we know from first case size of int and double is 4 and 8 respectively, a is int variable while d is a double variable. The final result will be a double, Hence the output of our program is 8 bytes." }, { "code": null, "e": 1823, "s": 1806, "text": "Type of operator" }, { "code": null, "e": 2014, "s": 1823, "text": "sizeof() is a compile time operator. compile time refers to the time at which the source code is converted to a binary code. It doesn’t execute (run) the code inside (). Lets see an example." }, { "code": null, "e": 2018, "s": 2014, "text": "C++" }, { "code": null, "e": 2020, "s": 2018, "text": "C" }, { "code": "#include <iostream> using namespace std;int main() { int y; int x = 11; y = sizeof(x++); //value of x doesn't change cout<<y<<\" \"<<x;// prints 4 11 }", "e": 2175, "s": 2020, "text": null }, { "code": "// C Program to illustrate that the 'sizeof' operator// is a 'compile time operator' #include <stdio.h> int main(void){ int y; int x = 11; y = sizeof(x++); //value of x doesn't change printf(\"%i %i\", y, x); // prints 4 and 11 return (0); } // This code is contributed by sarajadhav12052009", "e": 2479, "s": 2175, "text": null }, { "code": null, "e": 2484, "s": 2479, "text": "4 11" }, { "code": null, "e": 2644, "s": 2484, "text": "If we try to increment the value of x, it remains the same. This is because, x is incremented inside the parentheses and sizeof() is a compile time operator. " }, { "code": null, "e": 2804, "s": 2644, "text": "Need of Sizeof 1. To find out number of elements in a array. Sizeof can be used to calculate number of elements of the array automatically. Let see Example : " }, { "code": null, "e": 2806, "s": 2804, "text": "C" }, { "code": null, "e": 2810, "s": 2806, "text": "C++" }, { "code": "#include <stdio.h>int main(){ int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 }; printf(\"Number of elements:%lu \", sizeof(arr) / sizeof(arr[0])); return 0;}", "e": 2979, "s": 2810, "text": null }, { "code": "#include <iostream>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 }; cout << \"Number of elements: \" <<(sizeof(arr) / sizeof(arr[0])); return 0;}", "e": 3176, "s": 2979, "text": null }, { "code": null, "e": 3199, "s": 3176, "text": "Number of elements:11 " }, { "code": null, "e": 3489, "s": 3199, "text": "2. To allocate a block of memory dynamically. sizeof is greatly used in dynamic memory allocation. For example, if we want to allocate memory for which is sufficient to hold 10 integers and we don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof. " }, { "code": null, "e": 3491, "s": 3489, "text": "C" }, { "code": "int* ptr = (int*)malloc(10 * sizeof(int));", "e": 3534, "s": 3491, "text": null }, { "code": null, "e": 3706, "s": 3534, "text": "References https://en.wikipedia.org/wiki/SizeofPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3719, "s": 3706, "text": "dominicsavio" }, { "code": null, "e": 3730, "s": 3719, "text": "abhinavk03" }, { "code": null, "e": 3741, "s": 3730, "text": "manshu1046" }, { "code": null, "e": 3760, "s": 3741, "text": "sarajadhav12052009" }, { "code": null, "e": 3769, "s": 3760, "text": "C Basics" }, { "code": null, "e": 3781, "s": 3769, "text": "C-Operators" }, { "code": null, "e": 3794, "s": 3781, "text": "cpp-operator" }, { "code": null, "e": 3805, "s": 3794, "text": "C Language" }, { "code": null, "e": 3818, "s": 3805, "text": "cpp-operator" } ]
Water Jug Problem using Memoization
02 Sep, 2018 Given two jugs with the maximum capacity of m and n liters respectively. The jugs don’t have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or (d, 0). Examples: Input: 4 3 2Output: (0, 0) –> (4, 0) –> (4, 3) –> (0, 3) –> (3, 0) –> (3, 3) –> (4, 2) –> (0, 2) Input: 5 2 4Output: (0, 0) –> (5, 0) –> (5, 2) –> (0, 2) –> (2, 0) –> (2, 2) –> (4, 0) Approach: An approach using BFS has been discussed in the previous post. In this post an approach using memoization and recursion has been discussed. At any point, there can be a total of six possibilities: Empty the first jug completely Empty the second jug completely Fill the first jug Fill the second jug Fill the water from the second jug into the first jug until the first jug is full or the second jug has no water left Fill the water from the first jug into the second jug until the second jug is full or the first jug has no water left Approach: Using Recursion, visit all the six possible moves one by one until one of them returns True. Since there can be repetitions of same recursive calls, hence every return value is stored using memoization to avoid calling the recursive function again and returning the stored value. Below is the implementation of the above approach: # This function is used to initialize the # dictionary elements with a default value.from collections import defaultdict # jug1 and jug2 contain the value # for max capacity in respective jugs # and aim is the amount of water to be measured. jug1, jug2, aim = 4, 3, 2 # Initialize dictionary with # default value as false.visited = defaultdict(lambda: False) # Recursive function which prints the # intermediate steps to reach the final # solution and return boolean value # (True if solution is possible, otherwise False).# amt1 and amt2 are the amount of water present # in both jugs at a certain point of time.def waterJugSolver(amt1, amt2): # Checks for our goal and # returns true if achieved. if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0): print(amt1, amt2) return True # Checks if we have already visited the # combination or not. If not, then it proceeds further. if visited[(amt1, amt2)] == False: print(amt1, amt2) # Changes the boolean value of # the combination as it is visited. visited[(amt1, amt2)] = True # Check for all the 6 possibilities and # see if a solution is found in any one of them. return (waterJugSolver(0, amt2) or waterJugSolver(amt1, 0) or waterJugSolver(jug1, amt2) or waterJugSolver(amt1, jug2) or waterJugSolver(amt1 + min(amt2, (jug1-amt1)), amt2 - min(amt2, (jug1-amt1))) or waterJugSolver(amt1 - min(amt1, (jug2-amt2)), amt2 + min(amt1, (jug2-amt2)))) # Return False if the combination is # already visited to avoid repetition otherwise # recursion will enter an infinite loop. else: return False print("Steps: ") # Call the function and pass the# initial amount of water present in both jugs.waterJugSolver(0, 0) Steps: 0 0 4 0 4 3 0 3 3 0 3 3 4 2 0 2 Time complexity: O(M * N)Auxiliary Space: O(M * N) Algorithms-Dynamic Programming Algorithms-Recursion Memoization Dynamic Programming Recursion Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Find the longest path in a matrix with given constraints Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Sep, 2018" }, { "code": null, "e": 362, "s": 54, "text": "Given two jugs with the maximum capacity of m and n liters respectively. The jugs don’t have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or (d, 0)." }, { "code": null, "e": 372, "s": 362, "text": "Examples:" }, { "code": null, "e": 469, "s": 372, "text": "Input: 4 3 2Output: (0, 0) –> (4, 0) –> (4, 3) –> (0, 3) –> (3, 0) –> (3, 3) –> (4, 2) –> (0, 2)" }, { "code": null, "e": 556, "s": 469, "text": "Input: 5 2 4Output: (0, 0) –> (5, 0) –> (5, 2) –> (0, 2) –> (2, 0) –> (2, 2) –> (4, 0)" }, { "code": null, "e": 763, "s": 556, "text": "Approach: An approach using BFS has been discussed in the previous post. In this post an approach using memoization and recursion has been discussed. At any point, there can be a total of six possibilities:" }, { "code": null, "e": 794, "s": 763, "text": "Empty the first jug completely" }, { "code": null, "e": 826, "s": 794, "text": "Empty the second jug completely" }, { "code": null, "e": 845, "s": 826, "text": "Fill the first jug" }, { "code": null, "e": 865, "s": 845, "text": "Fill the second jug" }, { "code": null, "e": 983, "s": 865, "text": "Fill the water from the second jug into the first jug until the first jug is full or the second jug has no water left" }, { "code": null, "e": 1101, "s": 983, "text": "Fill the water from the first jug into the second jug until the second jug is full or the first jug has no water left" }, { "code": null, "e": 1391, "s": 1101, "text": "Approach: Using Recursion, visit all the six possible moves one by one until one of them returns True. Since there can be repetitions of same recursive calls, hence every return value is stored using memoization to avoid calling the recursive function again and returning the stored value." }, { "code": null, "e": 1442, "s": 1391, "text": "Below is the implementation of the above approach:" }, { "code": "# This function is used to initialize the # dictionary elements with a default value.from collections import defaultdict # jug1 and jug2 contain the value # for max capacity in respective jugs # and aim is the amount of water to be measured. jug1, jug2, aim = 4, 3, 2 # Initialize dictionary with # default value as false.visited = defaultdict(lambda: False) # Recursive function which prints the # intermediate steps to reach the final # solution and return boolean value # (True if solution is possible, otherwise False).# amt1 and amt2 are the amount of water present # in both jugs at a certain point of time.def waterJugSolver(amt1, amt2): # Checks for our goal and # returns true if achieved. if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0): print(amt1, amt2) return True # Checks if we have already visited the # combination or not. If not, then it proceeds further. if visited[(amt1, amt2)] == False: print(amt1, amt2) # Changes the boolean value of # the combination as it is visited. visited[(amt1, amt2)] = True # Check for all the 6 possibilities and # see if a solution is found in any one of them. return (waterJugSolver(0, amt2) or waterJugSolver(amt1, 0) or waterJugSolver(jug1, amt2) or waterJugSolver(amt1, jug2) or waterJugSolver(amt1 + min(amt2, (jug1-amt1)), amt2 - min(amt2, (jug1-amt1))) or waterJugSolver(amt1 - min(amt1, (jug2-amt2)), amt2 + min(amt1, (jug2-amt2)))) # Return False if the combination is # already visited to avoid repetition otherwise # recursion will enter an infinite loop. else: return False print(\"Steps: \") # Call the function and pass the# initial amount of water present in both jugs.waterJugSolver(0, 0)", "e": 3351, "s": 1442, "text": null }, { "code": null, "e": 3392, "s": 3351, "text": "Steps: \n0 0\n4 0\n4 3\n0 3\n3 0\n3 3\n4 2\n0 2\n" }, { "code": null, "e": 3443, "s": 3392, "text": "Time complexity: O(M * N)Auxiliary Space: O(M * N)" }, { "code": null, "e": 3474, "s": 3443, "text": "Algorithms-Dynamic Programming" }, { "code": null, "e": 3495, "s": 3474, "text": "Algorithms-Recursion" }, { "code": null, "e": 3507, "s": 3495, "text": "Memoization" }, { "code": null, "e": 3527, "s": 3507, "text": "Dynamic Programming" }, { "code": null, "e": 3537, "s": 3527, "text": "Recursion" }, { "code": null, "e": 3557, "s": 3537, "text": "Dynamic Programming" }, { "code": null, "e": 3567, "s": 3557, "text": "Recursion" }, { "code": null, "e": 3665, "s": 3567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3692, "s": 3665, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 3730, "s": 3692, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 3763, "s": 3730, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 3798, "s": 3763, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 3855, "s": 3798, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 3915, "s": 3855, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4000, "s": 3915, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 4010, "s": 4000, "text": "Recursion" }, { "code": null, "e": 4037, "s": 4010, "text": "Program for Tower of Hanoi" } ]
How to save new state to local JSON using ReactJS ?
14 Apr, 2021 Sometimes we need to store the state locally on the browser in a JSON format. We can save any information to the local storage of the browser and access that information anytime later. Setting up environment and Execution: Step 1: Create React App by using the following command.npx create-react-app foldername Step 1: Create React App by using the following command. npx create-react-app foldername Step 2: After creating your project folder, i.e., folder name, move to it using the following command:cd foldername Step 2: After creating your project folder, i.e., folder name, move to it using the following command: cd foldername Project Structure: It will look like the following. App.js import React, { Component } from 'react'; class App extends Component { state = { data: "This is data", num: 123, boolean: true, } // save data to localStorage saveStateToLocalStorage = () => { localStorage.setItem('state', JSON.stringify(this.state)); } // Fetch data from local storage getStateFromLocalStorage = () => { let data = localStorage.getItem('state'); if(data !== undefined) { this.setState(JSON.parse(data)); } } componentDidMount() { // Fetch data from local storage this.getStateFromLocalStorage(); } render() { return ( <div> <h2>GeeksforGeeks</h2> <button onClick={this.saveStateToLocalStorage}> Save State to local storage\ </button> </div> ); } } export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. JSON Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to do crud operations in ReactJS ? How to create a multi-page website using React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Apr, 2021" }, { "code": null, "e": 237, "s": 52, "text": "Sometimes we need to store the state locally on the browser in a JSON format. We can save any information to the local storage of the browser and access that information anytime later." }, { "code": null, "e": 275, "s": 237, "text": "Setting up environment and Execution:" }, { "code": null, "e": 363, "s": 275, "text": "Step 1: Create React App by using the following command.npx create-react-app foldername" }, { "code": null, "e": 420, "s": 363, "text": "Step 1: Create React App by using the following command." }, { "code": null, "e": 452, "s": 420, "text": "npx create-react-app foldername" }, { "code": null, "e": 568, "s": 452, "text": "Step 2: After creating your project folder, i.e., folder name, move to it using the following command:cd foldername" }, { "code": null, "e": 671, "s": 568, "text": "Step 2: After creating your project folder, i.e., folder name, move to it using the following command:" }, { "code": null, "e": 685, "s": 671, "text": "cd foldername" }, { "code": null, "e": 737, "s": 685, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 744, "s": 737, "text": "App.js" }, { "code": "import React, { Component } from 'react'; class App extends Component { state = { data: \"This is data\", num: 123, boolean: true, } // save data to localStorage saveStateToLocalStorage = () => { localStorage.setItem('state', JSON.stringify(this.state)); } // Fetch data from local storage getStateFromLocalStorage = () => { let data = localStorage.getItem('state'); if(data !== undefined) { this.setState(JSON.parse(data)); } } componentDidMount() { // Fetch data from local storage this.getStateFromLocalStorage(); } render() { return ( <div> <h2>GeeksforGeeks</h2> <button onClick={this.saveStateToLocalStorage}> Save State to local storage\\ </button> </div> ); } } export default App;\n", "e": 1567, "s": 744, "text": null }, { "code": null, "e": 1680, "s": 1567, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1690, "s": 1680, "text": "npm start" }, { "code": null, "e": 1789, "s": 1690, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 1794, "s": 1789, "text": "JSON" }, { "code": null, "e": 1801, "s": 1794, "text": "Picked" }, { "code": null, "e": 1817, "s": 1801, "text": "React-Questions" }, { "code": null, "e": 1825, "s": 1817, "text": "ReactJS" }, { "code": null, "e": 1842, "s": 1825, "text": "Web Technologies" }, { "code": null, "e": 1940, "s": 1842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1978, "s": 1940, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2005, "s": 1978, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2044, "s": 2005, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2083, "s": 2044, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2135, "s": 2083, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 2168, "s": 2135, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2230, "s": 2168, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2291, "s": 2230, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2341, "s": 2291, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
D3.js selection.property() Function
16 Jun, 2022 The selection.property() function is used to set or change the property and value of a particular element. The value of a particular property can be deleted by setting its value to null. Syntax: selection.property(name[, value]); Parameters: This function accept two parameters as mentioned above and described below: name: The name of the property to set. value: The property value to be set. Return Value: This function does not return any value. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <div> <input type="text"> </div> <script> // Sets value property of the input tag var input = d3.select("input") .property("value", "some value from input"); var text = document.querySelector("input"); // Value from input console.log(text.value); </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <div> <input type="checkbox" class="checkbox" name="" id="">checkbox<br> <button>Click me</button> </div> <script> function func() { // Sets checked and value property // of the checkbox var chk = d3.select(".checkbox").property( "value", "some value from checkbox"); var chk = d3.select(".checkbox") .property("checked", true); var text = document.querySelector(".checkbox"); // Value from checkbox console.log(text.value); console.log(text.checked); } let btn = document.querySelector("button"); btn.addEventListener("click", func); </script></body> </html> Output: Before clicking the click me button: After clicking the click me button: surinderdawra388 D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 215, "s": 28, "text": "The selection.property() function is used to set or change the property and value of a particular element. The value of a particular property can be deleted by setting its value to null." }, { "code": null, "e": 223, "s": 215, "text": "Syntax:" }, { "code": null, "e": 258, "s": 223, "text": "selection.property(name[, value]);" }, { "code": null, "e": 346, "s": 258, "text": "Parameters: This function accept two parameters as mentioned above and described below:" }, { "code": null, "e": 385, "s": 346, "text": "name: The name of the property to set." }, { "code": null, "e": 422, "s": 385, "text": "value: The property value to be set." }, { "code": null, "e": 477, "s": 422, "text": "Return Value: This function does not return any value." }, { "code": null, "e": 488, "s": 477, "text": "Example 1:" }, { "code": null, "e": 493, "s": 488, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <div> <input type=\"text\"> </div> <script> // Sets value property of the input tag var input = d3.select(\"input\") .property(\"value\", \"some value from input\"); var text = document.querySelector(\"input\"); // Value from input console.log(text.value); </script></body> </html>", "e": 1066, "s": 493, "text": null }, { "code": null, "e": 1074, "s": 1066, "text": "Output:" }, { "code": null, "e": 1085, "s": 1074, "text": "Example 2:" }, { "code": null, "e": 1090, "s": 1085, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <div> <input type=\"checkbox\" class=\"checkbox\" name=\"\" id=\"\">checkbox<br> <button>Click me</button> </div> <script> function func() { // Sets checked and value property // of the checkbox var chk = d3.select(\".checkbox\").property( \"value\", \"some value from checkbox\"); var chk = d3.select(\".checkbox\") .property(\"checked\", true); var text = document.querySelector(\".checkbox\"); // Value from checkbox console.log(text.value); console.log(text.checked); } let btn = document.querySelector(\"button\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 2075, "s": 1090, "text": null }, { "code": null, "e": 2083, "s": 2075, "text": "Output:" }, { "code": null, "e": 2120, "s": 2083, "text": "Before clicking the click me button:" }, { "code": null, "e": 2156, "s": 2120, "text": "After clicking the click me button:" }, { "code": null, "e": 2173, "s": 2156, "text": "surinderdawra388" }, { "code": null, "e": 2179, "s": 2173, "text": "D3.js" }, { "code": null, "e": 2190, "s": 2179, "text": "JavaScript" }, { "code": null, "e": 2207, "s": 2190, "text": "Web Technologies" } ]
Java Swing | JSlider
15 Apr, 2021 JSlider is a part of Java Swing package . JSlider is an implementation of slider. The Component allows the user to select a value by sliding the knob within the bounded value . The slider can show Major Tick marks and also the minor tick marks between two major tick marks, The knob can be positioned at only those points. Constructor of the class are : JSlider() : create a new slider with horizontal orientation and max and min value 100 and 0 respectively and the slider value is set to 50.JSlider(BoundedRangeModel b) : creates a new Slider with horizontal orientation and a specified boundary range model.JSlider(int o) : create a new slider with a specified orientation and max and min value 100 and 0 respectively and the slider value is set to 50.JSlider(int min, int max) :create a new slider with horizontal orientation and max and min value specified and the slider value is set to the average of max and min value.JSlider(int min, int max, int value) :create a new slider with horizontal orientation and max, min value and the slider Value specified .JSlider(int o, int min, int max, int value) : create a new slider with orientation and max, min value and the slider Value specified . JSlider() : create a new slider with horizontal orientation and max and min value 100 and 0 respectively and the slider value is set to 50. JSlider(BoundedRangeModel b) : creates a new Slider with horizontal orientation and a specified boundary range model. JSlider(int o) : create a new slider with a specified orientation and max and min value 100 and 0 respectively and the slider value is set to 50. JSlider(int min, int max) :create a new slider with horizontal orientation and max and min value specified and the slider value is set to the average of max and min value. JSlider(int min, int max, int value) :create a new slider with horizontal orientation and max, min value and the slider Value specified . JSlider(int o, int min, int max, int value) : create a new slider with orientation and max, min value and the slider Value specified . Commonly used functions setOrientation(int n) : sets the orientation of the slider to the specified value setValue( int v) : sets the value of the slider to the specified value setPaintTicks(boolean b) : the boolean value determines whether the ticks are painted on the slider or not setPaintTrack(boolean b) : the boolean value determines whether the track are painted on the slider or not setMajorTickSpacing(int n) : sets the spacing for major ticks . setMinorTickSpacing(int n) : sets the spacing for minor ticks . setFont(Font f) : set the font of the text for the slider setMaximum(int m) : set the maximum value for the slider setMinimum(int m) : sets the minimum value for the slider updateUI() : Resets the UI property to a value from the current look and feel. setValueIsAdjusting(boolean b) : Sets the model’s valueIsAdjusting property to boolean b. setUI(SliderUI ui) : Sets the UI object which implements the Look and feel for this component. setSnapToTicks(boolean b): if true is passed then the slider position is placed to nearest tick. setModel(BoundedRangeModel n) : sets the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. setLabelTable(Dictionary l) : Used to specify what label will be drawn at any given value. setInverted(boolean b): if passed true then the slider is set to inverted. imageUpdate(Image img, int s, int x, int y, int w, int h): repaints the component when the image has changed. setExtent(int extent) : sets the size of the range “covered” by the knob. removeChangeListener(ChangeListener l): removes a ChangeListener from the slider. getModel(): returns the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. getSnapToTicks() : returns true if the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob. getUI(): gets the UI object which implements the L&F for this component. getPaintTrack() : returns if the tracks are painted or not. getPaintTicks() : returns if ticks are painted or not getPaintLabels() : returns whether labels are painted or not getOrientation() : returns the orientation of the component. getMinorTickSpacing() : returns the minor tick spacing getMinimum(): returns the minimum value getMaximum(): returns the maximum value getMajorTickSpacing() : returns the major tick spacing. addChangeListener(ChangeListener l) :dds a ChangeListener to the slider.\ createChangeListener() : create a change listener for the componentsetUI(SliderUI ui) : sets the look and feel object that renders this component. getUI() : returns the look and feel object that renders this component. paramString() : returns a string representation of this JSlider. getUIClassID() : returns the name of the Look and feel class that renders this component. getAccessibleContext() : gets the AccessibleContext associated with this JSlider. setOrientation(int n) : sets the orientation of the slider to the specified value setValue( int v) : sets the value of the slider to the specified value setPaintTicks(boolean b) : the boolean value determines whether the ticks are painted on the slider or not setPaintTrack(boolean b) : the boolean value determines whether the track are painted on the slider or not setMajorTickSpacing(int n) : sets the spacing for major ticks . setMinorTickSpacing(int n) : sets the spacing for minor ticks . setFont(Font f) : set the font of the text for the slider setMaximum(int m) : set the maximum value for the slider setMinimum(int m) : sets the minimum value for the slider updateUI() : Resets the UI property to a value from the current look and feel. setValueIsAdjusting(boolean b) : Sets the model’s valueIsAdjusting property to boolean b. setUI(SliderUI ui) : Sets the UI object which implements the Look and feel for this component. setSnapToTicks(boolean b): if true is passed then the slider position is placed to nearest tick. setModel(BoundedRangeModel n) : sets the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. setLabelTable(Dictionary l) : Used to specify what label will be drawn at any given value. setInverted(boolean b): if passed true then the slider is set to inverted. imageUpdate(Image img, int s, int x, int y, int w, int h): repaints the component when the image has changed. setExtent(int extent) : sets the size of the range “covered” by the knob. removeChangeListener(ChangeListener l): removes a ChangeListener from the slider. getModel(): returns the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. getSnapToTicks() : returns true if the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob. getUI(): gets the UI object which implements the L&F for this component. getPaintTrack() : returns if the tracks are painted or not. getPaintTicks() : returns if ticks are painted or not getPaintLabels() : returns whether labels are painted or not getOrientation() : returns the orientation of the component. getMinorTickSpacing() : returns the minor tick spacing getMinimum(): returns the minimum value getMaximum(): returns the maximum value getMajorTickSpacing() : returns the major tick spacing. addChangeListener(ChangeListener l) :dds a ChangeListener to the slider.\ createChangeListener() : create a change listener for the component setUI(SliderUI ui) : sets the look and feel object that renders this component. getUI() : returns the look and feel object that renders this component. paramString() : returns a string representation of this JSlider. getUIClassID() : returns the name of the Look and feel class that renders this component. getAccessibleContext() : gets the AccessibleContext associated with this JSlider. The Following programs will illustrate the use of JSlider1. program to create a simple JSlider Java // java Program to create a simple JSliderimport javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame { // frame static JFrame f; // slider static JSlider b; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(); // add slider to panel p.add(b); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }} Output : 2 . Program to create a slider with min and max value and major and minor ticks painted. Java // java Program to create a slider with min and// max value and major and minor ticks painted.import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ChangeListener { // frame static JFrame f; // slider static JSlider b; // label static JLabel l; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create label l = new JLabel(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(0, 200, 120); // paint the ticks and tracks b.setPaintTrack(true); b.setPaintTicks(true); b.setPaintLabels(true); // set spacing b.setMajorTickSpacing(50); b.setMinorTickSpacing(5); // setChangeListener b.addChangeListener(s); // add slider to panel p.add(b); p.add(l); f.add(p); // set the text of label l.setText("value of Slider is =" + b.getValue()); // set the size of frame f.setSize(300, 300); f.show(); } // if JSlider value is changed public void stateChanged(ChangeEvent e) { l.setText("value of Slider is =" + b.getValue()); }} Output : 3 . Program to create a vertical slider with min and max value and major and minor ticks painted and set the font of the slider. Java // java Program to create a vertical slider with// min and max value and major and minor ticks// painted and set the font of the slider.import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ChangeListener { // frame static JFrame f; // slider static JSlider b; // label static JLabel l; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create label l = new JLabel(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(0, 200, 120); // paint the ticks and tracks b.setPaintTrack(true); b.setPaintTicks(true); b.setPaintLabels(true); // set spacing b.setMajorTickSpacing(50); b.setMinorTickSpacing(5); // setChangeListener b.addChangeListener(s); // set orientation of slider b.setOrientation(SwingConstants.VERTICAL); // set Font for the slider b.setFont(new Font("Serif", Font.ITALIC, 20)); // add slider to panel p.add(b); p.add(l); f.add(p); // set the text of label l.setText("value of Slider is =" + b.getValue()); // set the size of frame f.setSize(300, 300); f.show(); } // if JSlider value is changed public void stateChanged(ChangeEvent e) { l.setText("value of Slider is =" + b.getValue()); }} Output : Note : The above programs might not run in an online compiler please use an offline IDE ManasChhabra2 sweetyty java-swing Java Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2021" }, { "code": null, "e": 384, "s": 28, "text": "JSlider is a part of Java Swing package . JSlider is an implementation of slider. The Component allows the user to select a value by sliding the knob within the bounded value . The slider can show Major Tick marks and also the minor tick marks between two major tick marks, The knob can be positioned at only those points. Constructor of the class are : " }, { "code": null, "e": 1228, "s": 384, "text": "JSlider() : create a new slider with horizontal orientation and max and min value 100 and 0 respectively and the slider value is set to 50.JSlider(BoundedRangeModel b) : creates a new Slider with horizontal orientation and a specified boundary range model.JSlider(int o) : create a new slider with a specified orientation and max and min value 100 and 0 respectively and the slider value is set to 50.JSlider(int min, int max) :create a new slider with horizontal orientation and max and min value specified and the slider value is set to the average of max and min value.JSlider(int min, int max, int value) :create a new slider with horizontal orientation and max, min value and the slider Value specified .JSlider(int o, int min, int max, int value) : create a new slider with orientation and max, min value and the slider Value specified ." }, { "code": null, "e": 1368, "s": 1228, "text": "JSlider() : create a new slider with horizontal orientation and max and min value 100 and 0 respectively and the slider value is set to 50." }, { "code": null, "e": 1486, "s": 1368, "text": "JSlider(BoundedRangeModel b) : creates a new Slider with horizontal orientation and a specified boundary range model." }, { "code": null, "e": 1632, "s": 1486, "text": "JSlider(int o) : create a new slider with a specified orientation and max and min value 100 and 0 respectively and the slider value is set to 50." }, { "code": null, "e": 1804, "s": 1632, "text": "JSlider(int min, int max) :create a new slider with horizontal orientation and max and min value specified and the slider value is set to the average of max and min value." }, { "code": null, "e": 1942, "s": 1804, "text": "JSlider(int min, int max, int value) :create a new slider with horizontal orientation and max, min value and the slider Value specified ." }, { "code": null, "e": 2077, "s": 1942, "text": "JSlider(int o, int min, int max, int value) : create a new slider with orientation and max, min value and the slider Value specified ." }, { "code": null, "e": 2103, "s": 2077, "text": "Commonly used functions " }, { "code": null, "e": 5050, "s": 2103, "text": "setOrientation(int n) : sets the orientation of the slider to the specified value setValue( int v) : sets the value of the slider to the specified value setPaintTicks(boolean b) : the boolean value determines whether the ticks are painted on the slider or not setPaintTrack(boolean b) : the boolean value determines whether the track are painted on the slider or not setMajorTickSpacing(int n) : sets the spacing for major ticks . setMinorTickSpacing(int n) : sets the spacing for minor ticks . setFont(Font f) : set the font of the text for the slider setMaximum(int m) : set the maximum value for the slider setMinimum(int m) : sets the minimum value for the slider updateUI() : Resets the UI property to a value from the current look and feel. setValueIsAdjusting(boolean b) : Sets the model’s valueIsAdjusting property to boolean b. setUI(SliderUI ui) : Sets the UI object which implements the Look and feel for this component. setSnapToTicks(boolean b): if true is passed then the slider position is placed to nearest tick. setModel(BoundedRangeModel n) : sets the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. setLabelTable(Dictionary l) : Used to specify what label will be drawn at any given value. setInverted(boolean b): if passed true then the slider is set to inverted. imageUpdate(Image img, int s, int x, int y, int w, int h): repaints the component when the image has changed. setExtent(int extent) : sets the size of the range “covered” by the knob. removeChangeListener(ChangeListener l): removes a ChangeListener from the slider. getModel(): returns the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. getSnapToTicks() : returns true if the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob. getUI(): gets the UI object which implements the L&F for this component. getPaintTrack() : returns if the tracks are painted or not. getPaintTicks() : returns if ticks are painted or not getPaintLabels() : returns whether labels are painted or not getOrientation() : returns the orientation of the component. getMinorTickSpacing() : returns the minor tick spacing getMinimum(): returns the minimum value getMaximum(): returns the maximum value getMajorTickSpacing() : returns the major tick spacing. addChangeListener(ChangeListener l) :dds a ChangeListener to the slider.\\ createChangeListener() : create a change listener for the componentsetUI(SliderUI ui) : sets the look and feel object that renders this component. getUI() : returns the look and feel object that renders this component. paramString() : returns a string representation of this JSlider. getUIClassID() : returns the name of the Look and feel class that renders this component. getAccessibleContext() : gets the AccessibleContext associated with this JSlider. " }, { "code": null, "e": 5134, "s": 5050, "text": "setOrientation(int n) : sets the orientation of the slider to the specified value " }, { "code": null, "e": 5207, "s": 5134, "text": "setValue( int v) : sets the value of the slider to the specified value " }, { "code": null, "e": 5316, "s": 5207, "text": "setPaintTicks(boolean b) : the boolean value determines whether the ticks are painted on the slider or not " }, { "code": null, "e": 5425, "s": 5316, "text": "setPaintTrack(boolean b) : the boolean value determines whether the track are painted on the slider or not " }, { "code": null, "e": 5491, "s": 5425, "text": "setMajorTickSpacing(int n) : sets the spacing for major ticks . " }, { "code": null, "e": 5557, "s": 5491, "text": "setMinorTickSpacing(int n) : sets the spacing for minor ticks . " }, { "code": null, "e": 5617, "s": 5557, "text": "setFont(Font f) : set the font of the text for the slider " }, { "code": null, "e": 5676, "s": 5617, "text": "setMaximum(int m) : set the maximum value for the slider " }, { "code": null, "e": 5736, "s": 5676, "text": "setMinimum(int m) : sets the minimum value for the slider " }, { "code": null, "e": 5817, "s": 5736, "text": "updateUI() : Resets the UI property to a value from the current look and feel. " }, { "code": null, "e": 5909, "s": 5817, "text": "setValueIsAdjusting(boolean b) : Sets the model’s valueIsAdjusting property to boolean b. " }, { "code": null, "e": 6006, "s": 5909, "text": "setUI(SliderUI ui) : Sets the UI object which implements the Look and feel for this component. " }, { "code": null, "e": 6105, "s": 6006, "text": "setSnapToTicks(boolean b): if true is passed then the slider position is placed to nearest tick. " }, { "code": null, "e": 6247, "s": 6105, "text": "setModel(BoundedRangeModel n) : sets the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. " }, { "code": null, "e": 6340, "s": 6247, "text": "setLabelTable(Dictionary l) : Used to specify what label will be drawn at any given value. " }, { "code": null, "e": 6417, "s": 6340, "text": "setInverted(boolean b): if passed true then the slider is set to inverted. " }, { "code": null, "e": 6529, "s": 6417, "text": "imageUpdate(Image img, int s, int x, int y, int w, int h): repaints the component when the image has changed. " }, { "code": null, "e": 6605, "s": 6529, "text": "setExtent(int extent) : sets the size of the range “covered” by the knob. " }, { "code": null, "e": 6689, "s": 6605, "text": "removeChangeListener(ChangeListener l): removes a ChangeListener from the slider. " }, { "code": null, "e": 6814, "s": 6689, "text": "getModel(): returns the BoundedRangeModel that handles the slider’s three fundamental properties: minimum, maximum, value. " }, { "code": null, "e": 6972, "s": 6814, "text": "getSnapToTicks() : returns true if the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob. " }, { "code": null, "e": 7047, "s": 6972, "text": "getUI(): gets the UI object which implements the L&F for this component. " }, { "code": null, "e": 7109, "s": 7047, "text": "getPaintTrack() : returns if the tracks are painted or not. " }, { "code": null, "e": 7165, "s": 7109, "text": "getPaintTicks() : returns if ticks are painted or not " }, { "code": null, "e": 7228, "s": 7165, "text": "getPaintLabels() : returns whether labels are painted or not " }, { "code": null, "e": 7291, "s": 7228, "text": "getOrientation() : returns the orientation of the component. " }, { "code": null, "e": 7348, "s": 7291, "text": "getMinorTickSpacing() : returns the minor tick spacing " }, { "code": null, "e": 7390, "s": 7348, "text": "getMinimum(): returns the minimum value " }, { "code": null, "e": 7432, "s": 7390, "text": "getMaximum(): returns the maximum value " }, { "code": null, "e": 7490, "s": 7432, "text": "getMajorTickSpacing() : returns the major tick spacing. " }, { "code": null, "e": 7566, "s": 7490, "text": "addChangeListener(ChangeListener l) :dds a ChangeListener to the slider.\\ " }, { "code": null, "e": 7634, "s": 7566, "text": "createChangeListener() : create a change listener for the component" }, { "code": null, "e": 7716, "s": 7634, "text": "setUI(SliderUI ui) : sets the look and feel object that renders this component. " }, { "code": null, "e": 7790, "s": 7716, "text": "getUI() : returns the look and feel object that renders this component. " }, { "code": null, "e": 7857, "s": 7790, "text": "paramString() : returns a string representation of this JSlider. " }, { "code": null, "e": 7949, "s": 7857, "text": "getUIClassID() : returns the name of the Look and feel class that renders this component. " }, { "code": null, "e": 8033, "s": 7949, "text": "getAccessibleContext() : gets the AccessibleContext associated with this JSlider. " }, { "code": null, "e": 8130, "s": 8033, "text": "The Following programs will illustrate the use of JSlider1. program to create a simple JSlider " }, { "code": null, "e": 8135, "s": 8130, "text": "Java" }, { "code": "// java Program to create a simple JSliderimport javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame { // frame static JFrame f; // slider static JSlider b; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(); // add slider to panel p.add(b); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 8785, "s": 8135, "text": null }, { "code": null, "e": 8796, "s": 8785, "text": "Output : " }, { "code": null, "e": 8887, "s": 8796, "text": "2 . Program to create a slider with min and max value and major and minor ticks painted. " }, { "code": null, "e": 8892, "s": 8887, "text": "Java" }, { "code": "// java Program to create a slider with min and// max value and major and minor ticks painted.import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ChangeListener { // frame static JFrame f; // slider static JSlider b; // label static JLabel l; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create label l = new JLabel(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(0, 200, 120); // paint the ticks and tracks b.setPaintTrack(true); b.setPaintTicks(true); b.setPaintLabels(true); // set spacing b.setMajorTickSpacing(50); b.setMinorTickSpacing(5); // setChangeListener b.addChangeListener(s); // add slider to panel p.add(b); p.add(l); f.add(p); // set the text of label l.setText(\"value of Slider is =\" + b.getValue()); // set the size of frame f.setSize(300, 300); f.show(); } // if JSlider value is changed public void stateChanged(ChangeEvent e) { l.setText(\"value of Slider is =\" + b.getValue()); }}", "e": 10244, "s": 8892, "text": null }, { "code": null, "e": 10255, "s": 10244, "text": "Output : " }, { "code": null, "e": 10386, "s": 10255, "text": "3 . Program to create a vertical slider with min and max value and major and minor ticks painted and set the font of the slider. " }, { "code": null, "e": 10391, "s": 10386, "text": "Java" }, { "code": "// java Program to create a vertical slider with// min and max value and major and minor ticks// painted and set the font of the slider.import javax.swing.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ChangeListener { // frame static JFrame f; // slider static JSlider b; // label static JLabel l; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create label l = new JLabel(); // create a panel JPanel p = new JPanel(); // create a slider b = new JSlider(0, 200, 120); // paint the ticks and tracks b.setPaintTrack(true); b.setPaintTicks(true); b.setPaintLabels(true); // set spacing b.setMajorTickSpacing(50); b.setMinorTickSpacing(5); // setChangeListener b.addChangeListener(s); // set orientation of slider b.setOrientation(SwingConstants.VERTICAL); // set Font for the slider b.setFont(new Font(\"Serif\", Font.ITALIC, 20)); // add slider to panel p.add(b); p.add(l); f.add(p); // set the text of label l.setText(\"value of Slider is =\" + b.getValue()); // set the size of frame f.setSize(300, 300); f.show(); } // if JSlider value is changed public void stateChanged(ChangeEvent e) { l.setText(\"value of Slider is =\" + b.getValue()); }}", "e": 11961, "s": 10391, "text": null }, { "code": null, "e": 11972, "s": 11961, "text": "Output : " }, { "code": null, "e": 12061, "s": 11972, "text": "Note : The above programs might not run in an online compiler please use an offline IDE " }, { "code": null, "e": 12075, "s": 12061, "text": "ManasChhabra2" }, { "code": null, "e": 12084, "s": 12075, "text": "sweetyty" }, { "code": null, "e": 12095, "s": 12084, "text": "java-swing" }, { "code": null, "e": 12100, "s": 12095, "text": "Java" }, { "code": null, "e": 12121, "s": 12100, "text": "Programming Language" }, { "code": null, "e": 12126, "s": 12121, "text": "Java" } ]
MultipleChoiceField – Django Forms
13 Feb, 2020 MultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings which you one can use for multiple purposes. MultipleChoiceField has one required argument: choices :- Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable. Syntax field_name = forms.MultipleChoiceField(**options) Illustration of MultipleChoiceField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. from django import forms DEMO_CHOICES =( ("1", "Naveen"), ("2", "Pranav"), ("3", "Isha"), ("4", "Saloni"),)class GeeksForm(forms.Form): geeks_field = forms.MultipleChoiceField(choices = DEMO_CHOICES) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field MultipleChoiceField is created by replacing “_” with ” “. It is a field to input of Choices from a list. MultipleChoiceField is used for input of Choices in the database. One can input Gender, etc. Till now we have discussed how to implement MultipleChoiceField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into the field into a python string instance. To get Github code of working MultipleChoiceField, click here. In views.py, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form']= form if request.POST: if form.is_valid(): temp = form.cleaned_data.get("geeks_field") print(temp) return render(request, "home.html", context) Let’s try selecting Choices data now. Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. You can check that data is converted to a python list of string instance in geeks_field. Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to MultipleChoiceField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2020" }, { "code": null, "e": 275, "s": 28, "text": "MultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings which you one can use for multiple purposes." }, { "code": null, "e": 322, "s": 275, "text": "MultipleChoiceField has one required argument:" }, { "code": null, "e": 443, "s": 322, "text": "choices :- Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable." }, { "code": null, "e": 450, "s": 443, "text": "Syntax" }, { "code": null, "e": 500, "s": 450, "text": "field_name = forms.MultipleChoiceField(**options)" }, { "code": null, "e": 620, "s": 500, "text": "Illustration of MultipleChoiceField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 707, "s": 620, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 758, "s": 707, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 791, "s": 758, "text": "How to Create an App in Django ?" }, { "code": null, "e": 849, "s": 791, "text": "Enter the following code into forms.py file of geeks app." }, { "code": "from django import forms DEMO_CHOICES =( (\"1\", \"Naveen\"), (\"2\", \"Pranav\"), (\"3\", \"Isha\"), (\"4\", \"Saloni\"),)class GeeksForm(forms.Form): geeks_field = forms.MultipleChoiceField(choices = DEMO_CHOICES) ", "e": 1070, "s": 849, "text": null }, { "code": null, "e": 1106, "s": 1070, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 1344, "s": 1106, "text": null }, { "code": null, "e": 1477, "s": 1344, "text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)", "e": 1689, "s": 1477, "text": null }, { "code": null, "e": 1975, "s": 1689, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method=\"POST\"> {% csrf_token %} {{ form.as_p }} <input type=\"submit\" value=\"Submit\"></form>", "e": 2082, "s": 1975, "text": null }, { "code": null, "e": 2128, "s": 2082, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]", "e": 2262, "s": 2128, "text": null }, { "code": null, "e": 2325, "s": 2262, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 2352, "s": 2325, "text": "Python manage.py runserver" }, { "code": null, "e": 2478, "s": 2352, "text": "Thus, an geeks_field MultipleChoiceField is created by replacing “_” with ” “. It is a field to input of Choices from a list." }, { "code": null, "e": 2868, "s": 2478, "text": "MultipleChoiceField is used for input of Choices in the database. One can input Gender, etc. Till now we have discussed how to implement MultipleChoiceField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into the field into a python string instance. To get Github code of working MultipleChoiceField, click here." }, { "code": null, "e": 2881, "s": 2868, "text": "In views.py," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form']= form if request.POST: if form.is_valid(): temp = form.cleaned_data.get(\"geeks_field\") print(temp) return render(request, \"home.html\", context)", "e": 3251, "s": 2881, "text": null }, { "code": null, "e": 3289, "s": 3251, "text": "Let’s try selecting Choices data now." }, { "code": null, "e": 3624, "s": 3289, "text": "Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. You can check that data is converted to a python list of string instance in geeks_field." }, { "code": null, "e": 4061, "s": 3624, "text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to MultipleChoiceField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:" }, { "code": null, "e": 4073, "s": 4061, "text": "NaveenArora" }, { "code": null, "e": 4086, "s": 4073, "text": "Django-forms" }, { "code": null, "e": 4100, "s": 4086, "text": "Python Django" }, { "code": null, "e": 4107, "s": 4100, "text": "Python" } ]
Logger isLoggable() method in Java with Examples
26 Mar, 2019 isLoggable() method of a Logger class is used to return a response in boolean value which provides an answer to the query that if a message of the given level would actually be logged by this logger or not. This check is based on the Loggers effective level, which may be inherited from its parent. Syntax: public boolean isLoggable(Level level) Parameters: This method accepts one parameter level which represents message logging level. Return value: This method returns true if the given message level is currently being logged. Below programs illustrate the isLoggable() method: Program 1: // Java program to demonstrate// Logger.isLoggable() method import java.util.logging.*; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) { // Check if the Level.INFO // is currently being logged. boolean flag = logger.isLoggable( Level.INFO); // Print value System.out.println("The Level.INFO" + " is currently being logged - " + flag); }} The Level.INFO is currently being logged - true Program 2: // Java program to demonstrate// Logger.isLoggable() method import java.util.logging.*; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) { // Check if the Level.OFF // is currently being logged. boolean flag = logger.isLoggable(Level.OFF); // Print value System.out.println("The Level.OFF" + " is currently being logged - " + flag); }} The Level.OFF is currently being logged - true Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#isLoggable(java.util.logging.Level) Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2019" }, { "code": null, "e": 327, "s": 28, "text": "isLoggable() method of a Logger class is used to return a response in boolean value which provides an answer to the query that if a message of the given level would actually be logged by this logger or not. This check is based on the Loggers effective level, which may be inherited from its parent." }, { "code": null, "e": 335, "s": 327, "text": "Syntax:" }, { "code": null, "e": 375, "s": 335, "text": "public boolean isLoggable(Level level)\n" }, { "code": null, "e": 467, "s": 375, "text": "Parameters: This method accepts one parameter level which represents message logging level." }, { "code": null, "e": 560, "s": 467, "text": "Return value: This method returns true if the given message level is currently being logged." }, { "code": null, "e": 611, "s": 560, "text": "Below programs illustrate the isLoggable() method:" }, { "code": null, "e": 622, "s": 611, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Logger.isLoggable() method import java.util.logging.*; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) { // Check if the Level.INFO // is currently being logged. boolean flag = logger.isLoggable( Level.INFO); // Print value System.out.println(\"The Level.INFO\" + \" is currently being logged - \" + flag); }}", "e": 1195, "s": 622, "text": null }, { "code": null, "e": 1244, "s": 1195, "text": "The Level.INFO is currently being logged - true\n" }, { "code": null, "e": 1255, "s": 1244, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Logger.isLoggable() method import java.util.logging.*; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) { // Check if the Level.OFF // is currently being logged. boolean flag = logger.isLoggable(Level.OFF); // Print value System.out.println(\"The Level.OFF\" + \" is currently being logged - \" + flag); }}", "e": 1809, "s": 1255, "text": null }, { "code": null, "e": 1857, "s": 1809, "text": "The Level.OFF is currently being logged - true\n" }, { "code": null, "e": 1977, "s": 1857, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#isLoggable(java.util.logging.Level)" }, { "code": null, "e": 1997, "s": 1977, "text": "Java - util package" }, { "code": null, "e": 2012, "s": 1997, "text": "Java-Functions" }, { "code": null, "e": 2024, "s": 2012, "text": "Java-Logger" }, { "code": null, "e": 2029, "s": 2024, "text": "Java" }, { "code": null, "e": 2034, "s": 2029, "text": "Java" }, { "code": null, "e": 2132, "s": 2034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2147, "s": 2132, "text": "Stream In Java" }, { "code": null, "e": 2168, "s": 2147, "text": "Introduction to Java" }, { "code": null, "e": 2189, "s": 2168, "text": "Constructors in Java" }, { "code": null, "e": 2208, "s": 2189, "text": "Exceptions in Java" }, { "code": null, "e": 2225, "s": 2208, "text": "Generics in Java" }, { "code": null, "e": 2255, "s": 2225, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2281, "s": 2255, "text": "Java Programming Examples" }, { "code": null, "e": 2297, "s": 2281, "text": "Strings in Java" }, { "code": null, "e": 2334, "s": 2297, "text": "Differences between JDK, JRE and JVM" } ]
Read XML file and print the details as tabular data by using JavaScript
27 Jul, 2021 Introduction:To read the XML file and print the details of an XML file in a Tabular form by using javaScript. We need to create an XML file which data we want to print. XML stands for Extensible Markup Language · It is a markup language much similar to HTML.The main purpose of the XML file for designed to store and transport the data. Creating an XML file is very simple because it uses custom tags. Prerequisites: Basic Knowledge HTML Basic Knowledge CSS Basic Knowledge JavaScript Knowledge XML Approach: After creating the XML file, we will write JavaScript to read and extract data from the file in tabular form. So, we will send the XMLHttpRequest to the server and fetch the details from the XML file by using JavaScript. If the request is finished then the response is ready and Status is “OK” so, we get the XML data by the use of Tag Name. Now we will create two files: 1.employee.xml: A xml file that stores the employee’s details.To create an xml file we use custom tags, here we use different custom tags like the first name, last name, title, division, etc. which store the details of every employee according to the tag name. employee.xml <?xml version="1.0" encoding="utf-8"?><employees> <employee id="be129"> <firstname>Jitendra</firstname> <lastname>Kumar</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>19</room> </employee> <employee id="be130"> <firstname>Amit</firstname> <lastname>Kumar</lastname> <title>Accountant</title> <division>Accts Payable</division> <building>326</building> <room>14</room> </employee> <employee id="be131"> <firstname>Akash</firstname> <lastname>Kumar</lastname> <title>Engineering Manager</title> <division>Materials</division> <building>327</building> <room>21</room> </employee> <employee id="be132"> <firstname>Aishwarya</firstname> <lastname>Kulshrestha</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>22</room> </employee> <employee id="be133"> <firstname>Sachin</firstname> <lastname>Kumar</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>24</room> </employee> <employee id="be135"> <firstname>Vikash</firstname> <lastname>kumar</lastname> <title>COO</title> <division>Management</division> <building>216</building> <room>26</room> </employee> <employee id="be136"> <firstname>Suvam</firstname> <lastname>Basak</lastname> <title>Accountant</title> <division>Accts Payable</division> <building>326</building> <room>30</room> </employee> <employee id="be135"> <firstname>Abhinav</firstname> <lastname>kumar</lastname> <title>COO</title> <division>Management</division> <building>216</building> <room>32</room> </employee> <employee id="be131"> <firstname>DhanPal</firstname> <lastname>Singh</lastname> <title>Engineering Manager</title> <division>Materials</division> <building>327</building> <room>21</room> </employee> </employees> 2.index.html: This file contains the HTML, CSS and JavaScript code. We use the style tag for the CSS part in which we are styling the table attribute and button after that we use the script tag in which we write the JavaScript code and insert the employee.xml file. In the loadXMLDoc( ) function we send the HTTP request to the server when the request is finished then we get the response from the server and access the data from an XML file. In empDetails( ) function if we get the response from the server then we fetch the XML file data one by one by using the custom tag name. To display the data of this xml file we simply click on the Get Employees details button and the xml file data will be displayed on your screen in tabular form. index.html <!DOCTYPE html> <head> <title>Reads the XML data using JavaScript</title> <!-- CSS --> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #7ce2af } th { background-color: #7c0f65; color: white; } .button { position: relative; text-align: center; padding: 20px; border: 4px solid rgb(55, 12, 211); background: rgba(20, 192, 4, 0.5); color: rgb(230, 36, 78); outline: none; border-radius: 30px; font-size: 30px; width: 500px; } .button:hover { color: black; background: white; } </style> <!--JavaScript--> <script> function loadXMLDoc() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { // Request finished and response // is ready and Status is "OK" if (this.readyState == 4 && this.status == 200) { empDetails(this); } }; // employee.xml is the external xml file xmlhttp.open("GET", "employee.xml", true); xmlhttp.send(); } function empDetails(xml) { var i; var xmlDoc = xml.responseXML; var table = `<tr><th>Firstname</th><th>Lastname</th> <th>Title</th><th>Division</th> <th>Building</th><th>Room</th> </tr>`; var x = xmlDoc.getElementsByTagName("employee"); // Start to fetch the data by using TagName for (i = 0; i < x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("firstname")[0] .childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("lastname")[0] .childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("title")[0] .childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("division")[0] .childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("building")[0] .childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("room")[0] .childNodes[0].nodeValue + "</td></tr>"; } // Print the xml data in table form document.getElementById("id").innerHTML = table; } </script></head> <body> <center> <button type="button" class="button" onclick="loadXMLDoc()"> Get Employees Details </button> </center> <br><br> <table id="id"></table></body> </html> Steps to run the application:To read the XML data we need to run this code on the local server So, first we start the local server and after it opens the chrome browser, start the local host and see the results. After clicking on the getting Employees Details button, we will get the Employees Details in a tabular form. Output: CSS-Properties CSS-Questions HTML and XML HTML-Questions JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jul, 2021" }, { "code": null, "e": 456, "s": 54, "text": "Introduction:To read the XML file and print the details of an XML file in a Tabular form by using javaScript. We need to create an XML file which data we want to print. XML stands for Extensible Markup Language · It is a markup language much similar to HTML.The main purpose of the XML file for designed to store and transport the data. Creating an XML file is very simple because it uses custom tags." }, { "code": null, "e": 471, "s": 456, "text": "Prerequisites:" }, { "code": null, "e": 492, "s": 471, "text": "Basic Knowledge HTML" }, { "code": null, "e": 512, "s": 492, "text": "Basic Knowledge CSS" }, { "code": null, "e": 539, "s": 512, "text": "Basic Knowledge JavaScript" }, { "code": null, "e": 553, "s": 539, "text": "Knowledge XML" }, { "code": null, "e": 905, "s": 553, "text": "Approach: After creating the XML file, we will write JavaScript to read and extract data from the file in tabular form. So, we will send the XMLHttpRequest to the server and fetch the details from the XML file by using JavaScript. If the request is finished then the response is ready and Status is “OK” so, we get the XML data by the use of Tag Name." }, { "code": null, "e": 935, "s": 905, "text": "Now we will create two files:" }, { "code": null, "e": 1196, "s": 935, "text": "1.employee.xml: A xml file that stores the employee’s details.To create an xml file we use custom tags, here we use different custom tags like the first name, last name, title, division, etc. which store the details of every employee according to the tag name." }, { "code": null, "e": 1209, "s": 1196, "text": "employee.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><employees> <employee id=\"be129\"> <firstname>Jitendra</firstname> <lastname>Kumar</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>19</room> </employee> <employee id=\"be130\"> <firstname>Amit</firstname> <lastname>Kumar</lastname> <title>Accountant</title> <division>Accts Payable</division> <building>326</building> <room>14</room> </employee> <employee id=\"be131\"> <firstname>Akash</firstname> <lastname>Kumar</lastname> <title>Engineering Manager</title> <division>Materials</division> <building>327</building> <room>21</room> </employee> <employee id=\"be132\"> <firstname>Aishwarya</firstname> <lastname>Kulshrestha</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>22</room> </employee> <employee id=\"be133\"> <firstname>Sachin</firstname> <lastname>Kumar</lastname> <title>Engineer</title> <division>Materials</division> <building>327</building> <room>24</room> </employee> <employee id=\"be135\"> <firstname>Vikash</firstname> <lastname>kumar</lastname> <title>COO</title> <division>Management</division> <building>216</building> <room>26</room> </employee> <employee id=\"be136\"> <firstname>Suvam</firstname> <lastname>Basak</lastname> <title>Accountant</title> <division>Accts Payable</division> <building>326</building> <room>30</room> </employee> <employee id=\"be135\"> <firstname>Abhinav</firstname> <lastname>kumar</lastname> <title>COO</title> <division>Management</division> <building>216</building> <room>32</room> </employee> <employee id=\"be131\"> <firstname>DhanPal</firstname> <lastname>Singh</lastname> <title>Engineering Manager</title> <division>Materials</division> <building>327</building> <room>21</room> </employee> </employees>", "e": 3424, "s": 1209, "text": null }, { "code": null, "e": 4166, "s": 3424, "text": "2.index.html: This file contains the HTML, CSS and JavaScript code. We use the style tag for the CSS part in which we are styling the table attribute and button after that we use the script tag in which we write the JavaScript code and insert the employee.xml file. In the loadXMLDoc( ) function we send the HTTP request to the server when the request is finished then we get the response from the server and access the data from an XML file. In empDetails( ) function if we get the response from the server then we fetch the XML file data one by one by using the custom tag name. To display the data of this xml file we simply click on the Get Employees details button and the xml file data will be displayed on your screen in tabular form." }, { "code": null, "e": 4177, "s": 4166, "text": "index.html" }, { "code": "<!DOCTYPE html> <head> <title>Reads the XML data using JavaScript</title> <!-- CSS --> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #7ce2af } th { background-color: #7c0f65; color: white; } .button { position: relative; text-align: center; padding: 20px; border: 4px solid rgb(55, 12, 211); background: rgba(20, 192, 4, 0.5); color: rgb(230, 36, 78); outline: none; border-radius: 30px; font-size: 30px; width: 500px; } .button:hover { color: black; background: white; } </style> <!--JavaScript--> <script> function loadXMLDoc() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { // Request finished and response // is ready and Status is \"OK\" if (this.readyState == 4 && this.status == 200) { empDetails(this); } }; // employee.xml is the external xml file xmlhttp.open(\"GET\", \"employee.xml\", true); xmlhttp.send(); } function empDetails(xml) { var i; var xmlDoc = xml.responseXML; var table = `<tr><th>Firstname</th><th>Lastname</th> <th>Title</th><th>Division</th> <th>Building</th><th>Room</th> </tr>`; var x = xmlDoc.getElementsByTagName(\"employee\"); // Start to fetch the data by using TagName for (i = 0; i < x.length; i++) { table += \"<tr><td>\" + x[i].getElementsByTagName(\"firstname\")[0] .childNodes[0].nodeValue + \"</td><td>\" + x[i].getElementsByTagName(\"lastname\")[0] .childNodes[0].nodeValue + \"</td><td>\" + x[i].getElementsByTagName(\"title\")[0] .childNodes[0].nodeValue + \"</td><td>\" + x[i].getElementsByTagName(\"division\")[0] .childNodes[0].nodeValue + \"</td><td>\" + x[i].getElementsByTagName(\"building\")[0] .childNodes[0].nodeValue + \"</td><td>\" + x[i].getElementsByTagName(\"room\")[0] .childNodes[0].nodeValue + \"</td></tr>\"; } // Print the xml data in table form document.getElementById(\"id\").innerHTML = table; } </script></head> <body> <center> <button type=\"button\" class=\"button\" onclick=\"loadXMLDoc()\"> Get Employees Details </button> </center> <br><br> <table id=\"id\"></table></body> </html>", "e": 7206, "s": 4177, "text": null }, { "code": null, "e": 7528, "s": 7206, "text": "Steps to run the application:To read the XML data we need to run this code on the local server So, first we start the local server and after it opens the chrome browser, start the local host and see the results. After clicking on the getting Employees Details button, we will get the Employees Details in a tabular form." }, { "code": null, "e": 7536, "s": 7528, "text": "Output:" }, { "code": null, "e": 7551, "s": 7536, "text": "CSS-Properties" }, { "code": null, "e": 7565, "s": 7551, "text": "CSS-Questions" }, { "code": null, "e": 7578, "s": 7565, "text": "HTML and XML" }, { "code": null, "e": 7593, "s": 7578, "text": "HTML-Questions" }, { "code": null, "e": 7614, "s": 7593, "text": "JavaScript-Questions" }, { "code": null, "e": 7618, "s": 7614, "text": "CSS" }, { "code": null, "e": 7623, "s": 7618, "text": "HTML" }, { "code": null, "e": 7634, "s": 7623, "text": "JavaScript" }, { "code": null, "e": 7651, "s": 7634, "text": "Web Technologies" }, { "code": null, "e": 7656, "s": 7651, "text": "HTML" }, { "code": null, "e": 7754, "s": 7656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7793, "s": 7754, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 7832, "s": 7793, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7871, "s": 7832, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 7900, "s": 7871, "text": "Form validation using jQuery" }, { "code": null, "e": 7937, "s": 7900, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 7961, "s": 7937, "text": "REST API (Introduction)" }, { "code": null, "e": 8014, "s": 7961, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 8074, "s": 8014, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 8135, "s": 8074, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
homogeneity_score using sklearn in Python
01 Oct, 2020 An entirely homogeneous clustering is one where each cluster has information that directs a place toward a similar class label. Homogeneity portrays the closeness of the clustering algorithm to this (homogeneity_score) perfection. This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way. Syntax : sklearn.metrics.homogeneity_score(labels_true, labels_pred) The Metric is not symmetric, switching label_true with label_pred will return the completeness_score. Parameters : labels_true:<int array, shape = [n_samples]> : It accept the ground truth class labels to be used as a reference. labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate. Returns: homogeneity:<float>: Its return the score between 0.0 and 1.0 stands for perfectly homogeneous labeling. Example1: Python3 import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import homogeneity_score # Changing the location file# cd C:\Users\Dev\Desktop\Credit Card Fraud # Loading the datadf = pd.read_csv('creditcard.csv') # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis=1) # Building the clustering modelkmeans = KMeans(n_clusters=2) # Training the clustering modelkmeans.fit(X) # Storing the predicted Clustering labelslabels = kmeans.predict(X) # Evaluating the performancehomogeneity_score(y, labels) Output: 0.00496764949717645 Example 2: Perfectly homogeneous: Python3 from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 1, 0, 1], [1, 0, 1, 0]) print(hscore) Output: 1.0 Example 3: Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous: Python3 from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3]) print(hscore) Output: 0.9999999999999999 Example 4: Include samples from different classes don’t make for homogeneous labeling: Python3 from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1]) print(hscore) Output: 0.0 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 260, "s": 28, "text": "An entirely homogeneous clustering is one where each cluster has information that directs a place toward a similar class label. Homogeneity portrays the closeness of the clustering algorithm to this (homogeneity_score) perfection. " }, { "code": null, "e": 407, "s": 260, "text": "This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way." }, { "code": null, "e": 476, "s": 407, "text": "Syntax : sklearn.metrics.homogeneity_score(labels_true, labels_pred)" }, { "code": null, "e": 578, "s": 476, "text": "The Metric is not symmetric, switching label_true with label_pred will return the completeness_score." }, { "code": null, "e": 591, "s": 578, "text": "Parameters :" }, { "code": null, "e": 705, "s": 591, "text": "labels_true:<int array, shape = [n_samples]> : It accept the ground truth class labels to be used as a reference." }, { "code": null, "e": 797, "s": 705, "text": "labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate." }, { "code": null, "e": 806, "s": 797, "text": "Returns:" }, { "code": null, "e": 911, "s": 806, "text": "homogeneity:<float>: Its return the score between 0.0 and 1.0 stands for perfectly homogeneous labeling." }, { "code": null, "e": 921, "s": 911, "text": "Example1:" }, { "code": null, "e": 929, "s": 921, "text": "Python3" }, { "code": "import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import homogeneity_score # Changing the location file# cd C:\\Users\\Dev\\Desktop\\Credit Card Fraud # Loading the datadf = pd.read_csv('creditcard.csv') # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis=1) # Building the clustering modelkmeans = KMeans(n_clusters=2) # Training the clustering modelkmeans.fit(X) # Storing the predicted Clustering labelslabels = kmeans.predict(X) # Evaluating the performancehomogeneity_score(y, labels)", "e": 1520, "s": 929, "text": null }, { "code": null, "e": 1528, "s": 1520, "text": "Output:" }, { "code": null, "e": 1549, "s": 1528, "text": "0.00496764949717645\n" }, { "code": null, "e": 1583, "s": 1549, "text": "Example 2: Perfectly homogeneous:" }, { "code": null, "e": 1591, "s": 1583, "text": "Python3" }, { "code": "from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 1, 0, 1], [1, 0, 1, 0]) print(hscore)", "e": 1736, "s": 1591, "text": null }, { "code": null, "e": 1744, "s": 1736, "text": "Output:" }, { "code": null, "e": 1749, "s": 1744, "text": "1.0\n" }, { "code": null, "e": 1858, "s": 1749, "text": "Example 3: Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous:" }, { "code": null, "e": 1866, "s": 1858, "text": "Python3" }, { "code": "from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3]) print(hscore)", "e": 2011, "s": 1866, "text": null }, { "code": null, "e": 2019, "s": 2011, "text": "Output:" }, { "code": null, "e": 2039, "s": 2019, "text": "0.9999999999999999\n" }, { "code": null, "e": 2126, "s": 2039, "text": "Example 4: Include samples from different classes don’t make for homogeneous labeling:" }, { "code": null, "e": 2134, "s": 2126, "text": "Python3" }, { "code": "from sklearn.metrics.cluster import homogeneity_score # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1]) print(hscore)", "e": 2279, "s": 2134, "text": null }, { "code": null, "e": 2287, "s": 2279, "text": "Output:" }, { "code": null, "e": 2292, "s": 2287, "text": "0.0\n" }, { "code": null, "e": 2307, "s": 2292, "text": "python-utility" }, { "code": null, "e": 2314, "s": 2307, "text": "Python" } ]
How to make an ArrayList read only in Java
11 Dec, 2018 Given an ArrayList, the task is to make this ArrayList read-only in Java. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: Read-only ArrayList: [1, 2, 3, 4, 5] Input: ArrayList: [geeks, for, geeks] Output: Read-only ArrayList: [geeks, for, geeks] An ArrayList can be made read-only easily with the help of Collections.unmodifiableList() method. This method takes the modifiable ArrayList as a parameter and returns the read-only unmodifiable view of this ArrayList. Syntax: readOnlyArrayList = Collections.unmodifiableList(ArrayList); Below is the implementation of the above approach: // Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); list.add('Z'); // printing the list System.out.println("Initial list: " + list); // getting readonly list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // printing the list System.out.println("ReadOnly ArrayList: " + immutablelist); // Adding element to new Collection System.out.println("\nTrying to modify" + " the ReadOnly ArrayList."); immutablelist.add('A'); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }} Initial list: [X, Y, Z] ReadOnly ArrayList: [X, Y, Z] Trying to modify the ReadOnly ArrayList. Exception thrown : java.lang.UnsupportedOperationException Java-ArrayList Java-Collections Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Dec, 2018" }, { "code": null, "e": 126, "s": 52, "text": "Given an ArrayList, the task is to make this ArrayList read-only in Java." }, { "code": null, "e": 136, "s": 126, "text": "Examples:" }, { "code": null, "e": 305, "s": 136, "text": "Input: ArrayList: [1, 2, 3, 4, 5]\nOutput: Read-only ArrayList: [1, 2, 3, 4, 5] \n\nInput: ArrayList: [geeks, for, geeks]\nOutput: Read-only ArrayList: [geeks, for, geeks]\n" }, { "code": null, "e": 524, "s": 305, "text": "An ArrayList can be made read-only easily with the help of Collections.unmodifiableList() method. This method takes the modifiable ArrayList as a parameter and returns the read-only unmodifiable view of this ArrayList." }, { "code": null, "e": 532, "s": 524, "text": "Syntax:" }, { "code": null, "e": 593, "s": 532, "text": "readOnlyArrayList = Collections.unmodifiableList(ArrayList);" }, { "code": null, "e": 644, "s": 593, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); list.add('Z'); // printing the list System.out.println(\"Initial list: \" + list); // getting readonly list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // printing the list System.out.println(\"ReadOnly ArrayList: \" + immutablelist); // Adding element to new Collection System.out.println(\"\\nTrying to modify\" + \" the ReadOnly ArrayList.\"); immutablelist.add('A'); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 1857, "s": 644, "text": null }, { "code": null, "e": 2013, "s": 1857, "text": "Initial list: [X, Y, Z]\nReadOnly ArrayList: [X, Y, Z]\n\nTrying to modify the ReadOnly ArrayList.\nException thrown : java.lang.UnsupportedOperationException\n" }, { "code": null, "e": 2028, "s": 2013, "text": "Java-ArrayList" }, { "code": null, "e": 2045, "s": 2028, "text": "Java-Collections" }, { "code": null, "e": 2064, "s": 2045, "text": "Java-List-Programs" }, { "code": null, "e": 2069, "s": 2064, "text": "Java" }, { "code": null, "e": 2074, "s": 2069, "text": "Java" }, { "code": null, "e": 2091, "s": 2074, "text": "Java-Collections" } ]
Dash Framework
In this chapter, we will discuss about the Dash framework in detail. Dash is an open-source Python framework used for building analytical web applications. It is a powerful library that simplifies the development of data-driven applications. It’s especially useful for Python data scientists who aren’t very familiar with web development. Users can create amazing dashboards in their browser using dash. Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders and graphs directly to your analytical python code. Dash apps consist of a Flask server that communicates with front-end React components using JSON packets over HTTP requests. Dash applications are written purely in python, so NO HTML or JavaScript is necessary. If Dash is not already installed in your terminal, then install the below mentioned Dash libraries. As these libraries are under active development, install and upgrade then frequently. Python 2 and 3 are also supported. pip install dash==0.23.1 # The core dash backend pip install dash-renderer==0.13.0 # The dash front-end pip install dash-html-components==0.11.0 # HTML components pip install dash-core-components==0.26.0 # Supercharged components pip install plotly==3.1.0 # Plotly graphing library In order to make sure everything is working properly, here, we created a simple dashApp.py file. Dash apps are composed of two parts. The first part is the “layout” of the app which basically describes how the application looks like. The second part describes the interactivity of the application. We can build the layout with the dash_html_components and the dash_core_components library. Dash provides python classes for all the visual components of the application. We can also customize our own components with JavaScript and React.js. import dash_core_components as dcc import dash_html_components as html The dash_html_components is for all HTML tags where the dash_core_components is for interactivity built with React.js. Using above two libraries, let us write a code as given below − app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children='''Dash Framework: A web application framework for Python.''') And the equivalent HTML code would look like this − <div> <h1> Hello Dash </h1> <div> Dash Framework: A web application framework for Python. </div> </div> We will learn how to write a simple example on dash using above mentioned library in a file dashApp.py. # -*- coding: utf-8 -*- import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children='''Dash Framework: A web application framework for Python.'''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': { 'title': 'Dash Data Visualization' } } ) ]) if __name__ == '__main__': app.run_server(debug=True) Note the following points while running the Dash app. (MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py Serving Flask app "dashApp1" (lazy loading) Serving Flask app "dashApp1" (lazy loading) Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. Debug mode: on Debug mode: on Restarting with stat Restarting with stat Debugger is active! Debugger is active! Debugger PIN: 130-303-947 Debugger PIN: 130-303-947 Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) 127.0.0.1 - - [12/Aug/2018 09:32:39] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-layout HTTP/1.1" 200 - 127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-dependencies HTTP/1.1" 200 - 127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /favicon.ico HTTP/1.1" 200 - 127.0.0.1 - - [12/Aug/2018 09:39:52] "GET /favicon.ico HTTP/1.1" 200 - Visit http:127.0.0.1:8050/ in your web browser. You should see an app that looks like this. In above program, few important points to be noted are as follows − The app layout is composed of a tree of “components” like html.Div and dcc.Graph. The app layout is composed of a tree of “components” like html.Div and dcc.Graph. The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application. The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application. Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library. Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library. Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes. Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes. The children property is special. By convention, it’s always the first attribute which means that you can omit it. The children property is special. By convention, it’s always the first attribute which means that you can omit it. Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’). Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’). The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice − app.css.append_css ({“external_url”:https://codepen.io/chriddyp/pen/bwLwgP.css}) to get your file to get the same look and feel of these examples. The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice − app.css.append_css ({“external_url”:https://codepen.io/chriddyp/pen/bwLwgP.css}) to get your file to get the same look and feel of these examples. The dash_html_components library contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments. Let us add the inline style of the components in our previous app text − # -*- coding: utf-8 -*- import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() colors = { 'background': '#87D653', 'text': '#ff0033' } app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[ html.H1( children='Hello Dash', style={ 'textAlign': 'center', 'color': colors['text'] } ), html.Div(children='Dash: A web application framework for Python.', style={ 'textAlign': 'center', 'color': colors['text'] }), dcc.Graph( id='example-graph-2', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': { 'plot_bgcolor': colors['background'], 'paper_bgcolor': colors['background'], 'font': { 'color': colors['text'] } } } ) ]) if __name__ == '__main__': app.run_server(debug=True) In the above example, we modified the inline styles of the html.Div and html.H1 components with the style property. It is rendered in the Dash application as follows − There are couple of key distinctions between dash_html_components and HTML attributes − For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string. For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string. Style dictionary keys are camelCased, so text-align changes to textalign. Style dictionary keys are camelCased, so text-align changes to textalign. ClassName in Dash is similar to HTML class attribute. ClassName in Dash is similar to HTML class attribute. The first argument is the children of the HTML tag which is specified through the children keyword argument. The first argument is the children of the HTML tag which is specified through the children keyword argument. By writing our markup in Python, we can create complex reusable components like tables without switching contexts or languages − Below is a quick example that generates a “Table” from pandas dataframe. import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') def generate_table(dataframe, max_rows=10): return html.Table( # Header [html.Tr([html.Th(col) for col in dataframe.columns])] + # Body [html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns ]) for i in range(min(len(dataframe), max_rows))] ) app = dash.Dash() app.layout = html.Div(children=[ html.H4(children='US Agriculture Exports (2011)'), generate_table(df) ]) if __name__ == '__main__': app.run_server(debug=True) Our output will be something like − The dash_core_components library includes a component called Graph. Graph renders interactive data visualizations using the open source plotly.js JavaScript graphing library. Plotly.js support around 35 chart types and renders charts in both vector-quality SVG and high-performance WebGL. Below is an example that creates a scatter plot from a Pandas dataframe − import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.graph_objs as go app = dash.Dash() df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' + '5d1ea79569ed194d432e56108a04d188/raw/' + 'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+ 'gdp-life-exp-2007.csv') app.layout = html.Div([ dcc.Graph( id='life-exp-vs-gdp', figure={ 'data': [ go.Scatter( x=df[df['continent'] == i]['gdp per capita'], y=df[df['continent'] == i]['life expectancy'], text=df[df['continent'] == i]['country'], mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': 0.5, 'color': 'white'} }, name=i ) for i in df.continent.unique() ], 'layout': go.Layout( xaxis={'type': 'log', 'title': 'GDP Per Capita'}, yaxis={'title': 'Life Expectancy'}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' ) } ) ]) if __name__ == '__main__': app.run_server() The output of the above code is as follows − These graphs are interactive and responsive. You can hover over points to see their values, click on legend items to toggle traces, click and drag to zoom, hold down shift, and click and drag to pan. While dash exposes HTML flavours through the dash_html_components library, it can be tedious to write your copy in HTML. For writing blocks of texts, you can use the Markdown component in the dash_core_components library. The dash_core_components includes a set of higher-level components like dropdowns, graphs, markdown, blocks and many more. Like all other Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component. Below is the example, using some of the available components − # -*- coding: utf-8 -*- import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() app.layout = html.Div([ html.Label('Dropdown'), dcc.Dropdown( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': u'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value='MTL' ), html.Label('Multi-Select Dropdown'), dcc.Dropdown( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': u'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value=['MTL', 'SF'], multi=True ), html.Label('Radio Items'), dcc.RadioItems( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': u'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value='MTL' ), html.Label('Checkboxes'), dcc.Checklist( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': u'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], values=['MTL', 'SF'] ), html.Label('Text Input'), dcc.Input(value='MTL', type='text'), html.Label('Slider'), dcc.Slider( min=0, max=9, marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)}, value=5, ), ], style={'columnCount': 2}) if __name__ == '__main__': app.run_server(debug=True) Output from the above program is as follows − Dash components are declarative. Every configurable aspect of these components is set during installation as a keyword argument. You can call help in your python console on any of the components to learn more about a component and its available arguments. Some of them are given below − >>> help(dcc.Dropdown) Help on class Dropdown in module builtins: class Dropdown(dash.development.base_component.Component) | A Dropdown component. | Dropdown is an interactive dropdown element for selecting one or more | items. | The values and labels of the dropdown items are specified in the `options` | property and the selected item(s) are specified with the `value` property. | | Use a dropdown when you have many options (more than 5) or when you are | constrained for space. Otherwise, you can use RadioItems or a Checklist, | which have the benefit of showing the users all of the items at once. | | Keyword arguments: | - id (string; optional) | - options (list; optional): An array of options | - value (string | list; optional): The value of the input. If `multi` is false (the default) -- More -- To summarize, the layout of a Dash app describes what the app looks like. The layout is a hierarchical tree of components. The dash_html_components library provides classes for all the HTML tags and the keyword arguments, and describes the HTML attributes like style, className, and id. The dash_core_components library generates higher-level components like controls and graphs.
[ { "code": null, "e": 1894, "s": 1825, "text": "In this chapter, we will discuss about the Dash framework in detail." }, { "code": null, "e": 2229, "s": 1894, "text": "Dash is an open-source Python framework used for building analytical web applications. It is a powerful library that simplifies the development of data-driven applications. It’s especially useful for Python data scientists who aren’t very familiar with web development. Users can create amazing dashboards in their browser using dash." }, { "code": null, "e": 2379, "s": 2229, "text": "Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders and graphs directly to your analytical python code." }, { "code": null, "e": 2504, "s": 2379, "text": "Dash apps consist of a Flask server that communicates with front-end React components using JSON packets over HTTP requests." }, { "code": null, "e": 2591, "s": 2504, "text": "Dash applications are written purely in python, so NO HTML or JavaScript is necessary." }, { "code": null, "e": 2812, "s": 2591, "text": "If Dash is not already installed in your terminal, then install the below mentioned Dash libraries. As these libraries are under active development, install and upgrade then frequently. Python 2 and 3 are also supported." }, { "code": null, "e": 2861, "s": 2812, "text": "pip install dash==0.23.1 # The core dash backend" }, { "code": null, "e": 2916, "s": 2861, "text": "pip install dash-renderer==0.13.0 # The dash front-end" }, { "code": null, "e": 2975, "s": 2916, "text": "pip install dash-html-components==0.11.0 # HTML components" }, { "code": null, "e": 3042, "s": 2975, "text": "pip install dash-core-components==0.26.0 # Supercharged components" }, { "code": null, "e": 3094, "s": 3042, "text": "pip install plotly==3.1.0 # Plotly graphing library" }, { "code": null, "e": 3191, "s": 3094, "text": "In order to make sure everything is working properly, here, we created a simple dashApp.py file." }, { "code": null, "e": 3392, "s": 3191, "text": "Dash apps are composed of two parts. The first part is the “layout” of the app which basically describes how the application looks like. The second part describes the interactivity of the application." }, { "code": null, "e": 3634, "s": 3392, "text": "We can build the layout with the dash_html_components and the dash_core_components library. Dash provides python classes for all the visual components of the application. We can also customize our own components with JavaScript and React.js." }, { "code": null, "e": 3669, "s": 3634, "text": "import dash_core_components as dcc" }, { "code": null, "e": 3705, "s": 3669, "text": "import dash_html_components as html" }, { "code": null, "e": 3824, "s": 3705, "text": "The dash_html_components is for all HTML tags where the dash_core_components is for interactivity built with React.js." }, { "code": null, "e": 3888, "s": 3824, "text": "Using above two libraries, let us write a code as given below −" }, { "code": null, "e": 4059, "s": 3888, "text": "app = dash.Dash()\napp.layout = html.Div(children=[\n html.H1(children='Hello Dash'),\n html.Div(children='''Dash Framework: A web application framework for Python.''')\n" }, { "code": null, "e": 4111, "s": 4059, "text": "And the equivalent HTML code would look like this −" }, { "code": null, "e": 4222, "s": 4111, "text": "<div>\n <h1> Hello Dash </h1>\n <div> Dash Framework: A web application framework for Python. </div>\n</div>\n" }, { "code": null, "e": 4326, "s": 4222, "text": "We will learn how to write a simple example on dash using above mentioned library in a file dashApp.py." }, { "code": null, "e": 5004, "s": 4326, "text": "# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\napp = dash.Dash()\napp.layout = html.Div(children=[\n html.H1(children='Hello Dash'),\n html.Div(children='''Dash Framework: A web application framework for Python.'''),\n\t\n dcc.Graph(\n id='example-graph',\n figure={\n 'data': [\n {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},\n {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},\n ],\n 'layout': {\n 'title': 'Dash Data Visualization'\n }\n }\n )\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)" }, { "code": null, "e": 5058, "s": 5004, "text": "Note the following points while running the Dash app." }, { "code": null, "e": 5129, "s": 5058, "text": "(MyDjangoEnv) C:\\Users\\rajesh\\Desktop\\MyDjango\\dash>python dashApp1.py" }, { "code": null, "e": 5173, "s": 5129, "text": "Serving Flask app \"dashApp1\" (lazy loading)" }, { "code": null, "e": 5217, "s": 5173, "text": "Serving Flask app \"dashApp1\" (lazy loading)" }, { "code": null, "e": 5351, "s": 5217, "text": "Environment: production\nWARNING: Do not use the development server in a production environment.\nUse a production WSGI server instead." }, { "code": null, "e": 5375, "s": 5351, "text": "Environment: production" }, { "code": null, "e": 5447, "s": 5375, "text": "WARNING: Do not use the development server in a production environment." }, { "code": null, "e": 5485, "s": 5447, "text": "Use a production WSGI server instead." }, { "code": null, "e": 5500, "s": 5485, "text": "Debug mode: on" }, { "code": null, "e": 5515, "s": 5500, "text": "Debug mode: on" }, { "code": null, "e": 5536, "s": 5515, "text": "Restarting with stat" }, { "code": null, "e": 5557, "s": 5536, "text": "Restarting with stat" }, { "code": null, "e": 5577, "s": 5557, "text": "Debugger is active!" }, { "code": null, "e": 5597, "s": 5577, "text": "Debugger is active!" }, { "code": null, "e": 5623, "s": 5597, "text": "Debugger PIN: 130-303-947" }, { "code": null, "e": 5649, "s": 5623, "text": "Debugger PIN: 130-303-947" }, { "code": null, "e": 5706, "s": 5649, "text": "Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)" }, { "code": null, "e": 5763, "s": 5706, "text": "Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)" }, { "code": null, "e": 6116, "s": 5763, "text": "127.0.0.1 - - [12/Aug/2018 09:32:39] \"GET / HTTP/1.1\" 200 -\n127.0.0.1 - - [12/Aug/2018 09:32:42] \"GET /_dash-layout HTTP/1.1\" 200 -\n127.0.0.1 - - [12/Aug/2018 09:32:42] \"GET /_dash-dependencies HTTP/1.1\" 200 -\n127.0.0.1 - - [12/Aug/2018 09:32:42] \"GET /favicon.ico HTTP/1.1\" 200 -\n127.0.0.1 - - [12/Aug/2018 09:39:52] \"GET /favicon.ico HTTP/1.1\" 200 -\n" }, { "code": null, "e": 6208, "s": 6116, "text": "Visit http:127.0.0.1:8050/ in your web browser. You should see an app that looks like this." }, { "code": null, "e": 6276, "s": 6208, "text": "In above program, few important points to be noted are as follows −" }, { "code": null, "e": 6358, "s": 6276, "text": "The app layout is composed of a tree of “components” like html.Div and dcc.Graph." }, { "code": null, "e": 6440, "s": 6358, "text": "The app layout is composed of a tree of “components” like html.Div and dcc.Graph." }, { "code": null, "e": 6625, "s": 6440, "text": "The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application." }, { "code": null, "e": 6810, "s": 6625, "text": "The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application." }, { "code": null, "e": 7002, "s": 6810, "text": "Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library." }, { "code": null, "e": 7194, "s": 7002, "text": "Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library." }, { "code": null, "e": 7351, "s": 7194, "text": "Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes." }, { "code": null, "e": 7508, "s": 7351, "text": "Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes." }, { "code": null, "e": 7623, "s": 7508, "text": "The children property is special. By convention, it’s always the first attribute which means that you can omit it." }, { "code": null, "e": 7738, "s": 7623, "text": "The children property is special. By convention, it’s always the first attribute which means that you can omit it." }, { "code": null, "e": 7809, "s": 7738, "text": "Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’)." }, { "code": null, "e": 7880, "s": 7809, "text": "Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’)." }, { "code": null, "e": 8317, "s": 7880, "text": "The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice −\napp.css.append_css ({“external_url”:https://codepen.io/chriddyp/pen/bwLwgP.css}) to get your file to get the same look and feel of these examples." }, { "code": null, "e": 8607, "s": 8317, "text": "The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice −" }, { "code": null, "e": 8754, "s": 8607, "text": "app.css.append_css ({“external_url”:https://codepen.io/chriddyp/pen/bwLwgP.css}) to get your file to get the same look and feel of these examples." }, { "code": null, "e": 8893, "s": 8754, "text": "The dash_html_components library contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments." }, { "code": null, "e": 8966, "s": 8893, "text": "Let us add the inline style of the components in our previous app text −" }, { "code": null, "e": 10048, "s": 8966, "text": "# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\napp = dash.Dash()\ncolors = {\n 'background': '#87D653',\n 'text': '#ff0033'\n}\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n html.H1(\n children='Hello Dash',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n\t\n html.Div(children='Dash: A web application framework for Python.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\t\n dcc.Graph(\n id='example-graph-2',\n\n figure={\n 'data': [\n {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},\n {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},\n ],\n 'layout': {\n 'plot_bgcolor': colors['background'],\n 'paper_bgcolor': colors['background'],\n 'font': {\n 'color': colors['text']\n }\n }\n }\n )\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)" }, { "code": null, "e": 10164, "s": 10048, "text": "In the above example, we modified the inline styles of the html.Div and html.H1 components with the style property." }, { "code": null, "e": 10216, "s": 10164, "text": "It is rendered in the Dash application as follows −" }, { "code": null, "e": 10304, "s": 10216, "text": "There are couple of key distinctions between dash_html_components and HTML attributes −" }, { "code": null, "e": 10417, "s": 10304, "text": "For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string." }, { "code": null, "e": 10530, "s": 10417, "text": "For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string." }, { "code": null, "e": 10604, "s": 10530, "text": "Style dictionary keys are camelCased, so text-align changes to textalign." }, { "code": null, "e": 10678, "s": 10604, "text": "Style dictionary keys are camelCased, so text-align changes to textalign." }, { "code": null, "e": 10732, "s": 10678, "text": "ClassName in Dash is similar to HTML class attribute." }, { "code": null, "e": 10786, "s": 10732, "text": "ClassName in Dash is similar to HTML class attribute." }, { "code": null, "e": 10895, "s": 10786, "text": "The first argument is the children of the HTML tag which is specified through the children keyword argument." }, { "code": null, "e": 11004, "s": 10895, "text": "The first argument is the children of the HTML tag which is specified through the children keyword argument." }, { "code": null, "e": 11133, "s": 11004, "text": "By writing our markup in Python, we can create complex reusable components like tables without switching contexts or languages −" }, { "code": null, "e": 11206, "s": 11133, "text": "Below is a quick example that generates a “Table” from pandas dataframe." }, { "code": null, "e": 12005, "s": 11206, "text": "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\n\ndf = pd.read_csv(\n 'https://gist.githubusercontent.com/chriddyp/'\n 'c78bf172206ce24f77d6363a2d754b59/raw/'\n 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'\n 'usa-agricultural-exports-2011.csv')\n\t\ndef generate_table(dataframe, max_rows=10):\n return html.Table(\n # Header\n [html.Tr([html.Th(col) for col in dataframe.columns])] +\n # Body\n [html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))]\n )\n\t\napp = dash.Dash()\napp.layout = html.Div(children=[\n html.H4(children='US Agriculture Exports (2011)'),\n generate_table(df)\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)" }, { "code": null, "e": 12041, "s": 12005, "text": "Our output will be something like −" }, { "code": null, "e": 12109, "s": 12041, "text": "The dash_core_components library includes a component called Graph." }, { "code": null, "e": 12330, "s": 12109, "text": "Graph renders interactive data visualizations using the open source plotly.js JavaScript graphing library. Plotly.js support around 35 chart types and renders charts in both vector-quality SVG and high-performance WebGL." }, { "code": null, "e": 12404, "s": 12330, "text": "Below is an example that creates a scatter plot from a Pandas dataframe −" }, { "code": null, "e": 13665, "s": 12404, "text": "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objs as go\n\napp = dash.Dash()\n\ndf = pd.read_csv(\n 'https://gist.githubusercontent.com/chriddyp/' +\n '5d1ea79569ed194d432e56108a04d188/raw/' +\n 'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+\n 'gdp-life-exp-2007.csv')\n\t\napp.layout = html.Div([\n dcc.Graph(\n id='life-exp-vs-gdp',\n figure={\n 'data': [\n go.Scatter(\n x=df[df['continent'] == i]['gdp per capita'],\n y=df[df['continent'] == i]['life expectancy'],\n text=df[df['continent'] == i]['country'],\n mode='markers',\n opacity=0.7,\n marker={\n 'size': 15,\n 'line': {'width': 0.5, 'color': 'white'}\n },\n name=i\n ) for i in df.continent.unique()\n ],\n 'layout': go.Layout(\n xaxis={'type': 'log', 'title': 'GDP Per Capita'},\n yaxis={'title': 'Life Expectancy'},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n hovermode='closest'\n )\n }\n )\n])\n\nif __name__ == '__main__':\n app.run_server()" }, { "code": null, "e": 13710, "s": 13665, "text": "The output of the above code is as follows −" }, { "code": null, "e": 13910, "s": 13710, "text": "These graphs are interactive and responsive. You can hover over points to see their values, click on legend items to toggle traces, click and drag to zoom, hold down shift, and click and drag to pan." }, { "code": null, "e": 14132, "s": 13910, "text": "While dash exposes HTML flavours through the dash_html_components library, it can be tedious to write your copy in HTML. For writing blocks of texts, you can use the Markdown component in the dash_core_components library." }, { "code": null, "e": 14255, "s": 14132, "text": "The dash_core_components includes a set of higher-level components like dropdowns, graphs, markdown, blocks and many more." }, { "code": null, "e": 14417, "s": 14255, "text": "Like all other Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component." }, { "code": null, "e": 14480, "s": 14417, "text": "Below is the example, using some of the available components −" }, { "code": null, "e": 16009, "s": 14480, "text": "# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\napp = dash.Dash()\n\napp.layout = html.Div([\n html.Label('Dropdown'),\n dcc.Dropdown(\n options=[\n {'label': 'New York City', 'value': 'NYC'},\n {'label': u'Montréal', 'value': 'MTL'},\n {'label': 'San Francisco', 'value': 'SF'}\n ],\n value='MTL'\n ),\n\t\n html.Label('Multi-Select Dropdown'),\n dcc.Dropdown(\n options=[\n {'label': 'New York City', 'value': 'NYC'},\n {'label': u'Montréal', 'value': 'MTL'},\n {'label': 'San Francisco', 'value': 'SF'}\n ],\n value=['MTL', 'SF'],\n multi=True\n ),\n\t\n html.Label('Radio Items'),\n dcc.RadioItems(\n options=[\n {'label': 'New York City', 'value': 'NYC'},\n {'label': u'Montréal', 'value': 'MTL'},\n {'label': 'San Francisco', 'value': 'SF'}\n ],\n value='MTL'\n ),\n\t\n html.Label('Checkboxes'),\n dcc.Checklist(\n options=[\n {'label': 'New York City', 'value': 'NYC'},\n {'label': u'Montréal', 'value': 'MTL'},\n {'label': 'San Francisco', 'value': 'SF'}\n ],\n values=['MTL', 'SF']\n ),\n\n html.Label('Text Input'),\n dcc.Input(value='MTL', type='text'),\n\t\n html.Label('Slider'),\n dcc.Slider(\n min=0,\n max=9,\n marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n value=5,\n ),\n], style={'columnCount': 2})\n\nif __name__ == '__main__':\n app.run_server(debug=True)" }, { "code": null, "e": 16055, "s": 16009, "text": "Output from the above program is as follows −" }, { "code": null, "e": 16342, "s": 16055, "text": "Dash components are declarative. Every configurable aspect of these components is set during installation as a keyword argument. You can call help in your python console on any of the components to learn more about a component and its available arguments. Some of them are given below −" }, { "code": null, "e": 17155, "s": 16342, "text": ">>> help(dcc.Dropdown)\nHelp on class Dropdown in module builtins:\nclass Dropdown(dash.development.base_component.Component)\n| A Dropdown component.\n| Dropdown is an interactive dropdown element for selecting one or more\n\n| items.\n| The values and labels of the dropdown items are specified in the `options`\n| property and the selected item(s) are specified with the `value` property.\n|\n| Use a dropdown when you have many options (more than 5) or when you are\n| constrained for space. Otherwise, you can use RadioItems or a Checklist,\n| which have the benefit of showing the users all of the items at once.\n|\n| Keyword arguments:\n| - id (string; optional)\n| - options (list; optional): An array of options\n| - value (string | list; optional): The value of the input. If `multi` is false (the default)\n-- More --\n" } ]
Print all combinations generated by characters of a numeric string which does not exceed N
11 May, 2021 Given a numeric string S of length M and an integer N, the task is to find all distinct combinations of S (repetitions allowed) that are at most N. Examples: Input: S = “124”, N = 100Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44Explanation: Combinations “111”, “112”, “122”, “124”, “412” are greater than 100. Therefore, these combinations are excluded from the output. Input: S = “345”, N = 400Output: 3, 33, 333, 334, 335, 34, 343, 344, 345, 35, 353, 354, 355, 4, 43, 44, 45, 5, 53, 54, 55 Approach: The idea is to generate all the numbers possible using Backtracking and then print those numbers which does not exceed N. Follow the steps below to solve the problem: Initialize a Set of strings, say combinations[], to store all distinct combinations of S that numerically does not exceed N. Initialize a string ans to store the current combination of numbers possible from S. Declare a function generateCombinations() to generate all required combinations whose values are less than the given value N and the function is defined as:Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations().Backtrack to its previous state by removing the ith character from ans. Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations(). Push the current character S[i] to ans and convert the current string ans to the number and store it in x. If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations(). Backtrack to its previous state by removing the ith character from ans. After completing the above steps, print the set of all strings stored in combinations[]. 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; // Store the current sequence of sstring combination; // Store the all the required sequencesset<string> combinations; // Function to print all sequences of S// satisfying the required conditionvoid printSequences( set<string> combinations){ // Print all strings in the set for (string s : combinations) { cout << s << ' '; }} // Function to generate all sequences// of string S that are at most Nvoid generateCombinations(string& s, int n){ // Iterate over string s for (int i = 0; i < s.size(); i++) { // Push ith character to combination combination.push_back(s[i]); // Convert the string to number long x = stol(combination); // Check if the condition is true if (x <= n) { // Push the current string to // the final set of sequences combinations.insert(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination.pop_back(); }} // Driver Codeint main(){ string S = "124"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Store the current sequence of sstatic String combination = ""; // Store the all the required sequencesstatic HashSet<String> combinations = new LinkedHashSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences( HashSet<String> combinations){ // Print all Strings in the set for(String s : combinations) { System.out.print(s + " "); }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){ // Iterate over String s for(int i = 0; i < s.length(); i++) { // Push ith character to combination combination += (s.charAt(i)); // Convert the String to number long x = Integer.valueOf(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the final set of sequences combinations.add(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.substring( 0, combination.length() - 1); }} // Driver Codepublic static void main(String[] args){ String S = "124"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations);}} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Store the current sequence of scombination = ""; # Store the all the required sequencescombinations = []; # Function to print all sequences of S# satisfying the required conditiondef printSequences(combinations) : # Print all strings in the set for s in (combinations) : print(s, end = ' '); # Function to generate all sequences# of string S that are at most Ndef generateCombinations(s, n) : global combination; # Iterate over string s for i in range(len(s)) : # Push ith character to combination combination += s[i]; # Convert the string to number x = int(combination); # Check if the condition is true if (x <= n) : # Push the current string to # the final set of sequences combinations.append(combination); # Recursively call function generateCombinations(s, n); # Backtrack to its previous state combination = combination[:-1]; # Driver Codeif __name__ == "__main__" : S = "124"; N = 100; # Function Call generateCombinations(S, N); # Print required sequences printSequences(combinations); # This code is contributed by AnkThon // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Store the current sequence of sstatic String combination = ""; // Store the all the required sequencesstatic SortedSet<String> combinations = new SortedSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences( SortedSet<String> combinations){ // Print all Strings in the set foreach(String s in combinations) { Console.Write(s + " "); }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){ // Iterate over String s for(int i = 0; i < s.Length; i++) { // Push ith character to combination combination += (s[i]); // Convert the String to number long x = Int32.Parse(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the readonly set of sequences combinations.Add(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.Substring( 0, combination.Length - 1); }} // Driver Codepublic static void Main(String[] args){ String S = "124"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations);}} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // Store the current sequence of s var combination = ""; // Store the all the required sequences var combinations = []; // Function to print all sequences of S // satisfying the required condition function printSequences(combinations) { // Print all Strings in the set for (var s of combinations) { document.write(s + " "); } } // Function to generate all sequences // of String S that are at most N function generateCombinations(s, n) { // Iterate over String s for (var i = 0; i < s.length; i++) { // Push ith character to combination combination += s[i]; // Convert the String to number var x = parseInt(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the readonly set of sequences combinations.push(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.substring(0, combination.length - 1); } } // Driver Code var S = "124"; var N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations); </script> 1 11 12 14 2 21 22 24 4 41 42 44 Time Complexity: O(NN)Auxiliary Space: O(NN) amit143katiyar ankthon khushboogoyal499 29AjayKumar rdtank Permutation and Combination Backtracking Mathematical Recursion Strings Strings Mathematical Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. m Coloring Problem | Backtracking-5 Hamiltonian Cycle | Backtracking-6 Backtracking to find all subsets Printing all solutions in N-Queen Problem Generate all the binary strings of N bits Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2021" }, { "code": null, "e": 200, "s": 52, "text": "Given a numeric string S of length M and an integer N, the task is to find all distinct combinations of S (repetitions allowed) that are at most N." }, { "code": null, "e": 210, "s": 200, "text": "Examples:" }, { "code": null, "e": 428, "s": 210, "text": "Input: S = “124”, N = 100Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44Explanation: Combinations “111”, “112”, “122”, “124”, “412” are greater than 100. Therefore, these combinations are excluded from the output." }, { "code": null, "e": 550, "s": 428, "text": "Input: S = “345”, N = 400Output: 3, 33, 333, 334, 335, 34, 343, 344, 345, 35, 353, 354, 355, 4, 43, 44, 45, 5, 53, 54, 55" }, { "code": null, "e": 727, "s": 550, "text": "Approach: The idea is to generate all the numbers possible using Backtracking and then print those numbers which does not exceed N. Follow the steps below to solve the problem:" }, { "code": null, "e": 852, "s": 727, "text": "Initialize a Set of strings, say combinations[], to store all distinct combinations of S that numerically does not exceed N." }, { "code": null, "e": 937, "s": 852, "text": "Initialize a string ans to store the current combination of numbers possible from S." }, { "code": null, "e": 1491, "s": 937, "text": "Declare a function generateCombinations() to generate all required combinations whose values are less than the given value N and the function is defined as:Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations().Backtrack to its previous state by removing the ith character from ans." }, { "code": null, "e": 1818, "s": 1491, "text": "Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations()." }, { "code": null, "e": 1925, "s": 1818, "text": "Push the current character S[i] to ans and convert the current string ans to the number and store it in x." }, { "code": null, "e": 2060, "s": 1925, "text": "If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations()." }, { "code": null, "e": 2132, "s": 2060, "text": "Backtrack to its previous state by removing the ith character from ans." }, { "code": null, "e": 2221, "s": 2132, "text": "After completing the above steps, print the set of all strings stored in combinations[]." }, { "code": null, "e": 2272, "s": 2221, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2276, "s": 2272, "text": "C++" }, { "code": null, "e": 2281, "s": 2276, "text": "Java" }, { "code": null, "e": 2289, "s": 2281, "text": "Python3" }, { "code": null, "e": 2292, "s": 2289, "text": "C#" }, { "code": null, "e": 2303, "s": 2292, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Store the current sequence of sstring combination; // Store the all the required sequencesset<string> combinations; // Function to print all sequences of S// satisfying the required conditionvoid printSequences( set<string> combinations){ // Print all strings in the set for (string s : combinations) { cout << s << ' '; }} // Function to generate all sequences// of string S that are at most Nvoid generateCombinations(string& s, int n){ // Iterate over string s for (int i = 0; i < s.size(); i++) { // Push ith character to combination combination.push_back(s[i]); // Convert the string to number long x = stol(combination); // Check if the condition is true if (x <= n) { // Push the current string to // the final set of sequences combinations.insert(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination.pop_back(); }} // Driver Codeint main(){ string S = \"124\"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations); return 0;}", "e": 3626, "s": 2303, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Store the current sequence of sstatic String combination = \"\"; // Store the all the required sequencesstatic HashSet<String> combinations = new LinkedHashSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences( HashSet<String> combinations){ // Print all Strings in the set for(String s : combinations) { System.out.print(s + \" \"); }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){ // Iterate over String s for(int i = 0; i < s.length(); i++) { // Push ith character to combination combination += (s.charAt(i)); // Convert the String to number long x = Integer.valueOf(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the final set of sequences combinations.add(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.substring( 0, combination.length() - 1); }} // Driver Codepublic static void main(String[] args){ String S = \"124\"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations);}} // This code is contributed by Amit Katiyar", "e": 5183, "s": 3626, "text": null }, { "code": "# Python3 program for the above approach # Store the current sequence of scombination = \"\"; # Store the all the required sequencescombinations = []; # Function to print all sequences of S# satisfying the required conditiondef printSequences(combinations) : # Print all strings in the set for s in (combinations) : print(s, end = ' '); # Function to generate all sequences# of string S that are at most Ndef generateCombinations(s, n) : global combination; # Iterate over string s for i in range(len(s)) : # Push ith character to combination combination += s[i]; # Convert the string to number x = int(combination); # Check if the condition is true if (x <= n) : # Push the current string to # the final set of sequences combinations.append(combination); # Recursively call function generateCombinations(s, n); # Backtrack to its previous state combination = combination[:-1]; # Driver Codeif __name__ == \"__main__\" : S = \"124\"; N = 100; # Function Call generateCombinations(S, N); # Print required sequences printSequences(combinations); # This code is contributed by AnkThon", "e": 6433, "s": 5183, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Store the current sequence of sstatic String combination = \"\"; // Store the all the required sequencesstatic SortedSet<String> combinations = new SortedSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences( SortedSet<String> combinations){ // Print all Strings in the set foreach(String s in combinations) { Console.Write(s + \" \"); }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){ // Iterate over String s for(int i = 0; i < s.Length; i++) { // Push ith character to combination combination += (s[i]); // Convert the String to number long x = Int32.Parse(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the readonly set of sequences combinations.Add(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.Substring( 0, combination.Length - 1); }} // Driver Codepublic static void Main(String[] args){ String S = \"124\"; int N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations);}} // This code is contributed by 29AjayKumar", "e": 8003, "s": 6433, "text": null }, { "code": "<script> // JavaScript program for the above approach // Store the current sequence of s var combination = \"\"; // Store the all the required sequences var combinations = []; // Function to print all sequences of S // satisfying the required condition function printSequences(combinations) { // Print all Strings in the set for (var s of combinations) { document.write(s + \" \"); } } // Function to generate all sequences // of String S that are at most N function generateCombinations(s, n) { // Iterate over String s for (var i = 0; i < s.length; i++) { // Push ith character to combination combination += s[i]; // Convert the String to number var x = parseInt(combination); // Check if the condition is true if (x <= n) { // Push the current String to // the readonly set of sequences combinations.push(combination); // Recursively call function generateCombinations(s, n); } // Backtrack to its previous state combination = combination.substring(0, combination.length - 1); } } // Driver Code var S = \"124\"; var N = 100; // Function Call generateCombinations(S, N); // Print required sequences printSequences(combinations); </script>", "e": 9439, "s": 8003, "text": null }, { "code": null, "e": 9472, "s": 9439, "text": "1 11 12 14 2 21 22 24 4 41 42 44" }, { "code": null, "e": 9519, "s": 9474, "text": "Time Complexity: O(NN)Auxiliary Space: O(NN)" }, { "code": null, "e": 9534, "s": 9519, "text": "amit143katiyar" }, { "code": null, "e": 9542, "s": 9534, "text": "ankthon" }, { "code": null, "e": 9559, "s": 9542, "text": "khushboogoyal499" }, { "code": null, "e": 9571, "s": 9559, "text": "29AjayKumar" }, { "code": null, "e": 9578, "s": 9571, "text": "rdtank" }, { "code": null, "e": 9606, "s": 9578, "text": "Permutation and Combination" }, { "code": null, "e": 9619, "s": 9606, "text": "Backtracking" }, { "code": null, "e": 9632, "s": 9619, "text": "Mathematical" }, { "code": null, "e": 9642, "s": 9632, "text": "Recursion" }, { "code": null, "e": 9650, "s": 9642, "text": "Strings" }, { "code": null, "e": 9658, "s": 9650, "text": "Strings" }, { "code": null, "e": 9671, "s": 9658, "text": "Mathematical" }, { "code": null, "e": 9681, "s": 9671, "text": "Recursion" }, { "code": null, "e": 9694, "s": 9681, "text": "Backtracking" }, { "code": null, "e": 9792, "s": 9694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9828, "s": 9792, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 9863, "s": 9828, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 9896, "s": 9863, "text": "Backtracking to find all subsets" }, { "code": null, "e": 9938, "s": 9896, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 9980, "s": 9938, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 10010, "s": 9980, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 10053, "s": 10010, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 10068, "s": 10053, "text": "C++ Data Types" }, { "code": null, "e": 10092, "s": 10068, "text": "Merge two sorted arrays" } ]
WebSockets - Server Working
A Web Socket server is a simple program, which has the ability to handle Web Socket events and actions. It usually exposes similar methods to the Web Socket client API and most programming languages provide an implementation. The following diagram illustrates the communication process between a Web Socket server and a Web Socket client, emphasizing the triggered events and actions. The following diagram shows a Web Socket server and client event triggering − The Web Socket server works in a similar way to the Web Socket clients. It responds to events and performs actions when necessary. Regardless of the programming language used, every Web Socket server performs some specific actions. It is initialized to a Web Socket address. It handles OnOpen, OnClose, and OnMessage events, and sends messages to the clients too. Every Web Socket server needs a valid host and port. An example of creating a Web Socket instance in server is as follows − var server = new WebSocketServer("ws://localhost:8181"); Any valid URL can be used with the specification of a port, which was not used earlier. It is very useful to keep a record of the connected clients, as it provides details with different data or send different messages to each one. Fleck represents the incoming connections (clients) with the IwebSocketConnection interface. Whenever someone connects or disconnects from our service, empty list can be created or updated. var clients = new List<IWebSocketConnection>(); After that, we can call the Start method and wait for the clients to connect. After starting, the server is able to accept incoming connections. In Fleck, the Start method needs a parameter, which indicates the socket that raised the events − server.Start(socket) => { }); The OnOpen event determines that a new client has requested access and performs an initial handshake. The client should be added to the list and probably the information should be stored related to it, such as the IP address. Fleck provides us with such information, as well as a unique identifier for the connection. server.Start(socket) ⇒ { socket.OnOpen = () ⇒ { // Add the incoming connection to our list. clients.Add(socket); } // Handle the other events here... }); The OnClose event is raised whenever a client is disconnected. The Client is removed from the list and informs the rest of clients about the disconnection. socket.OnClose = () ⇒ { // Remove the disconnected client from the list. clients.Remove(socket); }; The OnMessage event is raised when a client sends data to the server. Inside this event handler, the incoming message can be transmitted to the clients, or probably select only some of them. The process is simple. Note that this handler takes a string named message as a parameter − socket.OnMessage = () ⇒ { // Display the message on the console. Console.WriteLine(message); }; The Send() method simply transmits the desired message to the specified client. Using Send(), text or binary data can be stored across the clients. The working of OnMessage event is as follows − socket.OnMessage = () ⇒ { foreach (var client in clients) { // Send the message to everyone! // Also, send the client connection's unique identifier in order // to recognize who is who. client.Send(client.ConnectionInfo.Id + " says: " + message);
[ { "code": null, "e": 2638, "s": 2253, "text": "A Web Socket server is a simple program, which has the ability to handle Web Socket events and actions. It usually exposes similar methods to the Web Socket client API and most programming languages provide an implementation. The following diagram illustrates the communication process between a Web Socket server and a Web Socket client, emphasizing the triggered events and actions." }, { "code": null, "e": 2716, "s": 2638, "text": "The following diagram shows a Web Socket server and client event triggering −" }, { "code": null, "e": 2948, "s": 2716, "text": "The Web Socket server works in a similar way to the Web Socket clients. It responds to events and performs actions when necessary. Regardless of the programming language used, every Web Socket server performs some specific actions." }, { "code": null, "e": 3080, "s": 2948, "text": "It is initialized to a Web Socket address. It handles OnOpen, OnClose, and OnMessage events, and sends messages to the clients too." }, { "code": null, "e": 3204, "s": 3080, "text": "Every Web Socket server needs a valid host and port. An example of creating a Web Socket instance in server is as follows −" }, { "code": null, "e": 3262, "s": 3204, "text": "var server = new WebSocketServer(\"ws://localhost:8181\");\n" }, { "code": null, "e": 3494, "s": 3262, "text": "Any valid URL can be used with the specification of a port, which was not used earlier. It is very useful to keep a record of the connected clients, as it provides details with different data or send different messages to each one." }, { "code": null, "e": 3684, "s": 3494, "text": "Fleck represents the incoming connections (clients) with the IwebSocketConnection interface. Whenever someone connects or disconnects from our service, empty list can be created or updated." }, { "code": null, "e": 3733, "s": 3684, "text": "var clients = new List<IWebSocketConnection>();\n" }, { "code": null, "e": 3976, "s": 3733, "text": "After that, we can call the Start method and wait for the clients to connect. After starting, the server is able to accept incoming connections. In Fleck, the Start method needs a parameter, which indicates the socket that raised the events −" }, { "code": null, "e": 4007, "s": 3976, "text": "server.Start(socket) =>\n{\n});\n" }, { "code": null, "e": 4325, "s": 4007, "text": "The OnOpen event determines that a new client has requested access and performs an initial handshake. The client should be added to the list and probably the information should be stored related to it, such as the IP address. Fleck provides us with such information, as well as a unique identifier for the connection." }, { "code": null, "e": 4503, "s": 4325, "text": "server.Start(socket) ⇒ {\n\n socket.OnOpen = () ⇒ {\n // Add the incoming connection to our list.\n clients.Add(socket);\n }\n\t\n // Handle the other events here...\n});" }, { "code": null, "e": 4659, "s": 4503, "text": "The OnClose event is raised whenever a client is disconnected. The Client is removed from the list and informs the rest of clients about the disconnection." }, { "code": null, "e": 4765, "s": 4659, "text": "socket.OnClose = () ⇒ {\n // Remove the disconnected client from the list.\n clients.Remove(socket);\n};" }, { "code": null, "e": 4956, "s": 4765, "text": "The OnMessage event is raised when a client sends data to the server. Inside this event handler, the incoming message can be transmitted to the clients, or probably select only some of them." }, { "code": null, "e": 5048, "s": 4956, "text": "The process is simple. Note that this handler takes a string named message as a parameter −" }, { "code": null, "e": 5150, "s": 5048, "text": "socket.OnMessage = () ⇒ {\n // Display the message on the console.\n Console.WriteLine(message);\n};" }, { "code": null, "e": 5298, "s": 5150, "text": "The Send() method simply transmits the desired message to the specified client. Using Send(), text or binary data can be stored across the clients." }, { "code": null, "e": 5345, "s": 5298, "text": "The working of OnMessage event is as follows −" } ]
Tensorflow.js tf.LayersModel class .summary() Method
21 Jul, 2021 The tf.LayersModel is a class used for training, inference, and evaluation of layers model in tensorflow.js. It contains methods for training, evaluation, prediction, and for saving of layers model purposes. So in this post, we are going to know about the model.summary() function. The model.summary() function in tensorflow.js prints the summary for the model it includes the name of the model, numbers of weight parameters, numbers of trainable parameters. Syntax: model_name.summary (line length, position, print function) Parameters: All the parameters are optional. line length: It is a custom line length in a number of characters. position: It is an array that showing widths for each column, values can be fractional or absolute. print function: function which is printing the summary for model, default function is console.log(). Returns: Void. Example 1: In this example, we are going to create the sequential model with single dense layers and printing the summary for the model using model.summary() function. Javascript // Importing the tensorflow.Js libraryimport * as tf from "@tensorflow/tfjs" // Creating modelvar myModel = tf.sequential({ layers:[tf.layers.dense({ units: 10, inputShape: [15] })]}); // Print the summarymyModel.summary(); Output: _________________________________________________________________ Layer (type) Output shape Param # ================================================================= dense_Dense8 (Dense) [null,10] 160 ================================================================= Total params: 160 Trainable params: 160 Non-trainable params: 0 _________________________________________________________________ Example 2: In this example, we are going to create the model with 2 dense layers having activation function relu and softmax using tf.model method and making predictions also printing the summary for the model. Javascript // Importing the tensorflow.Js libraryimport * as tf from "@tensorflow/tfjs" // Define inputvar inp=tf.input({shape:[8]}); // Dense layer 1var denseLayerOne=tf.layers.dense({units:7,activation:'relu'}); // Dense layer 1var denseLayerTwo=tf.layers.dense({units:5, activation:'softmax'}); // Generate the outputvar out=denseLayerTwo.apply(denseLayerOne.apply(inp)); // Model creationvar myModel=tf.model({inputs:inp,outputs:out}); // Make predictionconsole.log("\nPrediction :")myModel.predict(tf.ones([3,8])).print();console.log("\nSummary :")myModel.summary(); Output: Prediction : Tensor [[0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899], [0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899], [0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899]] Summary : _________________________________________________________________ Layer (type) Output shape Param # ================================================================= input7 (InputLayer) [null,8] 0 _________________________________________________________________ dense_Dense19 (Dense) [null,7] 63 _________________________________________________________________ dense_Dense20 (Dense) [null,5] 40 ================================================================= Total params: 103 Trainable params: 103 Non-trainable params: 0 _________________________________________________________________ Reference: https://js.tensorflow.org/api/latest/#tf.LayersModel.summary sumitgumber28 Picked Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 310, "s": 28, "text": "The tf.LayersModel is a class used for training, inference, and evaluation of layers model in tensorflow.js. It contains methods for training, evaluation, prediction, and for saving of layers model purposes. So in this post, we are going to know about the model.summary() function." }, { "code": null, "e": 488, "s": 310, "text": "The model.summary() function in tensorflow.js prints the summary for the model it includes the name of the model, numbers of weight parameters, numbers of trainable parameters." }, { "code": null, "e": 496, "s": 488, "text": "Syntax:" }, { "code": null, "e": 555, "s": 496, "text": "model_name.summary (line length, position, print function)" }, { "code": null, "e": 600, "s": 555, "text": "Parameters: All the parameters are optional." }, { "code": null, "e": 667, "s": 600, "text": "line length: It is a custom line length in a number of characters." }, { "code": null, "e": 767, "s": 667, "text": "position: It is an array that showing widths for each column, values can be fractional or absolute." }, { "code": null, "e": 868, "s": 767, "text": "print function: function which is printing the summary for model, default function is console.log()." }, { "code": null, "e": 883, "s": 868, "text": "Returns: Void." }, { "code": null, "e": 1052, "s": 883, "text": "Example 1: In this example, we are going to create the sequential model with single dense layers and printing the summary for the model using model.summary() function." }, { "code": null, "e": 1063, "s": 1052, "text": "Javascript" }, { "code": "// Importing the tensorflow.Js libraryimport * as tf from \"@tensorflow/tfjs\" // Creating modelvar myModel = tf.sequential({ layers:[tf.layers.dense({ units: 10, inputShape: [15] })]}); // Print the summarymyModel.summary();", "e": 1307, "s": 1063, "text": null }, { "code": null, "e": 1315, "s": 1307, "text": "Output:" }, { "code": null, "e": 1777, "s": 1315, "text": "_________________________________________________________________\nLayer (type) Output shape Param # \n=================================================================\ndense_Dense8 (Dense) [null,10] 160 \n=================================================================\nTotal params: 160\nTrainable params: 160\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 1988, "s": 1777, "text": "Example 2: In this example, we are going to create the model with 2 dense layers having activation function relu and softmax using tf.model method and making predictions also printing the summary for the model." }, { "code": null, "e": 1999, "s": 1988, "text": "Javascript" }, { "code": "// Importing the tensorflow.Js libraryimport * as tf from \"@tensorflow/tfjs\" // Define inputvar inp=tf.input({shape:[8]}); // Dense layer 1var denseLayerOne=tf.layers.dense({units:7,activation:'relu'}); // Dense layer 1var denseLayerTwo=tf.layers.dense({units:5, activation:'softmax'}); // Generate the outputvar out=denseLayerTwo.apply(denseLayerOne.apply(inp)); // Model creationvar myModel=tf.model({inputs:inp,outputs:out}); // Make predictionconsole.log(\"\\nPrediction :\")myModel.predict(tf.ones([3,8])).print();console.log(\"\\nSummary :\")myModel.summary();", "e": 2560, "s": 1999, "text": null }, { "code": null, "e": 2568, "s": 2560, "text": "Output:" }, { "code": null, "e": 3508, "s": 2568, "text": "Prediction :\nTensor\n [[0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899],\n [0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899],\n [0.2074656, 0.1515629, 0.2641615, 0.2237201, 0.1530899]]\n\nSummary :\n_________________________________________________________________\nLayer (type) Output shape Param # \n=================================================================\ninput7 (InputLayer) [null,8] 0 \n_________________________________________________________________\ndense_Dense19 (Dense) [null,7] 63 \n_________________________________________________________________\ndense_Dense20 (Dense) [null,5] 40 \n=================================================================\nTotal params: 103\nTrainable params: 103\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 3580, "s": 3508, "text": "Reference: https://js.tensorflow.org/api/latest/#tf.LayersModel.summary" }, { "code": null, "e": 3594, "s": 3580, "text": "sumitgumber28" }, { "code": null, "e": 3601, "s": 3594, "text": "Picked" }, { "code": null, "e": 3615, "s": 3601, "text": "Tensorflow.js" }, { "code": null, "e": 3626, "s": 3615, "text": "JavaScript" }, { "code": null, "e": 3643, "s": 3626, "text": "Web Technologies" } ]
How to Subtract Two Columns in Pandas DataFrame?
19 Dec, 2021 In this article, we will discuss how to subtract two columns in pandas dataframe in Python. Dataframe in use: This is the __getitem__ method syntax ([]), which lets you directly access the columns of the data frame using the column name. Example: Subtract two columns in Pandas dataframe Python3 import numpy as npimport pandas as pd data = np.arange(0, 20).reshape(4, 5) df1 = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) # using our previous example# now let's subtract the values of two columnsdf1['Column 1'] - df1['Column 2'] Output: We can create a function specifically for subtracting the columns, by taking column data as arguments and then using the apply method to apply it to all the data points throughout the column. Example: Subtract two columns in Pandas dataframe Python3 import numpy as npimport pandas as pd def diff(a, b): return b - a data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df['Difference_2_1'] = df.apply( lambda x: diff(x['Column 2'], x['Column 2']), axis=1) Output : Since the operation we want to perform is simple we can you can directly use the apply() method without explicitly defining a function. Provide the axis argument as 1 to access the columns. Syntax: s.apply(func, convert_dtype=True, args=()) Parameters: func: .apply takes a function and applies it to all values of pandas series. convert_dtype: Convert dtype as per the function’s operation. args=(): Additional arguments to pass to function instead of series. Return Type: Pandas Series after applied function/operation. Example: Subtract two columns in Pandas Dataframe Python3 import pandas as pdimport numpy as np data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df['diff_3_4'] = df.apply(lambda x: x['Column 3'] - x['Column 4'], axis=1)df Output: assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. Example: Subtract two columns in Pandas dataframe Python3 import numpy as npimport pandas as pd data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df = df.assign(diff_1_5=df['Column 1'] - df['Column 5']) df Output : pandas-dataframe-program Picked 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": "\n19 Dec, 2021" }, { "code": null, "e": 120, "s": 28, "text": "In this article, we will discuss how to subtract two columns in pandas dataframe in Python." }, { "code": null, "e": 138, "s": 120, "text": "Dataframe in use:" }, { "code": null, "e": 266, "s": 138, "text": "This is the __getitem__ method syntax ([]), which lets you directly access the columns of the data frame using the column name." }, { "code": null, "e": 316, "s": 266, "text": "Example: Subtract two columns in Pandas dataframe" }, { "code": null, "e": 324, "s": 316, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd data = np.arange(0, 20).reshape(4, 5) df1 = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) # using our previous example# now let's subtract the values of two columnsdf1['Column 1'] - df1['Column 2']", "e": 715, "s": 324, "text": null }, { "code": null, "e": 724, "s": 715, "text": "Output: " }, { "code": null, "e": 917, "s": 724, "text": "We can create a function specifically for subtracting the columns, by taking column data as arguments and then using the apply method to apply it to all the data points throughout the column. " }, { "code": null, "e": 967, "s": 917, "text": "Example: Subtract two columns in Pandas dataframe" }, { "code": null, "e": 975, "s": 967, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd def diff(a, b): return b - a data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df['Difference_2_1'] = df.apply( lambda x: diff(x['Column 2'], x['Column 2']), axis=1)", "e": 1379, "s": 975, "text": null }, { "code": null, "e": 1389, "s": 1379, "text": "Output : " }, { "code": null, "e": 1580, "s": 1389, "text": "Since the operation we want to perform is simple we can you can directly use the apply() method without explicitly defining a function. Provide the axis argument as 1 to access the columns. " }, { "code": null, "e": 1588, "s": 1580, "text": "Syntax:" }, { "code": null, "e": 1631, "s": 1588, "text": "s.apply(func, convert_dtype=True, args=())" }, { "code": null, "e": 1643, "s": 1631, "text": "Parameters:" }, { "code": null, "e": 1720, "s": 1643, "text": "func: .apply takes a function and applies it to all values of pandas series." }, { "code": null, "e": 1782, "s": 1720, "text": "convert_dtype: Convert dtype as per the function’s operation." }, { "code": null, "e": 1851, "s": 1782, "text": "args=(): Additional arguments to pass to function instead of series." }, { "code": null, "e": 1912, "s": 1851, "text": "Return Type: Pandas Series after applied function/operation." }, { "code": null, "e": 1963, "s": 1912, "text": "Example: Subtract two columns in Pandas Dataframe " }, { "code": null, "e": 1971, "s": 1963, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df['diff_3_4'] = df.apply(lambda x: x['Column 3'] - x['Column 4'], axis=1)df", "e": 2329, "s": 1971, "text": null }, { "code": null, "e": 2337, "s": 2329, "text": "Output:" }, { "code": null, "e": 2470, "s": 2337, "text": "assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. " }, { "code": null, "e": 2520, "s": 2470, "text": "Example: Subtract two columns in Pandas dataframe" }, { "code": null, "e": 2528, "s": 2520, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd data = np.arange(0, 20).reshape(4, 5) df = pd.DataFrame(data, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'], columns=['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5']) df = df.assign(diff_1_5=df['Column 1'] - df['Column 5']) df", "e": 2870, "s": 2528, "text": null }, { "code": null, "e": 2880, "s": 2870, "text": "Output : " }, { "code": null, "e": 2905, "s": 2880, "text": "pandas-dataframe-program" }, { "code": null, "e": 2912, "s": 2905, "text": "Picked" }, { "code": null, "e": 2936, "s": 2912, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2950, "s": 2936, "text": "Python-pandas" }, { "code": null, "e": 2957, "s": 2950, "text": "Python" } ]
wxPython - TextCtrl Class
In a GUI interface, the input is most commonly collected in a text box where the user can type using the keyboard. In wxPython, an object of wx.TextCtrl class serves this purpose. It is a control in which the text can be displayed and edited. The TextCtrl widget can be a single line, multi-line or a password field. TextCtrl class constructor takes the following form − wx.TextCtrl(parent, id, value, pos, size, style) The style parameter takes one or more constants from the following list − wx.TE_MULTILINE The text control allows multiple lines. If this style is not specified, the line break characters should not be used in the controls value. wx.TE_PASSWORD The text will be echoed as asterisks wx.TE_READONLY The text will not be user-editable wxTE_LEFT The text in the control will be left-justified (default) wxTE_CENTRE The text in the control will be centered wxTE_RIGHT The text in the control will be right-justified The important methods of wx.TextCtrl class are − AppendText() Adds text to the end of text control Clear() Clears the contents GetValue() Returns the contents of the text box Replace() Replaces the entire or portion of text in the box SetEditable() Makes the text box editable or read-only SetMaxLength() Sets maximum number of characters the control can hold SetValue() Sets the contents in the text box programmatically IsMultiLine() Returns true if set to TE_MULTILINE The following event binders are responsible for event handling related to entering text in TextCtrl box − EVT_TEXT Responds to changes in the contents of text box, either by manually keying in, or programmatically EVT_TEXT_ENTER Invokes associated handler when Enter key is pressed in the text box EVT_TEXT_MAXLEN Triggers associated handler as soon as the length of text entered reaches the value of SetMaxLength() function In the following example, four objects of wx.TextCtrl class with different attributes are placed on the panel. self.t1 = wx.TextCtrl(panel) self.t2 = wx.TextCtrl(panel,style = wx.TE_PASSWORD) self.t3 = wx.TextCtrl(panel,size = (200,100),style = wx.TE_MULTILINE) self.t4 = wx.TextCtrl ( panel, value = "ReadOnly Text", style = wx.TE_READONLY | wx.TE_CENTER ) While the first is a normal text box, the second is a password field. The third one is a multiline text box and the last text box is non-editable. EVT_TEXT binder on first box triggers OnKeyTyped() method for each key stroke in it. The second box is having its MaxLength set to 5. EVT_TEXT_MAXLEN binder sends OnMaxLen() function running as soon as the user tries to type more than 5 characters. The multiline text box responds to Enter key pressed because of EVT_TEXT_ENTER binder. The complete code is as follows − import wx class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title,size = (350,250)) panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) l1 = wx.StaticText(panel, -1, "Text Field") hbox1.Add(l1, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) self.t1 = wx.TextCtrl(panel) hbox1.Add(self.t1,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) self.t1.Bind(wx.EVT_TEXT,self.OnKeyTyped) vbox.Add(hbox1) hbox2 = wx.BoxSizer(wx.HORIZONTAL) l2 = wx.StaticText(panel, -1, "password field") hbox2.Add(l2, 1, wx.ALIGN_LEFT|wx.ALL,5) self.t2 = wx.TextCtrl(panel,style = wx.TE_PASSWORD) self.t2.SetMaxLength(5) hbox2.Add(self.t2,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) vbox.Add(hbox2) self.t2.Bind(wx.EVT_TEXT_MAXLEN,self.OnMaxLen) hbox3 = wx.BoxSizer(wx.HORIZONTAL) l3 = wx.StaticText(panel, -1, "Multiline Text") hbox3.Add(l3,1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) self.t3 = wx.TextCtrl(panel,size = (200,100),style = wx.TE_MULTILINE) hbox3.Add(self.t3,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) vbox.Add(hbox3) self.t3.Bind(wx.EVT_TEXT_ENTER,self.OnEnterPressed) hbox4 = wx.BoxSizer(wx.HORIZONTAL) l4 = wx.StaticText(panel, -1, "Read only text") hbox4.Add(l4, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) self.t4 = wx.TextCtrl(panel, value = "ReadOnly Text",style = wx.TE_READONLY|wx.TE_CENTER) hbox4.Add(self.t4,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) vbox.Add(hbox4) panel.SetSizer(vbox) self.Centre() self.Show() self.Fit() def OnKeyTyped(self, event): print event.GetString() def OnEnterPressed(self,event): print "Enter pressed" def OnMaxLen(self,event): print "Maximum length reached" app = wx.App() Mywin(None, 'TextCtrl demo') app.MainLoop() The above code produces the following output −
[ { "code": null, "e": 2387, "s": 2016, "text": "In a GUI interface, the input is most commonly collected in a text box where the user can type using the keyboard. In wxPython, an object of wx.TextCtrl class serves this purpose. It is a control in which the text can be displayed and edited. The TextCtrl widget can be a single line, multi-line or a password field. TextCtrl class constructor takes the following form −" }, { "code": null, "e": 2437, "s": 2387, "text": "wx.TextCtrl(parent, id, value, pos, size, style)\n" }, { "code": null, "e": 2511, "s": 2437, "text": "The style parameter takes one or more constants from the following list −" }, { "code": null, "e": 2527, "s": 2511, "text": "wx.TE_MULTILINE" }, { "code": null, "e": 2667, "s": 2527, "text": "The text control allows multiple lines. If this style is not specified, the line break characters should not be used in the controls value." }, { "code": null, "e": 2682, "s": 2667, "text": "wx.TE_PASSWORD" }, { "code": null, "e": 2719, "s": 2682, "text": "The text will be echoed as asterisks" }, { "code": null, "e": 2734, "s": 2719, "text": "wx.TE_READONLY" }, { "code": null, "e": 2769, "s": 2734, "text": "The text will not be user-editable" }, { "code": null, "e": 2779, "s": 2769, "text": "wxTE_LEFT" }, { "code": null, "e": 2836, "s": 2779, "text": "The text in the control will be left-justified (default)" }, { "code": null, "e": 2848, "s": 2836, "text": "wxTE_CENTRE" }, { "code": null, "e": 2889, "s": 2848, "text": "The text in the control will be centered" }, { "code": null, "e": 2900, "s": 2889, "text": "wxTE_RIGHT" }, { "code": null, "e": 2948, "s": 2900, "text": "The text in the control will be right-justified" }, { "code": null, "e": 2997, "s": 2948, "text": "The important methods of wx.TextCtrl class are −" }, { "code": null, "e": 3010, "s": 2997, "text": "AppendText()" }, { "code": null, "e": 3047, "s": 3010, "text": "Adds text to the end of text control" }, { "code": null, "e": 3055, "s": 3047, "text": "Clear()" }, { "code": null, "e": 3075, "s": 3055, "text": "Clears the contents" }, { "code": null, "e": 3086, "s": 3075, "text": "GetValue()" }, { "code": null, "e": 3123, "s": 3086, "text": "Returns the contents of the text box" }, { "code": null, "e": 3133, "s": 3123, "text": "Replace()" }, { "code": null, "e": 3183, "s": 3133, "text": "Replaces the entire or portion of text in the box" }, { "code": null, "e": 3197, "s": 3183, "text": "SetEditable()" }, { "code": null, "e": 3238, "s": 3197, "text": "Makes the text box editable or read-only" }, { "code": null, "e": 3253, "s": 3238, "text": "SetMaxLength()" }, { "code": null, "e": 3308, "s": 3253, "text": "Sets maximum number of characters the control can hold" }, { "code": null, "e": 3319, "s": 3308, "text": "SetValue()" }, { "code": null, "e": 3370, "s": 3319, "text": "Sets the contents in the text box programmatically" }, { "code": null, "e": 3384, "s": 3370, "text": "IsMultiLine()" }, { "code": null, "e": 3420, "s": 3384, "text": "Returns true if set to TE_MULTILINE" }, { "code": null, "e": 3526, "s": 3420, "text": "The following event binders are responsible for event handling related to entering text in TextCtrl box −" }, { "code": null, "e": 3535, "s": 3526, "text": "EVT_TEXT" }, { "code": null, "e": 3634, "s": 3535, "text": "Responds to changes in the contents of text box, either by manually keying in, or programmatically" }, { "code": null, "e": 3649, "s": 3634, "text": "EVT_TEXT_ENTER" }, { "code": null, "e": 3718, "s": 3649, "text": "Invokes associated handler when Enter key is pressed in the text box" }, { "code": null, "e": 3734, "s": 3718, "text": "EVT_TEXT_MAXLEN" }, { "code": null, "e": 3845, "s": 3734, "text": "Triggers associated handler as soon as the length of text entered reaches the value of SetMaxLength() function" }, { "code": null, "e": 3956, "s": 3845, "text": "In the following example, four objects of wx.TextCtrl class with different attributes are placed on the panel." }, { "code": null, "e": 4210, "s": 3956, "text": "self.t1 = wx.TextCtrl(panel) \nself.t2 = wx.TextCtrl(panel,style = wx.TE_PASSWORD) \nself.t3 = wx.TextCtrl(panel,size = (200,100),style = wx.TE_MULTILINE) \nself.t4 = wx.TextCtrl ( panel, value = \"ReadOnly Text\",\n style = wx.TE_READONLY | wx.TE_CENTER ) " }, { "code": null, "e": 4357, "s": 4210, "text": "While the first is a normal text box, the second is a password field. The third one is a multiline text box and the last text box is non-editable." }, { "code": null, "e": 4693, "s": 4357, "text": "EVT_TEXT binder on first box triggers OnKeyTyped() method for each key stroke in it. The second box is having its MaxLength set to 5. EVT_TEXT_MAXLEN binder sends OnMaxLen() function running as soon as the user tries to type more than 5 characters. The multiline text box responds to Enter key pressed because of EVT_TEXT_ENTER binder." }, { "code": null, "e": 4727, "s": 4693, "text": "The complete code is as follows −" }, { "code": null, "e": 6772, "s": 4727, "text": "import wx\n \nclass Mywin(wx.Frame): \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (350,250))\n\t\t\n panel = wx.Panel(self) \n vbox = wx.BoxSizer(wx.VERTICAL) \n \n hbox1 = wx.BoxSizer(wx.HORIZONTAL) \n l1 = wx.StaticText(panel, -1, \"Text Field\") \n\t\t\n hbox1.Add(l1, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n self.t1 = wx.TextCtrl(panel) \n\t\t\n hbox1.Add(self.t1,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n self.t1.Bind(wx.EVT_TEXT,self.OnKeyTyped) \n vbox.Add(hbox1) \n\t\t\n hbox2 = wx.BoxSizer(wx.HORIZONTAL)\n l2 = wx.StaticText(panel, -1, \"password field\") \n\t\t\n hbox2.Add(l2, 1, wx.ALIGN_LEFT|wx.ALL,5) \n self.t2 = wx.TextCtrl(panel,style = wx.TE_PASSWORD) \n self.t2.SetMaxLength(5) \n\t\t\n hbox2.Add(self.t2,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n vbox.Add(hbox2) \n self.t2.Bind(wx.EVT_TEXT_MAXLEN,self.OnMaxLen)\n\t\t\n hbox3 = wx.BoxSizer(wx.HORIZONTAL) \n l3 = wx.StaticText(panel, -1, \"Multiline Text\") \n\t\t\n hbox3.Add(l3,1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n self.t3 = wx.TextCtrl(panel,size = (200,100),style = wx.TE_MULTILINE) \n\t\t\n hbox3.Add(self.t3,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n vbox.Add(hbox3) \n self.t3.Bind(wx.EVT_TEXT_ENTER,self.OnEnterPressed) \n\t\t\n hbox4 = wx.BoxSizer(wx.HORIZONTAL) \n l4 = wx.StaticText(panel, -1, \"Read only text\") \n\t\t\n hbox4.Add(l4, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n self.t4 = wx.TextCtrl(panel, value = \"ReadOnly \n Text\",style = wx.TE_READONLY|wx.TE_CENTER) \n\t\t\t\n hbox4.Add(self.t4,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5) \n vbox.Add(hbox4) \n panel.SetSizer(vbox) \n \n self.Centre() \n self.Show() \n self.Fit() \n\t\t\n def OnKeyTyped(self, event): \n print event.GetString() \n\t\t\n def OnEnterPressed(self,event): \n print \"Enter pressed\" \n\t\t\n def OnMaxLen(self,event): \n print \"Maximum length reached\" \n\t\t\napp = wx.App() \nMywin(None, 'TextCtrl demo')\napp.MainLoop()" } ]
Classical Computing vs Quantum Computing
12 Jun, 2019 Introduction :The conventional method of computing is the most popular method for solving the desired problem with the estimated time complexities. Algorithms of searching, sorting and many others are there to tackle daily life problems and are efficiently controlled over time and space with respect to different approaches. For example, Linear Search has time complexity of O(n), Binary Search have (nlog2n). These all give a boom to software industries and other IT sectors to work for the welfare of the world. Basic Conventional Structure :Certainly, we use bits (either 0 or 1) for storing the information and with the help of these 2 bits, we calculate Giga to Tera to Petabytes of data and even much more with quite unparalleled efficiency. Now let’s go deep into it, Four classical Bits can be transformed in 24 combinations i.e. 16 combinations as follows- 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 That’s 16 possible combinations, out of which we can use only one at a time. Our CPU calculates at average 2.4GHz, apparently, it looks like that all combinations are calculated simultaneously but of course they are distinct from each other and CPU calculate one at a time each combination. Although simultaneous calculation can be done by having more than 1 CPU in the machine and that’s is called as Multiprocessing but that’s a different thing. The fact is that our CPU calculates each combination one at a time. Here arises a big and advanced research question – can all of them be used simultaneously at once without having any multiprocessors? To answer this crazy question, Quantum Computing came into the picture. This computing technique makes direct use of distinctively quantum mechanical phenomena such as superposition and entanglement to perform the operation on the data. The basic and extraordinary idea for quantum computing is that in normal classical computers, bits are the basic smallest unit of information. Quantum computers use qubits (Quantum bits) which can also be set up as 0 or 1 likewise the classical bits but the container of these bits are changed from transistors to photons. A Qubit can be among any 2 level quantum system, such as spin and a magnetic field, or a single photon. The possible states can be entitled as 0 or 1 as per the horizontal or vertical polarisation. Consequently, of Quantum World theory, qubit doesn’t have to be just one of those. it can be in any ratio of both the states at once. That merely called as Superposition.. Application of Quantum ComputingThis can lead to a severe and groundbreaking foundation in the field of computer science. This helps to solve many unsolved or virtually solvable problems with the unified space and time complexities. Creating an Application for the dice having 8 sidesTo write the basic program using quantum computing we have setup environment for the machine. Follow the below steps for setting up the Environment : Signup for a Free API key for Forest. After Signing up the API ket will be mailed to you freely. Check whether you have Python 3.x installed. (Use python –version). If version not updated then installed latest version from here) Once you have Right version install, install pyquil using command pip install pyquil Importing the required module : from pyquil.quil import Programfrom pyquil.api import QVMConnectionfrom pyquil.gates import Hfrom functools import reduce qvm = QVMConnection() > Important Note : Generally, quantum is programmed in Forest using the program object. QVM actually provides the connection to the quantum virtual machine (QVM). H is the Hadamard Gate. It is basically used to randomize the roll of the dice. reduce is basically the library used for iterative and looping functionalities. Final Program : from pyquil.quil import Programfrom pyquil.api import QVMConnectionfrom pyquil.gates import Hfrom functools import reduce qvm = QVMConnection() dice = Program(H(0),H(1), H(2)) roll = dice.measure_all() res = qvm.run(roll) value = reduce(lambda x,y: 2*x+y,res[0],0)+1 print ("Dice returned value are ", value) ; While printing the roll value we got some instructions set as Output : H 0 H 1 H 2 MEASURE 0 [0] MEASURE 1 [1] MEASURE 2 [2] These instruction sets are basically written in QUIL (Quantum Instruction Language) Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jun, 2019" }, { "code": null, "e": 569, "s": 54, "text": "Introduction :The conventional method of computing is the most popular method for solving the desired problem with the estimated time complexities. Algorithms of searching, sorting and many others are there to tackle daily life problems and are efficiently controlled over time and space with respect to different approaches. For example, Linear Search has time complexity of O(n), Binary Search have (nlog2n). These all give a boom to software industries and other IT sectors to work for the welfare of the world." }, { "code": null, "e": 921, "s": 569, "text": "Basic Conventional Structure :Certainly, we use bits (either 0 or 1) for storing the information and with the help of these 2 bits, we calculate Giga to Tera to Petabytes of data and even much more with quite unparalleled efficiency. Now let’s go deep into it, Four classical Bits can be transformed in 24 combinations i.e. 16 combinations as follows-" }, { "code": null, "e": 1038, "s": 921, "text": "0000 0001 0010 0011\n0100 0101 0110 0111\n1000 1001 1010 1011\n1100 1101 1110 1111\n" }, { "code": null, "e": 1688, "s": 1038, "text": "That’s 16 possible combinations, out of which we can use only one at a time. Our CPU calculates at average 2.4GHz, apparently, it looks like that all combinations are calculated simultaneously but of course they are distinct from each other and CPU calculate one at a time each combination. Although simultaneous calculation can be done by having more than 1 CPU in the machine and that’s is called as Multiprocessing but that’s a different thing. The fact is that our CPU calculates each combination one at a time. Here arises a big and advanced research question – can all of them be used simultaneously at once without having any multiprocessors?" }, { "code": null, "e": 2068, "s": 1688, "text": "To answer this crazy question, Quantum Computing came into the picture. This computing technique makes direct use of distinctively quantum mechanical phenomena such as superposition and entanglement to perform the operation on the data. The basic and extraordinary idea for quantum computing is that in normal classical computers, bits are the basic smallest unit of information." }, { "code": null, "e": 2618, "s": 2068, "text": "Quantum computers use qubits (Quantum bits) which can also be set up as 0 or 1 likewise the classical bits but the container of these bits are changed from transistors to photons. A Qubit can be among any 2 level quantum system, such as spin and a magnetic field, or a single photon. The possible states can be entitled as 0 or 1 as per the horizontal or vertical polarisation. Consequently, of Quantum World theory, qubit doesn’t have to be just one of those. it can be in any ratio of both the states at once. That merely called as Superposition.." }, { "code": null, "e": 2851, "s": 2618, "text": "Application of Quantum ComputingThis can lead to a severe and groundbreaking foundation in the field of computer science. This helps to solve many unsolved or virtually solvable problems with the unified space and time complexities." }, { "code": null, "e": 3052, "s": 2851, "text": "Creating an Application for the dice having 8 sidesTo write the basic program using quantum computing we have setup environment for the machine. Follow the below steps for setting up the Environment :" }, { "code": null, "e": 3149, "s": 3052, "text": "Signup for a Free API key for Forest. After Signing up the API ket will be mailed to you freely." }, { "code": null, "e": 3281, "s": 3149, "text": "Check whether you have Python 3.x installed. (Use python –version). If version not updated then installed latest version from here)" }, { "code": null, "e": 3366, "s": 3281, "text": "Once you have Right version install, install pyquil using command pip install pyquil" }, { "code": null, "e": 3398, "s": 3366, "text": "Importing the required module :" }, { "code": "from pyquil.quil import Programfrom pyquil.api import QVMConnectionfrom pyquil.gates import Hfrom functools import reduce qvm = QVMConnection()", "e": 3543, "s": 3398, "text": null }, { "code": null, "e": 3545, "s": 3543, "text": ">" }, { "code": null, "e": 3562, "s": 3545, "text": "Important Note :" }, { "code": null, "e": 3631, "s": 3562, "text": "Generally, quantum is programmed in Forest using the program object." }, { "code": null, "e": 3706, "s": 3631, "text": "QVM actually provides the connection to the quantum virtual machine (QVM)." }, { "code": null, "e": 3786, "s": 3706, "text": "H is the Hadamard Gate. It is basically used to randomize the roll of the dice." }, { "code": null, "e": 3866, "s": 3786, "text": "reduce is basically the library used for iterative and looping functionalities." }, { "code": null, "e": 3882, "s": 3866, "text": "Final Program :" }, { "code": "from pyquil.quil import Programfrom pyquil.api import QVMConnectionfrom pyquil.gates import Hfrom functools import reduce qvm = QVMConnection() dice = Program(H(0),H(1), H(2)) roll = dice.measure_all() res = qvm.run(roll) value = reduce(lambda x,y: 2*x+y,res[0],0)+1 print (\"Dice returned value are \", value)", "e": 4197, "s": 3882, "text": null }, { "code": null, "e": 4199, "s": 4197, "text": ";" }, { "code": null, "e": 4411, "s": 4199, "text": "While printing the roll value we got some instructions set as\nOutput : \nH 0\nH 1\nH 2\nMEASURE 0 [0]\nMEASURE 1 [1]\nMEASURE 2 [2]\n\nThese instruction sets are basically written in QUIL (Quantum Instruction Language)\n" }, { "code": null, "e": 4437, "s": 4411, "text": "Advanced Computer Subject" } ]
Decode a given pattern in two ways (Flipkart Interview Question)
23 Jun, 2022 A sender sends a binary string to a receiver meanwhile he encrypt the digits. You are given a encrypted form of string. Now, the receiver needs to decode the string, and while decoding there were 2 approaches. Let the encrypted binary string be P[] and actual string be S[]. First, receiver starts with first character as 0; S[0] = 0 // First decoded bit is 1 Remaining bits or S[i]s are decoded using following formulas. P[1] = S[1] + S[0] P[2] = S[2] + S[1] + S[0] P[3] = S[3] + S[2] + S[1] and so on ... Second, Receiver starts with first character as 1; S[0] = 1 // First decoded bit is 1 Remaining bits or S[i]s are decoded using following formulas. P[1] = S[1] + S[0] P[2] = S[2] + S[1] + S[0] P[3] = S[3] + S[2] + S[1] and so on ... You need to print two string generated using two different after evaluation from both first and second technique. If any string contains other that binary numbers you need to print NONE. Input1; 0123210 Output: 0111000, NONE Explanation for first output S[0] = 0, P[1] = S[1] + S[0], S[1] = 1 P[2] = S[2] + S[1] + S[0], S[2] = 1 P[3] = S[3] + S[2] + S[1], S[3] = 1 P[4] = S[4] + S[3] + S[2], S[4] = 0 P[5] = S[5] + S[4] + S[3], S[5] = 0 P[6] = S[6] + S[5] + S[4], S[6] = 0 Explanation for second output S[0] = 1, P[1] = S[1] + S[0], S[1] = 0 P[2] = s[2] + S[1] + S[0], S[2] = 1 P[3] = S[3] + S[2] + S[1], S[3] = 2, not a binary character so NONE. Source: Flipkart Interview | Set 9 (On-Campus) The idea to solve this problem is simple, we keep track of last two decoded bits. The current bit S[i] can always be calculated by subtracting last two decoded bits from P[i]. Following is the implementation of above idea. We store last two decoded bits in ‘first’ and ‘second’. C++ Java Python3 C# PHP Javascript #include<iostream>using namespace std; // This function prints decoding of P[] with first decoded// number as 'first'. If the decoded numbers contain anything// other than 0, then "NONE" is printedvoid decodeUtil(int P[], int n, int first){ int S[n]; // array to store decoded bit pattern S[0] = first; // The first number is always the given number int second = 0; // Initialize second // Calculate all bits starting from second for (int i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { cout << "NONE\n"; return; } second = first; first = S[i]; } // Print the output array for (int i = 0; i < n; i++) cout << S[i]; cout << endl;} // This function decodes P[] using two techniques// 1) Starts with 0 as first number 2) Starts 1 as first numbervoid decode(int P[], int n){ decodeUtil(P, n, 0); decodeUtil(P, n, 1);} int main(){ int P[] = {0, 1, 2, 3, 2, 1, 0}; int n = sizeof(P)/sizeof(P[0]); decode(P, n); return 0;} class GFG{ // This function prints decoding of P[]// with first decoded number as 'first'.// If the decoded numbers contain anything// other than 0, then "NONE" is printedpublic static void decodeUtil(int P[], int n, int first){ // Array to store decoded bit pattern int S[] = new int[n]; // The first number is always // the given number S[0] = first; // Initialize second int second = 0; // Calculate all bits starting // from second for(int i = 1; i < n; i++) { S[i] = P[i] - first-second; if (S[i] != 1 && S[i] != 0) { System.out.println("NONE"); return; } second = first; first = S[i]; } // Print the output array for(int i = 0; i < n; i++) { System.out.print(S[i]); } System.out.println();} // Driver codepublic static void main(String []args){ int P[] = { 0, 1, 2, 3, 2, 1, 0 }; int n = P.length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1);}} // This code is contributed by avanitrachhadiya2155 # This function prints decoding of P[] with# first decoded number as 'first'. If the# decoded numbers contain anything other# than 0, then "NONE" is printeddef decodeUtil(P, n, first): S = [0 for i in range(n)] # array to store decoded bit pattern S[0] = first # The first number is # always the given number second = 0 # Initialize second # Calculate all bits starting from second for i in range(1, n, 1): S[i] = P[i] - first - second if (S[i] != 1 and S[i] != 0): print("NONE") return second = first first = S[i] # Print the output array for i in range(0, n, 1): print(S[i], end = "") print("\n", end = "") # This function decodes P[] using# two techniques# 1) Starts with 0 as first number# 2) Starts 1 as first numberdef decode(P, n): decodeUtil(P, n, 0) decodeUtil(P, n, 1) # Driver Codeif __name__ == '__main__': P = [0, 1, 2, 3, 2, 1, 0] n = len(P) decode(P, n) # This code is contributed by# Shashank_Sharma using System; class GFG{ // This function prints decoding of P[]// with first decoded number as 'first'.// If the decoded numbers contain anything// other than 0, then "NONE" is printedstatic void decodeUtil(int[] P, int n, int first){ // Array to store decoded bit pattern int[] S = new int[n]; // The first number is always // the given number S[0] = first; // Initialize second int second = 0; // Calculate all bits starting // from second for(int i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { Console.WriteLine("NONE"); return; } second = first; first = S[i]; } // Print the output array for(int i = 0; i < n; i++) { Console.Write(S[i]); } Console.WriteLine();} // Driver codestatic public void Main(){ int[] P = { 0, 1, 2, 3, 2, 1, 0 }; int n = P.Length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1);}} // This code is contributed by rag2127 <?php // This function prints decoding// of P[] with first decoded// number as 'first'. If the// decoded numbers contain anything// other than 0, then "NONE" is printedfunction decodeUtil($P, $n, $first){ // The first number is always // the given number $S[0] = $first; // Initialize second $second = 0; // Calculate all bits starting // from second for ($i = 1; $i < $n; $i++) { $S[$i] = $P[$i] - $first - $second; if ($S[$i] != 1 && $S[$i] != 0) { echo "NONE\n"; return; } $second = $first; $first = $S[$i]; } // Print the output array for ($i = 0; $i < $n; $i++) echo $S[$i]; echo "\n";} // This function decodes P[]// using two techniques// 1) Starts with 0 as first number// 2) Starts 1 as first numberfunction decode($P, $n){ decodeUtil($P, $n, 0); decodeUtil($P, $n, 1);} // Driver Code $P=array (0, 1, 2, 3, 2, 1, 0); $n = sizeof($P); decode($P, $n); // This code is contributed by ajit?> <script> // This function prints decoding of P[] // with first decoded number as 'first'. // If the decoded numbers contain anything // other than 0, then "NONE" is printed function decodeUtil(P, n, first) { // Array to store decoded bit pattern let S = new Array(n); // The first number is always // the given number S[0] = first; // Initialize second let second = 0; // Calculate all bits starting // from second for(let i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { document.write("NONE" + "</br>"); return; } second = first; first = S[i]; } // Print the output array for(let i = 0; i < n; i++) { document.write(S[i]); } document.write("</br>"); } let P = [ 0, 1, 2, 3, 2, 1, 0 ]; let n = P.length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1); </script> 0111000 NONE Time Complexity: O(n) jit_t Shashank_Sharma nidhi_biet avanitrachhadiya2155 rag2127 mukesh07 hardikkoriintern Flipkart Arrays Flipkart Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Move all negative numbers to beginning and positive to end with constant extra space Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers)
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 262, "s": 52, "text": "A sender sends a binary string to a receiver meanwhile he encrypt the digits. You are given a encrypted form of string. Now, the receiver needs to decode the string, and while decoding there were 2 approaches." }, { "code": null, "e": 328, "s": 262, "text": "Let the encrypted binary string be P[] and actual string be S[]. " }, { "code": null, "e": 803, "s": 328, "text": "First, receiver starts with first character as 0; \nS[0] = 0 // First decoded bit is 1\nRemaining bits or S[i]s are decoded using following formulas.\nP[1] = S[1] + S[0] \nP[2] = S[2] + S[1] + S[0] \nP[3] = S[3] + S[2] + S[1] \nand so on ...\n\nSecond, Receiver starts with first character as 1; \nS[0] = 1 // First decoded bit is 1\nRemaining bits or S[i]s are decoded using following formulas.\nP[1] = S[1] + S[0] \nP[2] = S[2] + S[1] + S[0] \nP[3] = S[3] + S[2] + S[1] \nand so on ..." }, { "code": null, "e": 991, "s": 803, "text": "You need to print two string generated using two different after evaluation from both first and second technique. If any string contains other that binary numbers you need to print NONE. " }, { "code": null, "e": 1456, "s": 991, "text": "Input1; 0123210\nOutput: 0111000, NONE\n\nExplanation for first output\nS[0] = 0, \nP[1] = S[1] + S[0], S[1] = 1\nP[2] = S[2] + S[1] + S[0], S[2] = 1\nP[3] = S[3] + S[2] + S[1], S[3] = 1\nP[4] = S[4] + S[3] + S[2], S[4] = 0 \nP[5] = S[5] + S[4] + S[3], S[5] = 0\nP[6] = S[6] + S[5] + S[4], S[6] = 0\n\nExplanation for second output \nS[0] = 1,\nP[1] = S[1] + S[0], S[1] = 0\nP[2] = s[2] + S[1] + S[0], S[2] = 1\nP[3] = S[3] + S[2] + S[1], S[3] = 2, not a binary character so NONE." }, { "code": null, "e": 1503, "s": 1456, "text": "Source: Flipkart Interview | Set 9 (On-Campus)" }, { "code": null, "e": 1679, "s": 1503, "text": "The idea to solve this problem is simple, we keep track of last two decoded bits. The current bit S[i] can always be calculated by subtracting last two decoded bits from P[i]." }, { "code": null, "e": 1782, "s": 1679, "text": "Following is the implementation of above idea. We store last two decoded bits in ‘first’ and ‘second’." }, { "code": null, "e": 1786, "s": 1782, "text": "C++" }, { "code": null, "e": 1791, "s": 1786, "text": "Java" }, { "code": null, "e": 1799, "s": 1791, "text": "Python3" }, { "code": null, "e": 1802, "s": 1799, "text": "C#" }, { "code": null, "e": 1806, "s": 1802, "text": "PHP" }, { "code": null, "e": 1817, "s": 1806, "text": "Javascript" }, { "code": "#include<iostream>using namespace std; // This function prints decoding of P[] with first decoded// number as 'first'. If the decoded numbers contain anything// other than 0, then \"NONE\" is printedvoid decodeUtil(int P[], int n, int first){ int S[n]; // array to store decoded bit pattern S[0] = first; // The first number is always the given number int second = 0; // Initialize second // Calculate all bits starting from second for (int i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { cout << \"NONE\\n\"; return; } second = first; first = S[i]; } // Print the output array for (int i = 0; i < n; i++) cout << S[i]; cout << endl;} // This function decodes P[] using two techniques// 1) Starts with 0 as first number 2) Starts 1 as first numbervoid decode(int P[], int n){ decodeUtil(P, n, 0); decodeUtil(P, n, 1);} int main(){ int P[] = {0, 1, 2, 3, 2, 1, 0}; int n = sizeof(P)/sizeof(P[0]); decode(P, n); return 0;}", "e": 2891, "s": 1817, "text": null }, { "code": "class GFG{ // This function prints decoding of P[]// with first decoded number as 'first'.// If the decoded numbers contain anything// other than 0, then \"NONE\" is printedpublic static void decodeUtil(int P[], int n, int first){ // Array to store decoded bit pattern int S[] = new int[n]; // The first number is always // the given number S[0] = first; // Initialize second int second = 0; // Calculate all bits starting // from second for(int i = 1; i < n; i++) { S[i] = P[i] - first-second; if (S[i] != 1 && S[i] != 0) { System.out.println(\"NONE\"); return; } second = first; first = S[i]; } // Print the output array for(int i = 0; i < n; i++) { System.out.print(S[i]); } System.out.println();} // Driver codepublic static void main(String []args){ int P[] = { 0, 1, 2, 3, 2, 1, 0 }; int n = P.length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1);}} // This code is contributed by avanitrachhadiya2155", "e": 4126, "s": 2891, "text": null }, { "code": "# This function prints decoding of P[] with# first decoded number as 'first'. If the# decoded numbers contain anything other# than 0, then \"NONE\" is printeddef decodeUtil(P, n, first): S = [0 for i in range(n)] # array to store decoded bit pattern S[0] = first # The first number is # always the given number second = 0 # Initialize second # Calculate all bits starting from second for i in range(1, n, 1): S[i] = P[i] - first - second if (S[i] != 1 and S[i] != 0): print(\"NONE\") return second = first first = S[i] # Print the output array for i in range(0, n, 1): print(S[i], end = \"\") print(\"\\n\", end = \"\") # This function decodes P[] using# two techniques# 1) Starts with 0 as first number# 2) Starts 1 as first numberdef decode(P, n): decodeUtil(P, n, 0) decodeUtil(P, n, 1) # Driver Codeif __name__ == '__main__': P = [0, 1, 2, 3, 2, 1, 0] n = len(P) decode(P, n) # This code is contributed by# Shashank_Sharma", "e": 5182, "s": 4126, "text": null }, { "code": "using System; class GFG{ // This function prints decoding of P[]// with first decoded number as 'first'.// If the decoded numbers contain anything// other than 0, then \"NONE\" is printedstatic void decodeUtil(int[] P, int n, int first){ // Array to store decoded bit pattern int[] S = new int[n]; // The first number is always // the given number S[0] = first; // Initialize second int second = 0; // Calculate all bits starting // from second for(int i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { Console.WriteLine(\"NONE\"); return; } second = first; first = S[i]; } // Print the output array for(int i = 0; i < n; i++) { Console.Write(S[i]); } Console.WriteLine();} // Driver codestatic public void Main(){ int[] P = { 0, 1, 2, 3, 2, 1, 0 }; int n = P.Length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1);}} // This code is contributed by rag2127", "e": 6370, "s": 5182, "text": null }, { "code": "<?php // This function prints decoding// of P[] with first decoded// number as 'first'. If the// decoded numbers contain anything// other than 0, then \"NONE\" is printedfunction decodeUtil($P, $n, $first){ // The first number is always // the given number $S[0] = $first; // Initialize second $second = 0; // Calculate all bits starting // from second for ($i = 1; $i < $n; $i++) { $S[$i] = $P[$i] - $first - $second; if ($S[$i] != 1 && $S[$i] != 0) { echo \"NONE\\n\"; return; } $second = $first; $first = $S[$i]; } // Print the output array for ($i = 0; $i < $n; $i++) echo $S[$i]; echo \"\\n\";} // This function decodes P[]// using two techniques// 1) Starts with 0 as first number// 2) Starts 1 as first numberfunction decode($P, $n){ decodeUtil($P, $n, 0); decodeUtil($P, $n, 1);} // Driver Code $P=array (0, 1, 2, 3, 2, 1, 0); $n = sizeof($P); decode($P, $n); // This code is contributed by ajit?>", "e": 7401, "s": 6370, "text": null }, { "code": "<script> // This function prints decoding of P[] // with first decoded number as 'first'. // If the decoded numbers contain anything // other than 0, then \"NONE\" is printed function decodeUtil(P, n, first) { // Array to store decoded bit pattern let S = new Array(n); // The first number is always // the given number S[0] = first; // Initialize second let second = 0; // Calculate all bits starting // from second for(let i = 1; i < n; i++) { S[i] = P[i] - first - second; if (S[i] != 1 && S[i] != 0) { document.write(\"NONE\" + \"</br>\"); return; } second = first; first = S[i]; } // Print the output array for(let i = 0; i < n; i++) { document.write(S[i]); } document.write(\"</br>\"); } let P = [ 0, 1, 2, 3, 2, 1, 0 ]; let n = P.length; // This function decodes P[] using // two techniques 1) Starts with 0 // as first number 2) Starts 1 as // first number decodeUtil(P, n, 0); decodeUtil(P, n, 1); </script>", "e": 8598, "s": 7401, "text": null }, { "code": null, "e": 8612, "s": 8598, "text": "0111000\nNONE\n" }, { "code": null, "e": 8634, "s": 8612, "text": "Time Complexity: O(n)" }, { "code": null, "e": 8640, "s": 8634, "text": "jit_t" }, { "code": null, "e": 8656, "s": 8640, "text": "Shashank_Sharma" }, { "code": null, "e": 8667, "s": 8656, "text": "nidhi_biet" }, { "code": null, "e": 8688, "s": 8667, "text": "avanitrachhadiya2155" }, { "code": null, "e": 8696, "s": 8688, "text": "rag2127" }, { "code": null, "e": 8705, "s": 8696, "text": "mukesh07" }, { "code": null, "e": 8722, "s": 8705, "text": "hardikkoriintern" }, { "code": null, "e": 8731, "s": 8722, "text": "Flipkart" }, { "code": null, "e": 8738, "s": 8731, "text": "Arrays" }, { "code": null, "e": 8747, "s": 8738, "text": "Flipkart" }, { "code": null, "e": 8754, "s": 8747, "text": "Arrays" }, { "code": null, "e": 8852, "s": 8754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8884, "s": 8852, "text": "Introduction to Data Structures" }, { "code": null, "e": 8909, "s": 8884, "text": "Window Sliding Technique" }, { "code": null, "e": 8956, "s": 8909, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 9020, "s": 8956, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9051, "s": 9020, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 9072, "s": 9051, "text": "Next Greater Element" }, { "code": null, "e": 9130, "s": 9072, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 9215, "s": 9130, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 9242, "s": 9215, "text": "Count pairs with given sum" } ]
Program to check diagonal matrix and scalar matrix in C++
Given a matrix M[r][c], ‘r’ denotes number of rows and ‘c’ denotes number of columns such that r = c forming a square matrix. We have to find whether the given square matrix is diagonal and scalar matrix or not, if it is diagonal and scalar matrix then print yes in the result. A square matrix m[][] will be diagonal matrix if and only if the elements of the except the main diagonal are zero. Like in the given figure below − Here, the elements in the red are main diagonal which are non-zero rest elements except the main diagonal are zero making it a Diagonal matrix. Input: m[3][3] = { {7, 0, 0}, {0, 8, 0}, {0, 0, 9}} Output: yes Input: m[3][3] = { {1, 2, 3}, {0, 4, 0}, {0, 0, 5} } Output: no Start Step 1 -> define macro of size 4 Step 2 -> declare function to check if matrix is diagonal or not bool ifdiagonal(int arr[size][size]) Loop For int i = 0 and i < size and i++ Loop for int j = 0 and j < size and j++ IF ((i != j) & (arr[i][j] != 0)) return false End End End return true step 3 -> In main() Declare and set int arr[size][size] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; IF (ifdiagonal(arr)) Print its a diagonal matrix End Else Print its not a diagonal matrix End Stop #include <bits/stdc++.h> #define size 4 using namespace std; // check if matrix is diagonal matrix or not. bool ifdiagonal(int arr[size][size]){ for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) if ((i != j) && (arr[i][j] != 0)) return false; return true; } int main(){ int arr[size][size] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; if (ifdiagonal(arr)) cout << "its a diagonal matrix" << endl; else cout << "its not a diagonal matrix" << endl; return 0; } its a diagonal matrix A square matrix m[][] is Scalar Matrix if the elements in the main diagonal are equal and the rest of the elements are zero. Like in the given example below − Here, the elements in the red are the diagonal elements which are same and rest elements are zero making it a Scalar Matrix. Input: m[3][3] = { {2, 0, 0}, {0, 2, 0}, {0, 0, 2} } Output: yes Input: m[3][3] = { {3, 0, 0}, {0, 2, 0}, {0, 0, 3} } Output: no Start Step 1 -> Declare macro as #define size 4 Step 2 -> declare function to check matrix is scalar matrix or not. bool scalar(int arr[size][size]) Loop For int i = 0 and i < size and i++ Loop For int j = 0 and j < size and j++ IF ((i != j) && (arr[i][j] != 0)) return false End End End Loop for int i = 0 and i < size – 1 and i++ If (arr[i][i] != arr[i + 1][i + 1]) return false End End Return true Step 3 -> In main() Declare array as int arr[size][size] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } } IF(scalar(arr)) Print its a scalar matrix Else Print its not a scalar matrix Stop #include <bits/stdc++.h> #define size 4 using namespace std; // check matrix is scalar matrix or not. bool scalar(int arr[size][size]){ for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) if ((i != j) && (arr[i][j] != 0)) return false; for (int i = 0; i < size - 1; i++) if (arr[i][i] != arr[i + 1][i + 1]) return false; return true; } int main(){ int arr[size][size] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; if (scalar(arr)) cout << "its a scalar matrix" << endl; else cout << "its not a scalar matrix" << endl; return 0; } its a scalar matrix
[ { "code": null, "e": 1465, "s": 1187, "text": "Given a matrix M[r][c], ‘r’ denotes number of rows and ‘c’ denotes number of columns such that r = c forming a square matrix. We have to find whether the given square matrix is diagonal and scalar matrix or not, if it is diagonal and scalar matrix then print yes in the result." }, { "code": null, "e": 1581, "s": 1465, "text": "A square matrix m[][] will be diagonal matrix if and only if the elements of the except the main diagonal are zero." }, { "code": null, "e": 1614, "s": 1581, "text": "Like in the given figure below −" }, { "code": null, "e": 1758, "s": 1614, "text": "Here, the elements in the red are main diagonal which are non-zero rest elements except the main diagonal are zero making it a Diagonal matrix." }, { "code": null, "e": 1899, "s": 1758, "text": "Input: m[3][3] = { {7, 0, 0},\n {0, 8, 0},\n {0, 0, 9}}\nOutput: yes\nInput: m[3][3] = { {1, 2, 3},\n {0, 4, 0},\n {0, 0, 5}\n}\nOutput: no" }, { "code": null, "e": 2532, "s": 1899, "text": "Start\nStep 1 -> define macro of size 4\nStep 2 -> declare function to check if matrix is diagonal or not\n bool ifdiagonal(int arr[size][size])\n Loop For int i = 0 and i < size and i++\n Loop for int j = 0 and j < size and j++\n IF ((i != j) & (arr[i][j] != 0))\n return false\n End\n End\n End\n return true\nstep 3 -> In main()\n Declare and set int arr[size][size] = { { 1, 0, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 1, 0 },\n { 0, 0, 0, 1 }\n };\n IF (ifdiagonal(arr))\n Print its a diagonal matrix\n End\n Else\n Print its not a diagonal matrix\n End\nStop" }, { "code": null, "e": 3095, "s": 2532, "text": "#include <bits/stdc++.h>\n#define size 4\nusing namespace std;\n// check if matrix is diagonal matrix or not.\nbool ifdiagonal(int arr[size][size]){\n for (int i = 0; i < size; i++)\n for (int j = 0; j < size; j++)\n\n if ((i != j) && (arr[i][j] != 0))\n return false;\n return true;\n}\nint main(){\n int arr[size][size] = { { 1, 0, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 1, 0 },\n { 0, 0, 0, 1 }\n };\n if (ifdiagonal(arr))\n cout << \"its a diagonal matrix\" << endl;\n else\n cout << \"its not a diagonal matrix\" << endl;\n return 0;\n}" }, { "code": null, "e": 3117, "s": 3095, "text": "its a diagonal matrix" }, { "code": null, "e": 3243, "s": 3117, "text": " A square matrix m[][] is Scalar Matrix if the elements in the main diagonal are equal and the rest of the elements are zero." }, { "code": null, "e": 3277, "s": 3243, "text": "Like in the given example below −" }, { "code": null, "e": 3405, "s": 3279, "text": "Here, the elements in the red are the diagonal elements which are same and rest elements are zero making it a Scalar Matrix. " }, { "code": null, "e": 3546, "s": 3405, "text": "Input: m[3][3] = { {2, 0, 0},\n {0, 2, 0},\n {0, 0, 2} }\nOutput: yes\nInput: m[3][3] = { {3, 0, 0},\n {0, 2, 0},\n {0, 0, 3} }\nOutput: no" }, { "code": null, "e": 4293, "s": 3546, "text": "Start\nStep 1 -> Declare macro as #define size 4\nStep 2 -> declare function to check matrix is scalar matrix or not.\n bool scalar(int arr[size][size])\n Loop For int i = 0 and i < size and i++\n Loop For int j = 0 and j < size and j++\n IF ((i != j) && (arr[i][j] != 0))\n return false\n End\n End\n End\n Loop for int i = 0 and i < size – 1 and i++\n If (arr[i][i] != arr[i + 1][i + 1])\n return false\n End\n End\n Return true\nStep 3 -> In main()\n Declare array as int arr[size][size] = { { 2, 0, 0, 0 },\n { 0, 2, 0, 0 },\n { 0, 0, 2, 0 },\n { 0, 0, 0, 2 }\n }\n IF(scalar(arr))\n Print its a scalar matrix\n Else\n Print its not a scalar matrix\nStop" }, { "code": null, "e": 4947, "s": 4293, "text": "#include <bits/stdc++.h>\n#define size 4\nusing namespace std;\n// check matrix is scalar matrix or not.\nbool scalar(int arr[size][size]){\n for (int i = 0; i < size; i++)\n for (int j = 0; j < size; j++)\n if ((i != j) && (arr[i][j] != 0))\n return false;\n for (int i = 0; i < size - 1; i++)\n if (arr[i][i] != arr[i + 1][i + 1])\n return false;\n return true;\n}\nint main(){\n int arr[size][size] = { { 2, 0, 0, 0 },\n { 0, 2, 0, 0 },\n { 0, 0, 2, 0 },\n { 0, 0, 0, 2 } };\n if (scalar(arr))\n cout << \"its a scalar matrix\" << endl;\n else\n cout << \"its not a scalar matrix\" << endl;\n return 0;\n}" }, { "code": null, "e": 4967, "s": 4947, "text": "its a scalar matrix" } ]
HTTP headers | Link
23 Jun, 2020 For serialising one or more links in HTTP headers, the HTTP Link header-field is used. It allows the server to point an interested client to another resource containing metadata about the requested resource. It is semantically equivalent to the HTML <link> element. Syntax: Link: <uri-reference>; param1="value1" param2="value2" Directive: This header accept a single directive as mentioned above and described below. The link header contains parameters, which are separated with ; and are equivalent to attributes of the <link> element. <uri-reference>: The URI reference, must be enclosed between < and >. Examples: This means that more information about the requested resource is available in the resource whose relative URI is https://www.geeksforgeeks.org/. Link: <https://www.geeksforgeeks.org/>; rel="preconnect" The URI must be enclosed between < and >. So, this is not a good way to write. Link:https://www.geeksforgeeks.org/; rel="preconnect" Specifying multiple links: You can specify multiple links separated by commas. Example: Link: <https://example.one.com>; rel="preconnect", <https://example.two.com>; rel="preconnect", <https://example.three.com>; rel="preconnect" Typical uses are: A map of different language, content-type and version-specific URIs Licensing, such as Creative Commons Information about how to edit the file Policy information about appropriate use and/or distribution of the data Supported Browsers: The browser supported by HTTP-header link are unknown till now. HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request ReactJS | Router Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? How to get character array from string in JavaScript?
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2020" }, { "code": null, "e": 329, "s": 54, "text": "For serialising one or more links in HTTP headers, the HTTP Link header-field is used. It allows the server to point an interested client to another resource containing metadata about the requested resource. It is semantically equivalent to the HTML <link> element. Syntax: " }, { "code": null, "e": 385, "s": 329, "text": "Link: <uri-reference>; param1=\"value1\" param2=\"value2\"\n" }, { "code": null, "e": 595, "s": 385, "text": "Directive: This header accept a single directive as mentioned above and described below. The link header contains parameters, which are separated with ; and are equivalent to attributes of the <link> element. " }, { "code": null, "e": 666, "s": 595, "text": "<uri-reference>: The URI reference, must be enclosed between < and >. " }, { "code": null, "e": 677, "s": 666, "text": "Examples: " }, { "code": null, "e": 822, "s": 677, "text": "This means that more information about the requested resource is available in the resource whose relative URI is https://www.geeksforgeeks.org/." }, { "code": null, "e": 880, "s": 822, "text": "Link: <https://www.geeksforgeeks.org/>; rel=\"preconnect\"\n" }, { "code": null, "e": 959, "s": 880, "text": "The URI must be enclosed between < and >. So, this is not a good way to write." }, { "code": null, "e": 1014, "s": 959, "text": "Link:https://www.geeksforgeeks.org/; rel=\"preconnect\"\n" }, { "code": null, "e": 1095, "s": 1014, "text": "Specifying multiple links: You can specify multiple links separated by commas. " }, { "code": null, "e": 1105, "s": 1095, "text": "Example: " }, { "code": null, "e": 1250, "s": 1105, "text": "Link: <https://example.one.com>; rel=\"preconnect\", \n<https://example.two.com>; rel=\"preconnect\", \n<https://example.three.com>; rel=\"preconnect\"\n" }, { "code": null, "e": 1269, "s": 1250, "text": "Typical uses are: " }, { "code": null, "e": 1337, "s": 1269, "text": "A map of different language, content-type and version-specific URIs" }, { "code": null, "e": 1373, "s": 1337, "text": "Licensing, such as Creative Commons" }, { "code": null, "e": 1412, "s": 1373, "text": "Information about how to edit the file" }, { "code": null, "e": 1485, "s": 1412, "text": "Policy information about appropriate use and/or distribution of the data" }, { "code": null, "e": 1571, "s": 1485, "text": "Supported Browsers: The browser supported by HTTP-header link are unknown till now. " }, { "code": null, "e": 1584, "s": 1571, "text": "HTTP-headers" }, { "code": null, "e": 1591, "s": 1584, "text": "Picked" }, { "code": null, "e": 1608, "s": 1591, "text": "Web Technologies" }, { "code": null, "e": 1706, "s": 1608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1767, "s": 1706, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1810, "s": 1767, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1882, "s": 1810, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1922, "s": 1882, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1946, "s": 1922, "text": "REST API (Introduction)" }, { "code": null, "e": 1987, "s": 1946, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2004, "s": 1987, "text": "ReactJS | Router" }, { "code": null, "e": 2046, "s": 2004, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2093, "s": 2046, "text": "How to float three div side by side using CSS?" } ]
How to Generate Route Between Two Locations in Google Map in Android?
18 Jul, 2021 Google Map or any other such applications have methods to generate a route between two locations. Generally, there are a lot of parameters like closest distance, the fastest distance, alternative routes, etc to suffice the needs. These apps are really appealing, but the developer knows the pain behind developing such beautiful applications. Through this article, we will show you how you can generate a route between two locations in a Google Map in Android. Follow the below steps to begin. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. 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. Step 2: Add these dependencies and sync the project // For Map fragment implementation ‘com.google.android.libraries.places:places:2.4.0’ // To make a call to for getting Coordinates response from a Web URL implementation ‘com.squareup.okhttp3:okhttp:4.9.0’ Step 3: Add this permission in AndroidManifest.xml file <manifest.....> <uses-permission android:name=”android.permission.INTERNET” /> <application.......> </application.......> </manifest.....> Step 4: Add this Google Map fragment in the activity_main.xml file XML <!--Give it an ID as we will call this in the Main code--><fragment android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment"/> Step 5: Get and store your Places API Key Our application utilizes Google’s Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio? Our application utilizes Google’s Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs. Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio? Step 6: Retrieve & validate your key in MainActivity After referring to the above two articles, you will have your API key called in the Main. To validate the key for using Map Fragment, add this code. Kotlin if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } Step 7: Initialize the Map Fragment After appending the below code, the IDE will want to extend the MainActivity to OnMapReadyCallback. Apply these changes. You will also need to implement the member functions now. The member function will be onMapReady. Once done, the code will have no errors. Kotlin val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragmentmapFragment.getMapAsync(this) Step 8: Get the coordinates of two places We have manually declared the latitude and longitude values of two places, between whom we wish to generate a route. We declared them globally. But you can use your own methods to get those coordinates. Kotlin // GeeksforGeeks coordinatesprivate var originLatitude: Double = 28.5021359private var originLongitude: Double = 77.4054901 // Coordinates of a park nearbyprivate var destinationLatitude: Double = 28.5151087private var destinationLongitude: Double = 77.3932163 Step 9: Edit the onMapReady function mMap is already declared in the global variable. Kotlin private lateinit var mMap: GoogleMap Now we shall change the onMapReady call. Kotlin override fun onMapReady(p0: GoogleMap?) { mMap = p0!! val originLocation = LatLng(originLatitude, originLongitude) mMap.clear() mMap.addMarker(MarkerOptions().position(originLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 18F)) } Step 10: Create a function to generate the direction URL Kotlin private fun getDirectionURL(origin:LatLng, dest:LatLng, secret: String) : String{ return "https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}" + "&destination=${dest.latitude},${dest.longitude}" + "&sensor=false" + "&mode=driving" + "&key=$secret" } Step 11: Create a function to decode polyline Kotlin fun decodePolyline(encoded: String): List<LatLng> { val poly = ArrayList<LatLng>() var index = 0 val len = encoded.length var lat = 0 var lng = 0 while (index < len) { var b: Int var shift = 0 var result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlat = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lat += dlat shift = 0 result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlng = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lng += dlng val latLng = LatLng((lat.toDouble() / 1E5),(lng.toDouble() / 1E5)) poly.add(latLng) } return poly } Step 12: Create a class for Map Parameters The response when Step 10 is passed requires an instance of the object to catch the JSON. This class is that object. Kotlin class MapData { var routes = ArrayList<Routes>()} class Routes { var legs = ArrayList<Legs>()} class Legs { var distance = Distance() var duration = Duration() var end_address = "" var start_address = "" var end_location =Location() var start_location = Location() var steps = ArrayList<Steps>()} class Steps { var distance = Distance() var duration = Duration() var end_address = "" var start_address = "" var end_location =Location() var start_location = Location() var polyline = PolyLine() var travel_mode = "" var maneuver = ""} class Duration { var text = "" var value = 0} class Distance { var text = "" var value = 0} class PolyLine { var points = ""} class Location{ var lat ="" var lng =""} Step 13: Create an inner class to pass the URL string generated in Step 8 and call the decode polyline function Kotlin @SuppressLint("StaticFieldLeak") private inner class GetDirection(val url : String) : AsyncTask<Void, Void, List<List<LatLng>>>(){ override fun doInBackground(vararg params: Void?): List<List<LatLng>> { val client = OkHttpClient() val request = Request.Builder().url(url).build() val response = client.newCall(request).execute() val data = response.body!!.string() val result = ArrayList<List<LatLng>>() try{ val respObj = Gson().fromJson(data,MapData::class.java) val path = ArrayList<LatLng>() for (i in 0 until respObj.routes[0].legs[0].steps.size){ path.addAll(decodePolyline(respObj.routes[0].legs[0].steps[i].polyline.points)) } result.add(path) }catch (e:Exception){ e.printStackTrace() } return result } override fun onPostExecute(result: List<List<LatLng>>) { val lineoption = PolylineOptions() for (i in result.indices){ lineoption.addAll(result[i]) lineoption.width(10f) lineoption.color(Color.GREEN) lineoption.geodesic(true) } mMap.addPolyline(lineoption) }} Download the Source Code from here. Kotlin Kotlin XML // MainActivity.kt import android.annotation.SuppressLintimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.graphics.Colorimport android.os.AsyncTaskimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.MarkerOptionsimport com.google.android.gms.maps.model.PolylineOptionsimport com.google.android.libraries.places.api.Placesimport com.google.gson.Gsonimport okhttp3.OkHttpClientimport okhttp3.Request class MainActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private var originLatitude: Double = 28.5021359 private var originLongitude: Double = 77.4054901 private var destinationLatitude: Double = 28.5151087 private var destinationLongitude: Double = 77.3932163 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData["com.google.android.geo.API_KEY"] val apiKey = value.toString() // Initializing the Places API with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Map Fragment val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) val gd = findViewById<Button>(R.id.directions) gd.setOnClickListener{ mapFragment.getMapAsync { mMap = it val originLocation = LatLng(originLatitude, originLongitude) mMap.addMarker(MarkerOptions().position(originLocation)) val destinationLocation = LatLng(destinationLatitude, destinationLongitude) mMap.addMarker(MarkerOptions().position(destinationLocation)) val urll = getDirectionURL(originLocation, destinationLocation, apiKey) GetDirection(urll).execute() mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 14F)) } } } override fun onMapReady(p0: GoogleMap?) { mMap = p0!! val originLocation = LatLng(originLatitude, originLongitude) mMap.clear() mMap.addMarker(MarkerOptions().position(originLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 18F)) } private fun getDirectionURL(origin:LatLng, dest:LatLng, secret: String) : String{ return "https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}" + "&destination=${dest.latitude},${dest.longitude}" + "&sensor=false" + "&mode=driving" + "&key=$secret" } @SuppressLint("StaticFieldLeak") private inner class GetDirection(val url : String) : AsyncTask<Void, Void, List<List<LatLng>>>(){ override fun doInBackground(vararg params: Void?): List<List<LatLng>> { val client = OkHttpClient() val request = Request.Builder().url(url).build() val response = client.newCall(request).execute() val data = response.body!!.string() val result = ArrayList<List<LatLng>>() try{ val respObj = Gson().fromJson(data,MapData::class.java) val path = ArrayList<LatLng>() for (i in 0 until respObj.routes[0].legs[0].steps.size){ path.addAll(decodePolyline(respObj.routes[0].legs[0].steps[i].polyline.points)) } result.add(path) }catch (e:Exception){ e.printStackTrace() } return result } override fun onPostExecute(result: List<List<LatLng>>) { val lineoption = PolylineOptions() for (i in result.indices){ lineoption.addAll(result[i]) lineoption.width(10f) lineoption.color(Color.GREEN) lineoption.geodesic(true) } mMap.addPolyline(lineoption) } } fun decodePolyline(encoded: String): List<LatLng> { val poly = ArrayList<LatLng>() var index = 0 val len = encoded.length var lat = 0 var lng = 0 while (index < len) { var b: Int var shift = 0 var result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlat = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lat += dlat shift = 0 result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlng = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lng += dlng val latLng = LatLng((lat.toDouble() / 1E5),(lng.toDouble() / 1E5)) poly.add(latLng) } return poly }} // MapData.kt class MapData { var routes = ArrayList<Routes>()} class Routes { var legs = ArrayList<Legs>()} class Legs { var distance = Distance() var duration = Duration() var end_address = "" var start_address = "" var end_location =Location() var start_location = Location() var steps = ArrayList<Steps>()} class Steps { var distance = Distance() var duration = Duration() var end_address = "" var start_address = "" var end_location =Location() var start_location = Location() var polyline = PolyLine() var travel_mode = "" var maneuver = ""} class Duration { var text = "" var value = 0} class Distance { var text = "" var value = 0} class PolyLine { var points = ""} class Location{ var lat ="" var lng =""} <?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <fragment android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment"/> <Button android:id="@+id/directions" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text = "Click" tools:ignore="MissingConstraints" /> </RelativeLayout> Output: Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Bundle in Android with Example Kotlin Setters and Getters
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 372, "s": 28, "text": "Google Map or any other such applications have methods to generate a route between two locations. Generally, there are a lot of parameters like closest distance, the fastest distance, alternative routes, etc to suffice the needs. These apps are really appealing, but the developer knows the pain behind developing such beautiful applications. " }, { "code": null, "e": 523, "s": 372, "text": "Through this article, we will show you how you can generate a route between two locations in a Google Map in Android. Follow the below steps to begin." }, { "code": null, "e": 570, "s": 523, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 809, "s": 570, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 818, "s": 809, "text": "Chapters" }, { "code": null, "e": 845, "s": 818, "text": "descriptions off, selected" }, { "code": null, "e": 895, "s": 845, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 918, "s": 895, "text": "captions off, selected" }, { "code": null, "e": 926, "s": 918, "text": "English" }, { "code": null, "e": 950, "s": 926, "text": "This is a modal window." }, { "code": null, "e": 1019, "s": 950, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1041, "s": 1019, "text": "End of dialog window." }, { "code": null, "e": 1093, "s": 1041, "text": "Step 2: Add these dependencies and sync the project" }, { "code": null, "e": 1113, "s": 1093, "text": "// For Map fragment" }, { "code": null, "e": 1179, "s": 1113, "text": "implementation ‘com.google.android.libraries.places:places:2.4.0’" }, { "code": null, "e": 1248, "s": 1179, "text": "// To make a call to for getting Coordinates response from a Web URL" }, { "code": null, "e": 1299, "s": 1248, "text": "implementation ‘com.squareup.okhttp3:okhttp:4.9.0’" }, { "code": null, "e": 1355, "s": 1299, "text": "Step 3: Add this permission in AndroidManifest.xml file" }, { "code": null, "e": 1371, "s": 1355, "text": "<manifest.....>" }, { "code": null, "e": 1442, "s": 1371, "text": " <uses-permission android:name=”android.permission.INTERNET” />" }, { "code": null, "e": 1466, "s": 1442, "text": " <application.......>" }, { "code": null, "e": 1493, "s": 1466, "text": " </application.......>" }, { "code": null, "e": 1511, "s": 1493, "text": " </manifest.....>" }, { "code": null, "e": 1578, "s": 1511, "text": "Step 4: Add this Google Map fragment in the activity_main.xml file" }, { "code": null, "e": 1582, "s": 1578, "text": "XML" }, { "code": "<!--Give it an ID as we will call this in the Main code--><fragment android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/map\" tools:context=\".MapsActivity\" android:name=\"com.google.android.gms.maps.SupportMapFragment\"/>", "e": 1844, "s": 1582, "text": null }, { "code": null, "e": 1886, "s": 1844, "text": "Step 5: Get and store your Places API Key" }, { "code": null, "e": 2175, "s": 1886, "text": "Our application utilizes Google’s Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs.Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?" }, { "code": null, "e": 2353, "s": 2175, "text": "Our application utilizes Google’s Places API, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs." }, { "code": null, "e": 2465, "s": 2353, "text": "Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?" }, { "code": null, "e": 2518, "s": 2465, "text": "Step 6: Retrieve & validate your key in MainActivity" }, { "code": null, "e": 2667, "s": 2518, "text": "After referring to the above two articles, you will have your API key called in the Main. To validate the key for using Map Fragment, add this code." }, { "code": null, "e": 2674, "s": 2667, "text": "Kotlin" }, { "code": "if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) }", "e": 2771, "s": 2674, "text": null }, { "code": null, "e": 2807, "s": 2771, "text": "Step 7: Initialize the Map Fragment" }, { "code": null, "e": 3067, "s": 2807, "text": "After appending the below code, the IDE will want to extend the MainActivity to OnMapReadyCallback. Apply these changes. You will also need to implement the member functions now. The member function will be onMapReady. Once done, the code will have no errors." }, { "code": null, "e": 3074, "s": 3067, "text": "Kotlin" }, { "code": "val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragmentmapFragment.getMapAsync(this)", "e": 3193, "s": 3074, "text": null }, { "code": null, "e": 3235, "s": 3193, "text": "Step 8: Get the coordinates of two places" }, { "code": null, "e": 3438, "s": 3235, "text": "We have manually declared the latitude and longitude values of two places, between whom we wish to generate a route. We declared them globally. But you can use your own methods to get those coordinates." }, { "code": null, "e": 3445, "s": 3438, "text": "Kotlin" }, { "code": "// GeeksforGeeks coordinatesprivate var originLatitude: Double = 28.5021359private var originLongitude: Double = 77.4054901 // Coordinates of a park nearbyprivate var destinationLatitude: Double = 28.5151087private var destinationLongitude: Double = 77.3932163", "e": 3707, "s": 3445, "text": null }, { "code": null, "e": 3744, "s": 3707, "text": "Step 9: Edit the onMapReady function" }, { "code": null, "e": 3793, "s": 3744, "text": "mMap is already declared in the global variable." }, { "code": null, "e": 3800, "s": 3793, "text": "Kotlin" }, { "code": "private lateinit var mMap: GoogleMap", "e": 3837, "s": 3800, "text": null }, { "code": null, "e": 3878, "s": 3837, "text": "Now we shall change the onMapReady call." }, { "code": null, "e": 3885, "s": 3878, "text": "Kotlin" }, { "code": "override fun onMapReady(p0: GoogleMap?) { mMap = p0!! val originLocation = LatLng(originLatitude, originLongitude) mMap.clear() mMap.addMarker(MarkerOptions().position(originLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 18F)) }", "e": 4185, "s": 3885, "text": null }, { "code": null, "e": 4242, "s": 4185, "text": "Step 10: Create a function to generate the direction URL" }, { "code": null, "e": 4249, "s": 4242, "text": "Kotlin" }, { "code": "private fun getDirectionURL(origin:LatLng, dest:LatLng, secret: String) : String{ return \"https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}\" + \"&destination=${dest.latitude},${dest.longitude}\" + \"&sensor=false\" + \"&mode=driving\" + \"&key=$secret\" }", "e": 4610, "s": 4249, "text": null }, { "code": null, "e": 4656, "s": 4610, "text": "Step 11: Create a function to decode polyline" }, { "code": null, "e": 4663, "s": 4656, "text": "Kotlin" }, { "code": "fun decodePolyline(encoded: String): List<LatLng> { val poly = ArrayList<LatLng>() var index = 0 val len = encoded.length var lat = 0 var lng = 0 while (index < len) { var b: Int var shift = 0 var result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlat = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lat += dlat shift = 0 result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlng = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lng += dlng val latLng = LatLng((lat.toDouble() / 1E5),(lng.toDouble() / 1E5)) poly.add(latLng) } return poly }", "e": 5694, "s": 4663, "text": null }, { "code": null, "e": 5737, "s": 5694, "text": "Step 12: Create a class for Map Parameters" }, { "code": null, "e": 5854, "s": 5737, "text": "The response when Step 10 is passed requires an instance of the object to catch the JSON. This class is that object." }, { "code": null, "e": 5861, "s": 5854, "text": "Kotlin" }, { "code": "class MapData { var routes = ArrayList<Routes>()} class Routes { var legs = ArrayList<Legs>()} class Legs { var distance = Distance() var duration = Duration() var end_address = \"\" var start_address = \"\" var end_location =Location() var start_location = Location() var steps = ArrayList<Steps>()} class Steps { var distance = Distance() var duration = Duration() var end_address = \"\" var start_address = \"\" var end_location =Location() var start_location = Location() var polyline = PolyLine() var travel_mode = \"\" var maneuver = \"\"} class Duration { var text = \"\" var value = 0} class Distance { var text = \"\" var value = 0} class PolyLine { var points = \"\"} class Location{ var lat =\"\" var lng =\"\"}", "e": 6644, "s": 5861, "text": null }, { "code": null, "e": 6756, "s": 6644, "text": "Step 13: Create an inner class to pass the URL string generated in Step 8 and call the decode polyline function" }, { "code": null, "e": 6763, "s": 6756, "text": "Kotlin" }, { "code": "@SuppressLint(\"StaticFieldLeak\") private inner class GetDirection(val url : String) : AsyncTask<Void, Void, List<List<LatLng>>>(){ override fun doInBackground(vararg params: Void?): List<List<LatLng>> { val client = OkHttpClient() val request = Request.Builder().url(url).build() val response = client.newCall(request).execute() val data = response.body!!.string() val result = ArrayList<List<LatLng>>() try{ val respObj = Gson().fromJson(data,MapData::class.java) val path = ArrayList<LatLng>() for (i in 0 until respObj.routes[0].legs[0].steps.size){ path.addAll(decodePolyline(respObj.routes[0].legs[0].steps[i].polyline.points)) } result.add(path) }catch (e:Exception){ e.printStackTrace() } return result } override fun onPostExecute(result: List<List<LatLng>>) { val lineoption = PolylineOptions() for (i in result.indices){ lineoption.addAll(result[i]) lineoption.width(10f) lineoption.color(Color.GREEN) lineoption.geodesic(true) } mMap.addPolyline(lineoption) }}", "e": 8094, "s": 6763, "text": null }, { "code": null, "e": 8130, "s": 8094, "text": "Download the Source Code from here." }, { "code": null, "e": 8137, "s": 8130, "text": "Kotlin" }, { "code": null, "e": 8144, "s": 8137, "text": "Kotlin" }, { "code": null, "e": 8148, "s": 8144, "text": "XML" }, { "code": "// MainActivity.kt import android.annotation.SuppressLintimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.graphics.Colorimport android.os.AsyncTaskimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.MarkerOptionsimport com.google.android.gms.maps.model.PolylineOptionsimport com.google.android.libraries.places.api.Placesimport com.google.gson.Gsonimport okhttp3.OkHttpClientimport okhttp3.Request class MainActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private var originLatitude: Double = 28.5021359 private var originLongitude: Double = 77.4054901 private var destinationLatitude: Double = 28.5151087 private var destinationLongitude: Double = 77.3932163 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData[\"com.google.android.geo.API_KEY\"] val apiKey = value.toString() // Initializing the Places API with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Map Fragment val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) val gd = findViewById<Button>(R.id.directions) gd.setOnClickListener{ mapFragment.getMapAsync { mMap = it val originLocation = LatLng(originLatitude, originLongitude) mMap.addMarker(MarkerOptions().position(originLocation)) val destinationLocation = LatLng(destinationLatitude, destinationLongitude) mMap.addMarker(MarkerOptions().position(destinationLocation)) val urll = getDirectionURL(originLocation, destinationLocation, apiKey) GetDirection(urll).execute() mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 14F)) } } } override fun onMapReady(p0: GoogleMap?) { mMap = p0!! val originLocation = LatLng(originLatitude, originLongitude) mMap.clear() mMap.addMarker(MarkerOptions().position(originLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(originLocation, 18F)) } private fun getDirectionURL(origin:LatLng, dest:LatLng, secret: String) : String{ return \"https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}\" + \"&destination=${dest.latitude},${dest.longitude}\" + \"&sensor=false\" + \"&mode=driving\" + \"&key=$secret\" } @SuppressLint(\"StaticFieldLeak\") private inner class GetDirection(val url : String) : AsyncTask<Void, Void, List<List<LatLng>>>(){ override fun doInBackground(vararg params: Void?): List<List<LatLng>> { val client = OkHttpClient() val request = Request.Builder().url(url).build() val response = client.newCall(request).execute() val data = response.body!!.string() val result = ArrayList<List<LatLng>>() try{ val respObj = Gson().fromJson(data,MapData::class.java) val path = ArrayList<LatLng>() for (i in 0 until respObj.routes[0].legs[0].steps.size){ path.addAll(decodePolyline(respObj.routes[0].legs[0].steps[i].polyline.points)) } result.add(path) }catch (e:Exception){ e.printStackTrace() } return result } override fun onPostExecute(result: List<List<LatLng>>) { val lineoption = PolylineOptions() for (i in result.indices){ lineoption.addAll(result[i]) lineoption.width(10f) lineoption.color(Color.GREEN) lineoption.geodesic(true) } mMap.addPolyline(lineoption) } } fun decodePolyline(encoded: String): List<LatLng> { val poly = ArrayList<LatLng>() var index = 0 val len = encoded.length var lat = 0 var lng = 0 while (index < len) { var b: Int var shift = 0 var result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlat = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lat += dlat shift = 0 result = 0 do { b = encoded[index++].code - 63 result = result or (b and 0x1f shl shift) shift += 5 } while (b >= 0x20) val dlng = if (result and 1 != 0) (result shr 1).inv() else result shr 1 lng += dlng val latLng = LatLng((lat.toDouble() / 1E5),(lng.toDouble() / 1E5)) poly.add(latLng) } return poly }}", "e": 13814, "s": 8148, "text": null }, { "code": "// MapData.kt class MapData { var routes = ArrayList<Routes>()} class Routes { var legs = ArrayList<Legs>()} class Legs { var distance = Distance() var duration = Duration() var end_address = \"\" var start_address = \"\" var end_location =Location() var start_location = Location() var steps = ArrayList<Steps>()} class Steps { var distance = Distance() var duration = Duration() var end_address = \"\" var start_address = \"\" var end_location =Location() var start_location = Location() var polyline = PolyLine() var travel_mode = \"\" var maneuver = \"\"} class Duration { var text = \"\" var value = 0} class Distance { var text = \"\" var value = 0} class PolyLine { var points = \"\"} class Location{ var lat =\"\" var lng =\"\"}", "e": 14612, "s": 13814, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <fragment android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/map\" tools:context=\".MapsActivity\" android:name=\"com.google.android.gms.maps.SupportMapFragment\"/> <Button android:id=\"@+id/directions\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_alignParentBottom=\"true\" android:text = \"Click\" tools:ignore=\"MissingConstraints\" /> </RelativeLayout>", "e": 15508, "s": 14612, "text": null }, { "code": null, "e": 15516, "s": 15508, "text": "Output:" }, { "code": null, "e": 15524, "s": 15516, "text": "Android" }, { "code": null, "e": 15531, "s": 15524, "text": "Kotlin" }, { "code": null, "e": 15539, "s": 15531, "text": "Android" }, { "code": null, "e": 15637, "s": 15539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15706, "s": 15637, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 15738, "s": 15706, "text": "Android SDK and it's Components" }, { "code": null, "e": 15777, "s": 15738, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 15826, "s": 15777, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 15868, "s": 15826, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 15887, "s": 15868, "text": "Android UI Layouts" }, { "code": null, "e": 15900, "s": 15887, "text": "Kotlin Array" }, { "code": null, "e": 15942, "s": 15900, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 15973, "s": 15942, "text": "Bundle in Android with Example" } ]
Number of non-negative integral solutions of sum equation
31 Dec, 2021 Given a number n (number of variables) and val (sum of the variables), find out how many such non-negative integral solutions are possible. Examples : Input : n = 5, val = 1 Output : 5 Explanation: x1 + x2 + x3 + x4 + x5 = 1 Number of possible solution are : (0 0 0 0 1), (0 0 0 1 0), (0 0 1 0 0), (0 1 0 0 0), (1 0 0 0 0) Total number of possible solutions are 5 Input : n = 5, val = 4 Output : 70 Explanation: x1 + x2 + x3 + x4 + x5 = 4 Number of possible solution are: (1 1 1 1 0), (1 0 1 1 1), (0 1 1 1 1), (2 1 0 0 1), (2 2 0 0 0)........ so on...... Total numbers of possible solutions are 70 Asked in: Microsoft Interview 1. Make a recursive function call to countSolutions(int n, int val) 2. Call this Solution function countSolutions(n-1, val-i) until n = 1 and val >=0 and then return 1. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to find the numbers// of non negative integral solutions#include<iostream>using namespace std; // return number of non negative// integral solutionsint countSolutions(int n, int val){ // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // return the total no possible solution return total;} // driver codeint main(){ int n = 5; int val = 20; cout<<countSolutions(n, val);} //This code is contributed by Smitha Dinesh Semwal // Java program to find the numbers// of non negative integral solutionsclass GFG { // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code public static void main(String[] args) { int n = 5; int val = 20; System.out.print(countSolutions(n, val)); }} // This code is contributed by Anant Agarwal. # Python3 program to find the numbers# of non negative integral solutions # return number of non negative# integral solutionsdef countSolutions(n, val): # initialize total = 0 total = 0 # Base Case if n = 1 and val >= 0 # then it should return 1 if n == 1 and val >=0: return 1 # iterate the loop till equal the val for i in range(val+1): # total solution of equations # and again call the recursive # function Solutions(variable,value) total += countSolutions(n-1, val-i) # return the total no possible solution return total # driver coden = 5val = 20print(countSolutions(n, val)) // C# program to find the numbers// of non negative integral solutionsusing System; class GFG { // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code public static void Main() { int n = 5; int val = 20; Console.WriteLine(countSolutions(n, val)); }} // This code is contributed by Anant vt_m. <?php// PHP program to find the numbers// of non negative integral solutions // return number of non negative// integral solutionsfunction countSolutions($n, $val){ // initialize total = 0 $total = 0; // Base Case if n = 1 and // val >= 0 then it should // return 1 if ($n == 1 && $val >=0) return 1; // iterate the loop // till equal the val for ($i = 0; $i <= $val; $i++) { // total solution of equations // and again call the recursive // function Solutions(variable,value) $total += countSolutions($n - 1, $val - $i); } // return the total // no possible solution return $total;} // Driver Code$n = 5;$val = 20; echo countSolutions($n, $val); // This code is contributed by nitin mittal.?> <script> // JavaScript program to find the numbers// of non negative integral solutions // return number of non negative // integral solutions function countSolutions(n, val) { // initialize total = 0 let total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (let i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code let n = 5; let val = 20; document.write(countSolutions(n, val)); </script> Output : 10626 Dynamic Programming Approach: (Using Memoization) C++ Java Python3 C# Javascript // CPP program to find the numbers// of non negative integral solutions#include<bits/stdc++.h>using namespace std; int dp[1001][1001]; // return number of non negative// integral solutionsint countSolutions(int n, int val){ // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n][val] != -1) { return dp[n][val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n][val] = total; // Return dp return dp[n][val];} // driver codeint main(){ int n = 5; int val = 20; memset(dp, -1, sizeof(dp)); cout << countSolutions(n, val);} // Java program to find the numbers// of non negative integral solutionsimport java.util.*;public class GFG{ static int dp[][] = new int[1001][1001]; // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n][val] != -1) { return dp[n][val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n][val] = total; // Return dp return dp[n][val]; } // driver code public static void main(String args[]){ int n = 5; int val = 20; for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i][j]=-1; } } System.out.println(countSolutions(n, val)); }} // This code is contributed by Samim Hossain Mondal. # Python3 program to find the numbers# of non negative integral solutions # Taking the matrix as globallydp = [[-1 for i in range(1001)] for j in range(1001)] # Return number of non negative# integral solutionsdef countSolutions(n, val): # Initialize total = 0 total = 0 # Base Case if n = 1 and val >= 0 # then it should return 1 if n == 1 and val >= 0: return 1 # If a value is already present # in dp if (dp[n][val] != -1): return dp[n][val] # Iterate the loop till equal the val for i in range(val + 1): # total solution of equations # and again call the recursive # function Solutions(variable,value) total += countSolutions(n - 1, val - i) # Return the total no possible solution dp[n][val] = total return dp[n][val] # Driver coden = 5val = 20 print(countSolutions(n, val)) # This code is contributed by Samim Hossain Mondal. // C# program to find the numbers// of non negative integral solutionsusing System;class GFG{ static int [,]dp = new int[1001, 1001]; // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n, val] != -1) { return dp[n, val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n, val] = total; // Return dp return dp[n, val]; } // driver code public static void Main(){ int n = 5; int val = 20; for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i, j] = -1; } } Console.Write(countSolutions(n, val)); }} // This code is contributed by Samim Hossain Mondal. <script>// JavaScript program to find the numbers// of non negative integral solutions var dp = new Array(1001); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(1001); } // return number of non negative // integral solutions function countSolutions(n, val) { // initialize total = 0 let total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // if a value is already // present in dp if(dp[n][val] != -1) return dp[n][val]; // iterate the loop till equal the val for (let i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return dp[n][val] = total; } // Driver codelet n = 5;let val = 20; for(let i = 0; i < 1001; i++) { for(let j = 0; j < 1001; j++) { dp[i][j] = -1; }}document.write(countSolutions(n, val)); // This code is contributed by Samim Hossain Mondal. </script> 10626 Time Complexity: O(n * val) Auxiliary Space: O(n * val) nitin mittal Akanksha_Rai souravghosh0416 samim2000 Microsoft Mathematical Recursion Technical Scripter Microsoft Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Minimum number of jumps to reach end Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Print all subsequences of a string
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Dec, 2021" }, { "code": null, "e": 195, "s": 54, "text": "Given a number n (number of variables) and val (sum of the variables), find out how many such non-negative integral solutions are possible. " }, { "code": null, "e": 207, "s": 195, "text": "Examples : " }, { "code": null, "e": 659, "s": 207, "text": "Input : n = 5, val = 1\nOutput : 5\nExplanation:\nx1 + x2 + x3 + x4 + x5 = 1\nNumber of possible solution are : \n(0 0 0 0 1), (0 0 0 1 0), (0 0 1 0 0),\n(0 1 0 0 0), (1 0 0 0 0)\nTotal number of possible solutions are 5\n\nInput : n = 5, val = 4\nOutput : 70\nExplanation:\nx1 + x2 + x3 + x4 + x5 = 4\nNumber of possible solution are: \n(1 1 1 1 0), (1 0 1 1 1), (0 1 1 1 1), \n(2 1 0 0 1), (2 2 0 0 0)........ so on......\nTotal numbers of possible solutions are 70" }, { "code": null, "e": 690, "s": 659, "text": "Asked in: Microsoft Interview " }, { "code": null, "e": 859, "s": 690, "text": "1. Make a recursive function call to countSolutions(int n, int val) 2. Call this Solution function countSolutions(n-1, val-i) until n = 1 and val >=0 and then return 1." }, { "code": null, "e": 906, "s": 859, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 910, "s": 906, "text": "C++" }, { "code": null, "e": 915, "s": 910, "text": "Java" }, { "code": null, "e": 923, "s": 915, "text": "Python3" }, { "code": null, "e": 926, "s": 923, "text": "C#" }, { "code": null, "e": 930, "s": 926, "text": "PHP" }, { "code": null, "e": 941, "s": 930, "text": "Javascript" }, { "code": "// CPP program to find the numbers// of non negative integral solutions#include<iostream>using namespace std; // return number of non negative// integral solutionsint countSolutions(int n, int val){ // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // return the total no possible solution return total;} // driver codeint main(){ int n = 5; int val = 20; cout<<countSolutions(n, val);} //This code is contributed by Smitha Dinesh Semwal", "e": 1783, "s": 941, "text": null }, { "code": "// Java program to find the numbers// of non negative integral solutionsclass GFG { // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code public static void main(String[] args) { int n = 5; int val = 20; System.out.print(countSolutions(n, val)); }} // This code is contributed by Anant Agarwal.", "e": 2626, "s": 1783, "text": null }, { "code": "# Python3 program to find the numbers# of non negative integral solutions # return number of non negative# integral solutionsdef countSolutions(n, val): # initialize total = 0 total = 0 # Base Case if n = 1 and val >= 0 # then it should return 1 if n == 1 and val >=0: return 1 # iterate the loop till equal the val for i in range(val+1): # total solution of equations # and again call the recursive # function Solutions(variable,value) total += countSolutions(n-1, val-i) # return the total no possible solution return total # driver coden = 5val = 20print(countSolutions(n, val))", "e": 3279, "s": 2626, "text": null }, { "code": "// C# program to find the numbers// of non negative integral solutionsusing System; class GFG { // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (int i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code public static void Main() { int n = 5; int val = 20; Console.WriteLine(countSolutions(n, val)); }} // This code is contributed by Anant vt_m.", "e": 4246, "s": 3279, "text": null }, { "code": "<?php// PHP program to find the numbers// of non negative integral solutions // return number of non negative// integral solutionsfunction countSolutions($n, $val){ // initialize total = 0 $total = 0; // Base Case if n = 1 and // val >= 0 then it should // return 1 if ($n == 1 && $val >=0) return 1; // iterate the loop // till equal the val for ($i = 0; $i <= $val; $i++) { // total solution of equations // and again call the recursive // function Solutions(variable,value) $total += countSolutions($n - 1, $val - $i); } // return the total // no possible solution return $total;} // Driver Code$n = 5;$val = 20; echo countSolutions($n, $val); // This code is contributed by nitin mittal.?>", "e": 5074, "s": 4246, "text": null }, { "code": "<script> // JavaScript program to find the numbers// of non negative integral solutions // return number of non negative // integral solutions function countSolutions(n, val) { // initialize total = 0 let total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // iterate the loop till equal the val for (let i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return total; } // Driver code let n = 5; let val = 20; document.write(countSolutions(n, val)); </script>", "e": 5862, "s": 5074, "text": null }, { "code": null, "e": 5872, "s": 5862, "text": "Output : " }, { "code": null, "e": 5878, "s": 5872, "text": "10626" }, { "code": null, "e": 5908, "s": 5878, "text": "Dynamic Programming Approach:" }, { "code": null, "e": 5928, "s": 5908, "text": "(Using Memoization)" }, { "code": null, "e": 5932, "s": 5928, "text": "C++" }, { "code": null, "e": 5937, "s": 5932, "text": "Java" }, { "code": null, "e": 5945, "s": 5937, "text": "Python3" }, { "code": null, "e": 5948, "s": 5945, "text": "C#" }, { "code": null, "e": 5959, "s": 5948, "text": "Javascript" }, { "code": "// CPP program to find the numbers// of non negative integral solutions#include<bits/stdc++.h>using namespace std; int dp[1001][1001]; // return number of non negative// integral solutionsint countSolutions(int n, int val){ // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n][val] != -1) { return dp[n][val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n][val] = total; // Return dp return dp[n][val];} // driver codeint main(){ int n = 5; int val = 20; memset(dp, -1, sizeof(dp)); cout << countSolutions(n, val);}", "e": 6973, "s": 5959, "text": null }, { "code": "// Java program to find the numbers// of non negative integral solutionsimport java.util.*;public class GFG{ static int dp[][] = new int[1001][1001]; // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n][val] != -1) { return dp[n][val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n][val] = total; // Return dp return dp[n][val]; } // driver code public static void main(String args[]){ int n = 5; int val = 20; for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i][j]=-1; } } System.out.println(countSolutions(n, val)); }} // This code is contributed by Samim Hossain Mondal.", "e": 8139, "s": 6973, "text": null }, { "code": "# Python3 program to find the numbers# of non negative integral solutions # Taking the matrix as globallydp = [[-1 for i in range(1001)] for j in range(1001)] # Return number of non negative# integral solutionsdef countSolutions(n, val): # Initialize total = 0 total = 0 # Base Case if n = 1 and val >= 0 # then it should return 1 if n == 1 and val >= 0: return 1 # If a value is already present # in dp if (dp[n][val] != -1): return dp[n][val] # Iterate the loop till equal the val for i in range(val + 1): # total solution of equations # and again call the recursive # function Solutions(variable,value) total += countSolutions(n - 1, val - i) # Return the total no possible solution dp[n][val] = total return dp[n][val] # Driver coden = 5val = 20 print(countSolutions(n, val)) # This code is contributed by Samim Hossain Mondal.", "e": 9079, "s": 8139, "text": null }, { "code": "// C# program to find the numbers// of non negative integral solutionsusing System;class GFG{ static int [,]dp = new int[1001, 1001]; // return number of non negative // integral solutions static int countSolutions(int n, int val) { // initialize total = 0 int total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >=0) { return 1; } // If a value already present in dp, // return it if(dp[n, val] != -1) { return dp[n, val]; } // iterate the loop till equal the val for (int i = 0; i <= val; i++){ // total solution of equations // and again call the recursive // function Solutions(variable,value) total += countSolutions(n-1, val-i); } // Store the value in dp dp[n, val] = total; // Return dp return dp[n, val]; } // driver code public static void Main(){ int n = 5; int val = 20; for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i, j] = -1; } } Console.Write(countSolutions(n, val)); }} // This code is contributed by Samim Hossain Mondal.", "e": 10213, "s": 9079, "text": null }, { "code": "<script>// JavaScript program to find the numbers// of non negative integral solutions var dp = new Array(1001); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(1001); } // return number of non negative // integral solutions function countSolutions(n, val) { // initialize total = 0 let total = 0; // Base Case if n = 1 and val >= 0 // then it should return 1 if (n == 1 && val >= 0) return 1; // if a value is already // present in dp if(dp[n][val] != -1) return dp[n][val]; // iterate the loop till equal the val for (let i = 0; i <= val; i++) { // total solution of equations // and again call the recursive // function Solutions(variable, value) total += countSolutions(n - 1, val - i); } // return the total no possible solution return dp[n][val] = total; } // Driver codelet n = 5;let val = 20; for(let i = 0; i < 1001; i++) { for(let j = 0; j < 1001; j++) { dp[i][j] = -1; }}document.write(countSolutions(n, val)); // This code is contributed by Samim Hossain Mondal. </script>", "e": 11374, "s": 10213, "text": null }, { "code": null, "e": 11380, "s": 11374, "text": "10626" }, { "code": null, "e": 11408, "s": 11380, "text": "Time Complexity: O(n * val)" }, { "code": null, "e": 11436, "s": 11408, "text": "Auxiliary Space: O(n * val)" }, { "code": null, "e": 11449, "s": 11436, "text": "nitin mittal" }, { "code": null, "e": 11462, "s": 11449, "text": "Akanksha_Rai" }, { "code": null, "e": 11478, "s": 11462, "text": "souravghosh0416" }, { "code": null, "e": 11488, "s": 11478, "text": "samim2000" }, { "code": null, "e": 11498, "s": 11488, "text": "Microsoft" }, { "code": null, "e": 11511, "s": 11498, "text": "Mathematical" }, { "code": null, "e": 11521, "s": 11511, "text": "Recursion" }, { "code": null, "e": 11540, "s": 11521, "text": "Technical Scripter" }, { "code": null, "e": 11550, "s": 11540, "text": "Microsoft" }, { "code": null, "e": 11563, "s": 11550, "text": "Mathematical" }, { "code": null, "e": 11573, "s": 11563, "text": "Recursion" }, { "code": null, "e": 11671, "s": 11573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11695, "s": 11671, "text": "Merge two sorted arrays" }, { "code": null, "e": 11716, "s": 11695, "text": "Operators in C / C++" }, { "code": null, "e": 11738, "s": 11716, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 11752, "s": 11738, "text": "Prime Numbers" }, { "code": null, "e": 11789, "s": 11752, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 11874, "s": 11789, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 11884, "s": 11874, "text": "Recursion" }, { "code": null, "e": 11911, "s": 11884, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 11939, "s": 11911, "text": "Backtracking | Introduction" } ]
Window Sliding Technique
06 Jul, 2022 Window Sliding Technique is a computational technique which aims to reduce the use of nested loop and replace it with a single loop, thereby reducing the time complexity. What is Sliding Window? Consider a long chain connected together. Suppose you want to apply oil in the complete chain with your hands, without pouring the oil from above. One way to do so is to: pick some oil, apply onto a section of chain, then again pick some oil then apply it to the next section where oil is not applied yet and so on till the complete chain is oiled. Another way to do so, is to use a cloth, dip it in oil, and then hold onto one end of the chain with this cloth. Then instead of re-dipping it again and again, just slide the cloth with hand onto the next section, and next, and so on till the other end. The second way is known as the Sliding window technique and the portion which is slided from one end to end, is known as Sliding Window. Sliding window technique Prerequisite to use Sliding window technique The use of Sliding Window technique can be done in a very specific scenario, where the size of window for computation is fixed throughout the complete nested loop. Only then the time complexity can be reduced. How to use Sliding Window Technique? The general use of Sliding window technique can be demonstrated as following: Find the size of window required Compute the result for 1st window, i.e. from start of data structureThen use a loop to slide the window by 1, and keep computing the result window by window. Find the size of window required Compute the result for 1st window, i.e. from start of data structure Then use a loop to slide the window by 1, and keep computing the result window by window. Examples to illustrate the use of Sliding window technique Example: Given an array of integers of size ‘n’, Our aim is to calculate the maximum sum of ‘k’ consecutive elements in the array. Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Input : arr[] = {2, 3}, k = 3Output : InvalidThere is no subarray of size 3 as size of whole array is 2. Naive Approach: So, let’s analyze the problem with Brute Force Approach. We start with first index and sum till k-th element. We do it for all possible consecutive blocks or groups of k elements. This method requires nested for loop, the outer for loop starts with the starting element of the block of k elements and the inner or the nested loop will add up till the k-th element. Consider the below implementation : C++ C Java Python3 C# PHP Javascript // O(n*k) solution for finding maximum sum of// a subarray of size k#include <bits/stdc++.h>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // Initialize result int max_sum = INT_MIN; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = max(current_sum, max_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // O(n*k) solution for finding maximum sum of// a subarray of size k#include <limits.h>#include <math.h>#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // Initialize result int max_sum = INT_MIN; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = max(current_sum, max_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", maxSum(arr, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java code O(n*k) solution for finding maximum sum of// a subarray of size kclass GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int arr[], int n, int k) { // Initialize result int max_sum = Integer.MIN_VALUE; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.max(current_sum, max_sum); } return max_sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129) # codeimport sys # O(n * k) solution for finding# maximum sum of a subarray of size kINT_MIN = -sys.maxsize - 1 # Returns maximum sum in a# subarray of size k. def maxSum(arr, n, k): # Initialize result max_sum = INT_MIN # Consider all blocks # starting with i. for i in range(n - k + 1): current_sum = 0 for j in range(k): current_sum = current_sum + arr[i + j] # Update result if required. max_sum = max(current_sum, max_sum) return max_sum # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4n = len(arr)print(maxSum(arr, n, k)) # This code is contributed by mits // C# code here O(n*k) solution for// finding maximum sum of a subarray// of size kusing System; class GFG { // Returns maximum sum in a // subarray of size k. static int maxSum(int[] arr, int n, int k) { // Initialize result int max_sum = int.MinValue; // Consider all blocks starting // with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.Max(current_sum, max_sum); } return max_sum; } // Driver code public static void Main() { int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.Length; Console.WriteLine(maxSum(arr, n, k)); }} // This code is contributed by anuj_67. <?php // code?><?php// O(n*k) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a subarray of size k.function maxSum($arr, $n, $k){ // Initialize result $max_sum = PHP_INT_MIN ; // Consider all blocks // starting with i. for ( $i = 0; $i < $n - $k + 1; $i++) { $current_sum = 0; for ( $j = 0; $j < $k; $j++) $current_sum = $current_sum + $arr[$i + $j]; // Update result if required. $max_sum = max($current_sum, $max_sum ); } return $max_sum;} // Driver code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = count($arr); echo maxSum($arr, $n, $k); // This code is contributed by anuj_67.?> <script> // O(n*k) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a subarray of size k.function maxSum( arr, n, k){ // Initialize result let max_sum = Number.MIN_VALUE; // Consider all blocks starting with i. for (let i = 0; i < n - k + 1; i++) { let current_sum = 0; for (let j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.max(current_sum, max_sum); } return max_sum;} // Driver codelet arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];let k = 4;let n = arr.length;document.write(maxSum(arr, n, k)); </script> 24 It can be observed from the above code that the time complexity is O(k*n) as it contains two nested loops. Sliding Window Technique: The technique can be best understood with the window pane in bus, consider a window of length n and the pane which is fixed in it of length k. Consider, initially the pane is at extreme left i.e., at 0 units from the left. Now, co-relate the window with array arr[] of size n and pane with current_sum of size k elements. Now, if we apply force on the window such that it moves a unit distance ahead. The pane will cover next k consecutive elements. Applying sliding window technique : We compute the sum of first k elements out of n terms using a linear loop and store the sum in variable window_sum.Then we will graze linearly over the array till it reaches the end and simultaneously keep track of maximum sum.To get the current sum of block of k elements just subtract the first element from the previous block and add the last element of the current block . We compute the sum of first k elements out of n terms using a linear loop and store the sum in variable window_sum. Then we will graze linearly over the array till it reaches the end and simultaneously keep track of maximum sum. To get the current sum of block of k elements just subtract the first element from the previous block and add the last element of the current block . The below representation will make it clear how the window slides over the array. Consider an array arr[] = {5, 2, -1, 0, 3} and value of k = 3 and n = 5 This is the initial phase where we have calculated the initial window sum starting from index 0 . At this stage the window sum is 6. Now, we set the maximum_sum as current_window i.e 6. Now, we slide our window by a unit index. Therefore, now it discards 5 from the window and adds 0 to the window. Hence, we will get our new window sum by subtracting 5 and then adding 0 to it. So, our window sum now becomes 1. Now, we will compare this window sum with the maximum_sum. As it is smaller we wont the change the maximum_sum. Similarly, now once again we slide our window by a unit index and obtain the new window sum to be 2. Again we check if this current window sum is greater than the maximum_sum till now. Once, again it is smaller so we don’t change the maximum_sum.Therefore, for the above array our maximum_sum is 6. Below is the code for above approach: C++ Java Python3 C# PHP Javascript // O(n) solution for finding maximum sum of// a subarray of size k#include <iostream>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // n must be greater if (n < k) { cout << "Invalid"; return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = max(max_sum, window_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;} // Java code for// O(n) solution for finding// maximum sum of a subarray// of size kclass GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int arr[], int n, int k) { // n must be greater if (n < k) { System.out.println("Invalid"); return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = Math.max(max_sum, window_sum); } return max_sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }} // This code is contributed// by prerna saini. # O(n) solution for finding# maximum sum of a subarray of size k def maxSum(arr, k): # length of the array n = len(arr) # n must be greater than k if n < k: print("Invalid") return -1 # Compute sum of first window of size k window_sum = sum(arr[:k]) # first sum available max_sum = window_sum # Compute the sums of remaining windows by # removing first element of previous # window and adding last element of # the current window. for i in range(n - k): window_sum = window_sum - arr[i] + arr[i + k] max_sum = max(window_sum, max_sum) return max_sum # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4print(maxSum(arr, k)) # This code is contributed by Kyle McClay // C# code for O(n) solution for finding// maximum sum of a subarray of size kusing System; class GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int[] arr, int n, int k) { // n must be greater if (n < k) { Console.WriteLine("Invalid"); return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = Math.Max(max_sum, window_sum); } return max_sum; } // Driver code public static void Main() { int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.Length; Console.WriteLine(maxSum(arr, n, k)); }} // This code is contributed by anuj_67. <?php// O(n) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a // subarray of size k.function maxSum( $arr, $n, $k){ // n must be greater if ($n < $k) { echo "Invalid"; return -1; } // Compute sum of first // window of size k $max_sum = 0; for($i = 0; $i < $k; $i++) $max_sum += $arr[$i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. $window_sum = $max_sum; for ($i = $k; $i < $n; $i++) { $window_sum += $arr[$i] - $arr[$i - $k]; $max_sum = max($max_sum, $window_sum); } return $max_sum;} // Driver code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = count($arr); echo maxSum($arr, $n, $k); // This code is contributed by anuj_67?> <script> // Javascript code for // O(n) solution for finding // maximum sum of a subarray // of size k function maxSum(arr, n, k) { let max = 0; let sum = 0; // find initial sum of first k elements for (let i = 0; i < k; i++) { sum += arr[i]; max = sum; } // iterate the array once // and increment the right edge for (let i = k; i < n; i++) { sum += arr[i] - arr[i - k]; // compare if sum is more than max, // if yes then replace // max with new sum value if (sum > max) { max = sum; } } return max; } // Driver codelet arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];let k = 4;let n = arr.length;document.write(maxSum(arr, n, k)); </script> 24 Now, it is quite obvious that the Time Complexity is linear as we can see that only one loop runs in our code. Hence, our Time Complexity is O(n). We can use this technique to find max/min k-subarray, XOR, product, sum, etc. Refer sliding window problems for such problems. Sliding Window Technique | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSliding Window Technique | GeeksforGeeksWatch laterShareCopy link95/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9-3BXsfrpbY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Recent Articles on Window Sliding Technique Practice Questions on Window Sliding DSA Self Paced – The Most used and Trusted Course on DSA This article is contributed by Kanika Thakral. 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. vt_m AnnieAlford Mithun Kumar KyleMcClay Ekta Arora Parimal7 maartenjjacobs rohitsingh07052 GauravMaheshwari1 amartyaghoshgfg RishabhPrabhu krisania804 starcode01 sliding-window Arrays Technical Scripter sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Arrays in C/C++ Program for array rotation Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 223, "s": 52, "text": "Window Sliding Technique is a computational technique which aims to reduce the use of nested loop and replace it with a single loop, thereby reducing the time complexity." }, { "code": null, "e": 247, "s": 223, "text": "What is Sliding Window?" }, { "code": null, "e": 394, "s": 247, "text": "Consider a long chain connected together. Suppose you want to apply oil in the complete chain with your hands, without pouring the oil from above." }, { "code": null, "e": 419, "s": 394, "text": "One way to do so is to: " }, { "code": null, "e": 435, "s": 419, "text": "pick some oil, " }, { "code": null, "e": 467, "s": 435, "text": "apply onto a section of chain, " }, { "code": null, "e": 492, "s": 467, "text": "then again pick some oil" }, { "code": null, "e": 555, "s": 492, "text": "then apply it to the next section where oil is not applied yet" }, { "code": null, "e": 599, "s": 555, "text": "and so on till the complete chain is oiled." }, { "code": null, "e": 853, "s": 599, "text": "Another way to do so, is to use a cloth, dip it in oil, and then hold onto one end of the chain with this cloth. Then instead of re-dipping it again and again, just slide the cloth with hand onto the next section, and next, and so on till the other end." }, { "code": null, "e": 990, "s": 853, "text": "The second way is known as the Sliding window technique and the portion which is slided from one end to end, is known as Sliding Window." }, { "code": null, "e": 1015, "s": 990, "text": "Sliding window technique" }, { "code": null, "e": 1060, "s": 1015, "text": "Prerequisite to use Sliding window technique" }, { "code": null, "e": 1271, "s": 1060, "text": "The use of Sliding Window technique can be done in a very specific scenario, where the size of window for computation is fixed throughout the complete nested loop. Only then the time complexity can be reduced. " }, { "code": null, "e": 1308, "s": 1271, "text": "How to use Sliding Window Technique?" }, { "code": null, "e": 1386, "s": 1308, "text": "The general use of Sliding window technique can be demonstrated as following:" }, { "code": null, "e": 1577, "s": 1386, "text": "Find the size of window required Compute the result for 1st window, i.e. from start of data structureThen use a loop to slide the window by 1, and keep computing the result window by window." }, { "code": null, "e": 1611, "s": 1577, "text": "Find the size of window required " }, { "code": null, "e": 1680, "s": 1611, "text": "Compute the result for 1st window, i.e. from start of data structure" }, { "code": null, "e": 1770, "s": 1680, "text": "Then use a loop to slide the window by 1, and keep computing the result window by window." }, { "code": null, "e": 1829, "s": 1770, "text": "Examples to illustrate the use of Sliding window technique" }, { "code": null, "e": 1960, "s": 1829, "text": "Example: Given an array of integers of size ‘n’, Our aim is to calculate the maximum sum of ‘k’ consecutive elements in the array." }, { "code": null, "e": 2017, "s": 1960, "text": "Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700" }, { "code": null, "e": 2147, "s": 2017, "text": "Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39We get maximum sum by adding subarray {4, 2, 10, 23} of size 4." }, { "code": null, "e": 2253, "s": 2147, "text": "Input : arr[] = {2, 3}, k = 3Output : InvalidThere is no subarray of size 3 as size of whole array is 2." }, { "code": null, "e": 2634, "s": 2253, "text": "Naive Approach: So, let’s analyze the problem with Brute Force Approach. We start with first index and sum till k-th element. We do it for all possible consecutive blocks or groups of k elements. This method requires nested for loop, the outer for loop starts with the starting element of the block of k elements and the inner or the nested loop will add up till the k-th element." }, { "code": null, "e": 2671, "s": 2634, "text": "Consider the below implementation : " }, { "code": null, "e": 2675, "s": 2671, "text": "C++" }, { "code": null, "e": 2677, "s": 2675, "text": "C" }, { "code": null, "e": 2682, "s": 2677, "text": "Java" }, { "code": null, "e": 2690, "s": 2682, "text": "Python3" }, { "code": null, "e": 2693, "s": 2690, "text": "C#" }, { "code": null, "e": 2697, "s": 2693, "text": "PHP" }, { "code": null, "e": 2708, "s": 2697, "text": "Javascript" }, { "code": "// O(n*k) solution for finding maximum sum of// a subarray of size k#include <bits/stdc++.h>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // Initialize result int max_sum = INT_MIN; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = max(current_sum, max_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3502, "s": 2708, "text": null }, { "code": "// O(n*k) solution for finding maximum sum of// a subarray of size k#include <limits.h>#include <math.h>#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // Initialize result int max_sum = INT_MIN; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = max(current_sum, max_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", maxSum(arr, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4418, "s": 3502, "text": null }, { "code": "// Java code O(n*k) solution for finding maximum sum of// a subarray of size kclass GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int arr[], int n, int k) { // Initialize result int max_sum = Integer.MIN_VALUE; // Consider all blocks starting with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.max(current_sum, max_sum); } return max_sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 5317, "s": 4418, "text": null }, { "code": "# codeimport sys # O(n * k) solution for finding# maximum sum of a subarray of size kINT_MIN = -sys.maxsize - 1 # Returns maximum sum in a# subarray of size k. def maxSum(arr, n, k): # Initialize result max_sum = INT_MIN # Consider all blocks # starting with i. for i in range(n - k + 1): current_sum = 0 for j in range(k): current_sum = current_sum + arr[i + j] # Update result if required. max_sum = max(current_sum, max_sum) return max_sum # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4n = len(arr)print(maxSum(arr, n, k)) # This code is contributed by mits", "e": 5965, "s": 5317, "text": null }, { "code": "// C# code here O(n*k) solution for// finding maximum sum of a subarray// of size kusing System; class GFG { // Returns maximum sum in a // subarray of size k. static int maxSum(int[] arr, int n, int k) { // Initialize result int max_sum = int.MinValue; // Consider all blocks starting // with i. for (int i = 0; i < n - k + 1; i++) { int current_sum = 0; for (int j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.Max(current_sum, max_sum); } return max_sum; } // Driver code public static void Main() { int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.Length; Console.WriteLine(maxSum(arr, n, k)); }} // This code is contributed by anuj_67.", "e": 6856, "s": 5965, "text": null }, { "code": "<?php // code?><?php// O(n*k) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a subarray of size k.function maxSum($arr, $n, $k){ // Initialize result $max_sum = PHP_INT_MIN ; // Consider all blocks // starting with i. for ( $i = 0; $i < $n - $k + 1; $i++) { $current_sum = 0; for ( $j = 0; $j < $k; $j++) $current_sum = $current_sum + $arr[$i + $j]; // Update result if required. $max_sum = max($current_sum, $max_sum ); } return $max_sum;} // Driver code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = count($arr); echo maxSum($arr, $n, $k); // This code is contributed by anuj_67.?>", "e": 7614, "s": 6856, "text": null }, { "code": "<script> // O(n*k) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a subarray of size k.function maxSum( arr, n, k){ // Initialize result let max_sum = Number.MIN_VALUE; // Consider all blocks starting with i. for (let i = 0; i < n - k + 1; i++) { let current_sum = 0; for (let j = 0; j < k; j++) current_sum = current_sum + arr[i + j]; // Update result if required. max_sum = Math.max(current_sum, max_sum); } return max_sum;} // Driver codelet arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];let k = 4;let n = arr.length;document.write(maxSum(arr, n, k)); </script>", "e": 8276, "s": 7614, "text": null }, { "code": null, "e": 8279, "s": 8276, "text": "24" }, { "code": null, "e": 8386, "s": 8279, "text": "It can be observed from the above code that the time complexity is O(k*n) as it contains two nested loops." }, { "code": null, "e": 8863, "s": 8386, "text": "Sliding Window Technique: The technique can be best understood with the window pane in bus, consider a window of length n and the pane which is fixed in it of length k. Consider, initially the pane is at extreme left i.e., at 0 units from the left. Now, co-relate the window with array arr[] of size n and pane with current_sum of size k elements. Now, if we apply force on the window such that it moves a unit distance ahead. The pane will cover next k consecutive elements. " }, { "code": null, "e": 8900, "s": 8863, "text": "Applying sliding window technique : " }, { "code": null, "e": 9277, "s": 8900, "text": "We compute the sum of first k elements out of n terms using a linear loop and store the sum in variable window_sum.Then we will graze linearly over the array till it reaches the end and simultaneously keep track of maximum sum.To get the current sum of block of k elements just subtract the first element from the previous block and add the last element of the current block ." }, { "code": null, "e": 9393, "s": 9277, "text": "We compute the sum of first k elements out of n terms using a linear loop and store the sum in variable window_sum." }, { "code": null, "e": 9506, "s": 9393, "text": "Then we will graze linearly over the array till it reaches the end and simultaneously keep track of maximum sum." }, { "code": null, "e": 9656, "s": 9506, "text": "To get the current sum of block of k elements just subtract the first element from the previous block and add the last element of the current block ." }, { "code": null, "e": 9739, "s": 9656, "text": "The below representation will make it clear how the window slides over the array. " }, { "code": null, "e": 9811, "s": 9739, "text": "Consider an array arr[] = {5, 2, -1, 0, 3} and value of k = 3 and n = 5" }, { "code": null, "e": 9999, "s": 9811, "text": "This is the initial phase where we have calculated the initial window sum starting from index 0 . At this stage the window sum is 6. Now, we set the maximum_sum as current_window i.e 6. " }, { "code": null, "e": 10340, "s": 9999, "text": "Now, we slide our window by a unit index. Therefore, now it discards 5 from the window and adds 0 to the window. Hence, we will get our new window sum by subtracting 5 and then adding 0 to it. So, our window sum now becomes 1. Now, we will compare this window sum with the maximum_sum. As it is smaller we wont the change the maximum_sum. " }, { "code": null, "e": 10639, "s": 10340, "text": "Similarly, now once again we slide our window by a unit index and obtain the new window sum to be 2. Again we check if this current window sum is greater than the maximum_sum till now. Once, again it is smaller so we don’t change the maximum_sum.Therefore, for the above array our maximum_sum is 6." }, { "code": null, "e": 10677, "s": 10639, "text": "Below is the code for above approach:" }, { "code": null, "e": 10681, "s": 10677, "text": "C++" }, { "code": null, "e": 10686, "s": 10681, "text": "Java" }, { "code": null, "e": 10694, "s": 10686, "text": "Python3" }, { "code": null, "e": 10697, "s": 10694, "text": "C#" }, { "code": null, "e": 10701, "s": 10697, "text": "PHP" }, { "code": null, "e": 10712, "s": 10701, "text": "Javascript" }, { "code": "// O(n) solution for finding maximum sum of// a subarray of size k#include <iostream>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // n must be greater if (n < k) { cout << \"Invalid\"; return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = max(max_sum, window_sum); } return max_sum;} // Driver codeint main(){ int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;}", "e": 11611, "s": 10712, "text": null }, { "code": "// Java code for// O(n) solution for finding// maximum sum of a subarray// of size kclass GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int arr[], int n, int k) { // n must be greater if (n < k) { System.out.println(\"Invalid\"); return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = Math.max(max_sum, window_sum); } return max_sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }} // This code is contributed// by prerna saini.", "e": 12713, "s": 11611, "text": null }, { "code": "# O(n) solution for finding# maximum sum of a subarray of size k def maxSum(arr, k): # length of the array n = len(arr) # n must be greater than k if n < k: print(\"Invalid\") return -1 # Compute sum of first window of size k window_sum = sum(arr[:k]) # first sum available max_sum = window_sum # Compute the sums of remaining windows by # removing first element of previous # window and adding last element of # the current window. for i in range(n - k): window_sum = window_sum - arr[i] + arr[i + k] max_sum = max(window_sum, max_sum) return max_sum # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4print(maxSum(arr, k)) # This code is contributed by Kyle McClay", "e": 13467, "s": 12713, "text": null }, { "code": "// C# code for O(n) solution for finding// maximum sum of a subarray of size kusing System; class GFG { // Returns maximum sum in // a subarray of size k. static int maxSum(int[] arr, int n, int k) { // n must be greater if (n < k) { Console.WriteLine(\"Invalid\"); return -1; } // Compute sum of first window of size k int max_sum = 0; for (int i = 0; i < k; i++) max_sum += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int window_sum = max_sum; for (int i = k; i < n; i++) { window_sum += arr[i] - arr[i - k]; max_sum = Math.Max(max_sum, window_sum); } return max_sum; } // Driver code public static void Main() { int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; int k = 4; int n = arr.Length; Console.WriteLine(maxSum(arr, n, k)); }} // This code is contributed by anuj_67.", "e": 14557, "s": 13467, "text": null }, { "code": "<?php// O(n) solution for finding maximum sum of// a subarray of size k // Returns maximum sum in a // subarray of size k.function maxSum( $arr, $n, $k){ // n must be greater if ($n < $k) { echo \"Invalid\"; return -1; } // Compute sum of first // window of size k $max_sum = 0; for($i = 0; $i < $k; $i++) $max_sum += $arr[$i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. $window_sum = $max_sum; for ($i = $k; $i < $n; $i++) { $window_sum += $arr[$i] - $arr[$i - $k]; $max_sum = max($max_sum, $window_sum); } return $max_sum;} // Driver code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = count($arr); echo maxSum($arr, $n, $k); // This code is contributed by anuj_67?>", "e": 15431, "s": 14557, "text": null }, { "code": "<script> // Javascript code for // O(n) solution for finding // maximum sum of a subarray // of size k function maxSum(arr, n, k) { let max = 0; let sum = 0; // find initial sum of first k elements for (let i = 0; i < k; i++) { sum += arr[i]; max = sum; } // iterate the array once // and increment the right edge for (let i = k; i < n; i++) { sum += arr[i] - arr[i - k]; // compare if sum is more than max, // if yes then replace // max with new sum value if (sum > max) { max = sum; } } return max; } // Driver codelet arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];let k = 4;let n = arr.length;document.write(maxSum(arr, n, k)); </script>", "e": 16269, "s": 15431, "text": null }, { "code": null, "e": 16272, "s": 16269, "text": "24" }, { "code": null, "e": 16419, "s": 16272, "text": "Now, it is quite obvious that the Time Complexity is linear as we can see that only one loop runs in our code. Hence, our Time Complexity is O(n)." }, { "code": null, "e": 16547, "s": 16419, "text": "We can use this technique to find max/min k-subarray, XOR, product, sum, etc. Refer sliding window problems for such problems. " }, { "code": null, "e": 17419, "s": 16547, "text": "Sliding Window Technique | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSliding Window Technique | GeeksforGeeksWatch laterShareCopy link95/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9-3BXsfrpbY\" 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": 17463, "s": 17419, "text": "Recent Articles on Window Sliding Technique" }, { "code": null, "e": 17500, "s": 17463, "text": "Practice Questions on Window Sliding" }, { "code": null, "e": 17557, "s": 17500, "text": "DSA Self Paced – The Most used and Trusted Course on DSA" }, { "code": null, "e": 17979, "s": 17557, "text": "This article is contributed by Kanika Thakral. 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": 17984, "s": 17979, "text": "vt_m" }, { "code": null, "e": 17996, "s": 17984, "text": "AnnieAlford" }, { "code": null, "e": 18009, "s": 17996, "text": "Mithun Kumar" }, { "code": null, "e": 18020, "s": 18009, "text": "KyleMcClay" }, { "code": null, "e": 18031, "s": 18020, "text": "Ekta Arora" }, { "code": null, "e": 18040, "s": 18031, "text": "Parimal7" }, { "code": null, "e": 18055, "s": 18040, "text": "maartenjjacobs" }, { "code": null, "e": 18071, "s": 18055, "text": "rohitsingh07052" }, { "code": null, "e": 18089, "s": 18071, "text": "GauravMaheshwari1" }, { "code": null, "e": 18105, "s": 18089, "text": "amartyaghoshgfg" }, { "code": null, "e": 18119, "s": 18105, "text": "RishabhPrabhu" }, { "code": null, "e": 18131, "s": 18119, "text": "krisania804" }, { "code": null, "e": 18142, "s": 18131, "text": "starcode01" }, { "code": null, "e": 18157, "s": 18142, "text": "sliding-window" }, { "code": null, "e": 18164, "s": 18157, "text": "Arrays" }, { "code": null, "e": 18183, "s": 18164, "text": "Technical Scripter" }, { "code": null, "e": 18198, "s": 18183, "text": "sliding-window" }, { "code": null, "e": 18205, "s": 18198, "text": "Arrays" }, { "code": null, "e": 18303, "s": 18205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18318, "s": 18303, "text": "Arrays in Java" }, { "code": null, "e": 18386, "s": 18318, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 18430, "s": 18386, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 18462, "s": 18430, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 18478, "s": 18462, "text": "Arrays in C/C++" }, { "code": null, "e": 18505, "s": 18478, "text": "Program for array rotation" }, { "code": null, "e": 18537, "s": 18505, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 18585, "s": 18537, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 18599, "s": 18585, "text": "Linear Search" } ]
Find the minimum and maximum sum of N-1 elements of the array
25 May, 2022 Given an unsorted array A of size N, the task is to find the minimum and maximum values that can be calculated by adding exactly N-1 elements. Examples: Input: a[] = {13, 5, 11, 9, 7} Output: 32 40 Explanation: Minimum sum is 5 + 7 + 9 + 11 = 32 and maximum sum is 7 + 9 + 11 + 13 = 40.Input: a[] = {13, 11, 45, 32, 89, 21} Output: 122 200 Explanation: Minimum sum is 11 + 13 + 21 + 32 + 45 = 122 and maximum sum is 13 + 21 + 32 + 45 + 89 = 200.Input: a[] = {6, 3, 15, 27, 9} Output: 33 57 Explanation: Minimum sum is 3 + 6 + 9 + 15 = 33 and maximum sum is 6 + 9 + 15 + 27 = 57. Simple Approach: Sort the array in ascending order.Sum of the first N-1 elements in the array gives the minimum possible sum.Sum of the last N-1 elements in the array gives the maximum possible sum. Sort the array in ascending order. Sum of the first N-1 elements in the array gives the minimum possible sum. Sum of the last N-1 elements in the array gives the maximum possible sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; // Python Implementation of the above approachvoid minMax(vector<int>&arr){ // Initialize the min_value // and max_value to 0 int min_value = 0; int max_value = 0; int n = arr.size(); // Sort array before calculating // min and max value sort(arr.begin(),arr.end()); int j = n - 1; for(int i = 0; i < n - 1; i++) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; j -= 1; } // Output: min_value and max_value cout<<min_value<<" "<<max_value<<endl;} // Driver Codeint main(){ vector<int>arr = {10, 9, 8, 7, 6, 5}; vector<int>arr1 = {100, 200, 300, 400, 500}; minMax(arr); minMax(arr1); } // This code is contributed by shinjanpatra // Java Implementation of the above approachimport java.util.*; class GFG { static void minMax(int[] arr) { // Initialize the min_value // and max_value to 0 long min_value = 0; long max_value = 0; int n = arr.length; // Sort array before calculating // min and max value Arrays.sort(arr); for (int i = 0, j = n - 1; i < n - 1; i++, j--) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; } // Output: min_value and max_value System.out.println( min_value + " " + max_value); } // Driver Code public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Initialize your array elements here int[] arr = { 10, 9, 8, 7, 6, 5 }; int[] arr1 = { 100, 200, 300, 400, 500 }; minMax(arr); minMax(arr1); }} # Python Implementation of the above approachdef minMax(arr): # Initialize the min_value # and max_value to 0 min_value = 0 max_value = 0 n=len(arr) # Sort array before calculating # min and max value arr.sort() j=n-1 for i in range(n-1): # All elements except # rightmost will be added min_value += arr[i] # All elements except # leftmost will be added max_value += arr[j] j-=1 # Output: min_value and max_value print(min_value," ",max_value) # Driver Codearr=[10, 9, 8, 7, 6, 5]arr1=[100, 200, 300, 400, 500] minMax(arr)minMax(arr1) # This code is contributed by ab2127. using System; public class GFG{ static void minMax(int[] arr) { // Initialize the min_value // and max_value to 0 long min_value = 0; long max_value = 0; int n = arr.Length; // Sort array before calculating // min and max value Array.Sort(arr); int j = n - 1; for (int i = 0 ;i < n - 1; i++) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; j--; } // Output: min_value and max_value Console.WriteLine( min_value + " " + max_value); } // Driver Code static public void Main (){ // Initialize your array elements here int[] arr = { 10, 9, 8, 7, 6, 5 }; int[] arr1 = { 100, 200, 300, 400, 500 }; minMax(arr); minMax(arr1); }} // This code is contributed by rag2127 <script>// Javascript Implementation of the above approach function minMax(arr) { // Initialize the min_value // and max_value to 0 let min_value = 0; let max_value = 0; let n = arr.length; // Sort array before calculating // min and max value arr.sort(function(a,b){return a-b;}); for (let i = 0, j = n - 1; i < n - 1; i++, j--) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; } // Output: min_value and max_value document.write( min_value + " " + max_value+"<br>"); } // Driver Code let arr=[10, 9, 8, 7, 6, 5]; let arr1=[100, 200, 300, 400, 500 ]; minMax(arr); minMax(arr1); // This code is contributed by avanitrachhadiya2155</script> Output: 35 40 1000 1400 Time complexity: O(NlogN) Efficient Approach: Find the minimum and maximum element of the array.Calculate the sum of all the elements in the array.Excluding maximum element from the sum gives the minimum possible sum.Excluding the minimum element from the sum gives the maximum possible sum. Find the minimum and maximum element of the array. Calculate the sum of all the elements in the array. Excluding maximum element from the sum gives the minimum possible sum. Excluding the minimum element from the sum gives the maximum possible sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the minimum and maximum// sum from an array.#include <bits/stdc++.h>using namespace std; // Function to calculate minimum and maximum sumstatic void miniMaxSum(int arr[], int n){ // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(int i = 1; i < n; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum cout << (sum - maxElement) << " " << (sum - minElement) << endl;} // Driver Codeint main(){ // Test Case 1: int a1[] = { 13, 5, 11, 9, 7 }; int n = sizeof(a1) / sizeof(a1[0]); // Call miniMaxSum() miniMaxSum(a1, n); // Test Case 2: int a2[] = { 13, 11, 45, 32, 89, 21 }; n = sizeof(a2) / sizeof(a2[0]); miniMaxSum(a2, n); // Test Case 3: int a3[] = { 6, 3, 15, 27, 9 }; n = sizeof(a3) / sizeof(a3[0]); miniMaxSum(a3, n);} // This code is contributed by chitranayal // Java program to find the minimum and maximum// sum from an array.class GFG { // Function to calculate minimum and maximum sum static void miniMaxSum(int[] arr) { // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for (int i = 1; i < arr.length; i++) { // calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum System.out.println((sum - maxElement) + " " + (sum - minElement)); } // Driver Code public static void main(String args[]) { // Test Case 1: int a1[] = { 13, 5, 11, 9, 7 }; // Call miniMaxSum() miniMaxSum(a1); // Test Case 2: int a2[] = { 13, 11, 45, 32, 89, 21 }; miniMaxSum(a2); // Test Case 3: int a3[] = { 6, 3, 15, 27, 9 }; miniMaxSum(a3); }} # Python3 program to find the minimum and# maximum sum from a list. # Function to calculate minimum and maximum sumdef miniMaxSum(arr, n): # Initialize the minElement, maxElement # and sum by 0. minElement = 0 maxElement = 0 sum = 0 # Assigning maxElement, minElement # and sum as the first list element minElement = arr[0] maxElement = minElement sum = minElement # Traverse the entire list for i in range(1, n): # Calculate the sum of # list elements sum += arr[i] # Keep updating the # minimum element if (arr[i] < minElement): minElement = arr[i] # Keep updating the # maximum element if (arr[i] > maxElement): maxElement = arr[i] # Print the minimum and maximum sum print(sum - maxElement, sum - minElement) # Driver Code # Test Case 1:a1 = [ 13, 5, 11, 9, 7 ]n = len(a1) # Call miniMaxSum()miniMaxSum(a1, n) # Test Case 2:a2 = [ 13, 11, 45, 32, 89, 21 ]n = len(a2)miniMaxSum(a2, n) # Test Case 3:a3 = [ 6, 3, 15, 27, 9 ]n = len(a3)miniMaxSum(a3, n) # This code is contributed by vishu2908 // C# program to find the minimum and maximum// sum from an array.using System; class GFG{ // Function to calculate minimum and maximum sumstatic void miniMaxSum(int[] arr){ // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(int i = 1; i < arr.Length; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // Print the minimum and maximum sum Console.WriteLine((sum - maxElement) + " " + (sum - minElement));} // Driver Codepublic static void Main(){ // Test Case 1: int[] a1 = new int[]{ 13, 5, 11, 9, 7 }; // Call miniMaxSum() miniMaxSum(a1); // Test Case 2: int[] a2 = new int[]{ 13, 11, 45, 32, 89, 21 }; miniMaxSum(a2); // Test Case 3: int[] a3 = new int[]{ 6, 3, 15, 27, 9 }; miniMaxSum(a3);}} // This code is contributed by sanjoy_62 <script> // Function to calculate minimum and maximum sumfunction miniMaxSum( arr, n){ // Initialize the minElement, maxElement // and sum by 0. var minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(var i = 1; i < n; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum document.write((sum - maxElement)+ " "+ (sum - minElement) + "<br>");} // Driver Code var a1= [ 13, 5, 11, 9, 7 ]; // Call miniMaxSum() miniMaxSum(a1, 5); // Test Case 2: var a2 = [13, 11, 45, 32, 89, 21 ]; miniMaxSum(a2, 6); // Test Case 3: var a3 = [ 6, 3, 15, 27, 9 ]; miniMaxSum(a3, 5); </script> 32 40 122 200 33 57 Time complexity: O(N) prashantsrivastava1 ukasp vishu2908 sanjoy_62 rahuljrj642 akshitsaxenaa09 avanitrachhadiya2155 rag2127 ab2127 shinjanpatra Java-Array-Programs Arrays Competitive Programming School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 195, "s": 52, "text": "Given an unsorted array A of size N, the task is to find the minimum and maximum values that can be calculated by adding exactly N-1 elements." }, { "code": null, "e": 205, "s": 195, "text": "Examples:" }, { "code": null, "e": 631, "s": 205, "text": "Input: a[] = {13, 5, 11, 9, 7} Output: 32 40 Explanation: Minimum sum is 5 + 7 + 9 + 11 = 32 and maximum sum is 7 + 9 + 11 + 13 = 40.Input: a[] = {13, 11, 45, 32, 89, 21} Output: 122 200 Explanation: Minimum sum is 11 + 13 + 21 + 32 + 45 = 122 and maximum sum is 13 + 21 + 32 + 45 + 89 = 200.Input: a[] = {6, 3, 15, 27, 9} Output: 33 57 Explanation: Minimum sum is 3 + 6 + 9 + 15 = 33 and maximum sum is 6 + 9 + 15 + 27 = 57." }, { "code": null, "e": 648, "s": 631, "text": "Simple Approach:" }, { "code": null, "e": 830, "s": 648, "text": "Sort the array in ascending order.Sum of the first N-1 elements in the array gives the minimum possible sum.Sum of the last N-1 elements in the array gives the maximum possible sum." }, { "code": null, "e": 865, "s": 830, "text": "Sort the array in ascending order." }, { "code": null, "e": 940, "s": 865, "text": "Sum of the first N-1 elements in the array gives the minimum possible sum." }, { "code": null, "e": 1014, "s": 940, "text": "Sum of the last N-1 elements in the array gives the maximum possible sum." }, { "code": null, "e": 1065, "s": 1014, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1069, "s": 1065, "text": "C++" }, { "code": null, "e": 1074, "s": 1069, "text": "Java" }, { "code": null, "e": 1082, "s": 1074, "text": "Python3" }, { "code": null, "e": 1085, "s": 1082, "text": "C#" }, { "code": null, "e": 1096, "s": 1085, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; // Python Implementation of the above approachvoid minMax(vector<int>&arr){ // Initialize the min_value // and max_value to 0 int min_value = 0; int max_value = 0; int n = arr.size(); // Sort array before calculating // min and max value sort(arr.begin(),arr.end()); int j = n - 1; for(int i = 0; i < n - 1; i++) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; j -= 1; } // Output: min_value and max_value cout<<min_value<<\" \"<<max_value<<endl;} // Driver Codeint main(){ vector<int>arr = {10, 9, 8, 7, 6, 5}; vector<int>arr1 = {100, 200, 300, 400, 500}; minMax(arr); minMax(arr1); } // This code is contributed by shinjanpatra", "e": 2009, "s": 1096, "text": null }, { "code": "// Java Implementation of the above approachimport java.util.*; class GFG { static void minMax(int[] arr) { // Initialize the min_value // and max_value to 0 long min_value = 0; long max_value = 0; int n = arr.length; // Sort array before calculating // min and max value Arrays.sort(arr); for (int i = 0, j = n - 1; i < n - 1; i++, j--) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; } // Output: min_value and max_value System.out.println( min_value + \" \" + max_value); } // Driver Code public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Initialize your array elements here int[] arr = { 10, 9, 8, 7, 6, 5 }; int[] arr1 = { 100, 200, 300, 400, 500 }; minMax(arr); minMax(arr1); }}", "e": 3128, "s": 2009, "text": null }, { "code": "# Python Implementation of the above approachdef minMax(arr): # Initialize the min_value # and max_value to 0 min_value = 0 max_value = 0 n=len(arr) # Sort array before calculating # min and max value arr.sort() j=n-1 for i in range(n-1): # All elements except # rightmost will be added min_value += arr[i] # All elements except # leftmost will be added max_value += arr[j] j-=1 # Output: min_value and max_value print(min_value,\" \",max_value) # Driver Codearr=[10, 9, 8, 7, 6, 5]arr1=[100, 200, 300, 400, 500] minMax(arr)minMax(arr1) # This code is contributed by ab2127.", "e": 3821, "s": 3128, "text": null }, { "code": "using System; public class GFG{ static void minMax(int[] arr) { // Initialize the min_value // and max_value to 0 long min_value = 0; long max_value = 0; int n = arr.Length; // Sort array before calculating // min and max value Array.Sort(arr); int j = n - 1; for (int i = 0 ;i < n - 1; i++) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; j--; } // Output: min_value and max_value Console.WriteLine( min_value + \" \" + max_value); } // Driver Code static public void Main (){ // Initialize your array elements here int[] arr = { 10, 9, 8, 7, 6, 5 }; int[] arr1 = { 100, 200, 300, 400, 500 }; minMax(arr); minMax(arr1); }} // This code is contributed by rag2127", "e": 4904, "s": 3821, "text": null }, { "code": "<script>// Javascript Implementation of the above approach function minMax(arr) { // Initialize the min_value // and max_value to 0 let min_value = 0; let max_value = 0; let n = arr.length; // Sort array before calculating // min and max value arr.sort(function(a,b){return a-b;}); for (let i = 0, j = n - 1; i < n - 1; i++, j--) { // All elements except // rightmost will be added min_value += arr[i]; // All elements except // leftmost will be added max_value += arr[j]; } // Output: min_value and max_value document.write( min_value + \" \" + max_value+\"<br>\"); } // Driver Code let arr=[10, 9, 8, 7, 6, 5]; let arr1=[100, 200, 300, 400, 500 ]; minMax(arr); minMax(arr1); // This code is contributed by avanitrachhadiya2155</script>", "e": 5917, "s": 4904, "text": null }, { "code": null, "e": 5925, "s": 5917, "text": "Output:" }, { "code": null, "e": 5941, "s": 5925, "text": "35 40\n1000 1400" }, { "code": null, "e": 5967, "s": 5941, "text": "Time complexity: O(NlogN)" }, { "code": null, "e": 5987, "s": 5967, "text": "Efficient Approach:" }, { "code": null, "e": 6233, "s": 5987, "text": "Find the minimum and maximum element of the array.Calculate the sum of all the elements in the array.Excluding maximum element from the sum gives the minimum possible sum.Excluding the minimum element from the sum gives the maximum possible sum." }, { "code": null, "e": 6284, "s": 6233, "text": "Find the minimum and maximum element of the array." }, { "code": null, "e": 6336, "s": 6284, "text": "Calculate the sum of all the elements in the array." }, { "code": null, "e": 6407, "s": 6336, "text": "Excluding maximum element from the sum gives the minimum possible sum." }, { "code": null, "e": 6482, "s": 6407, "text": "Excluding the minimum element from the sum gives the maximum possible sum." }, { "code": null, "e": 6533, "s": 6482, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 6537, "s": 6533, "text": "C++" }, { "code": null, "e": 6542, "s": 6537, "text": "Java" }, { "code": null, "e": 6550, "s": 6542, "text": "Python3" }, { "code": null, "e": 6553, "s": 6550, "text": "C#" }, { "code": null, "e": 6564, "s": 6553, "text": "Javascript" }, { "code": "// C++ program to find the minimum and maximum// sum from an array.#include <bits/stdc++.h>using namespace std; // Function to calculate minimum and maximum sumstatic void miniMaxSum(int arr[], int n){ // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(int i = 1; i < n; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum cout << (sum - maxElement) << \" \" << (sum - minElement) << endl;} // Driver Codeint main(){ // Test Case 1: int a1[] = { 13, 5, 11, 9, 7 }; int n = sizeof(a1) / sizeof(a1[0]); // Call miniMaxSum() miniMaxSum(a1, n); // Test Case 2: int a2[] = { 13, 11, 45, 32, 89, 21 }; n = sizeof(a2) / sizeof(a2[0]); miniMaxSum(a2, n); // Test Case 3: int a3[] = { 6, 3, 15, 27, 9 }; n = sizeof(a3) / sizeof(a3[0]); miniMaxSum(a3, n);} // This code is contributed by chitranayal", "e": 8035, "s": 6564, "text": null }, { "code": "// Java program to find the minimum and maximum// sum from an array.class GFG { // Function to calculate minimum and maximum sum static void miniMaxSum(int[] arr) { // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for (int i = 1; i < arr.length; i++) { // calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum System.out.println((sum - maxElement) + \" \" + (sum - minElement)); } // Driver Code public static void main(String args[]) { // Test Case 1: int a1[] = { 13, 5, 11, 9, 7 }; // Call miniMaxSum() miniMaxSum(a1); // Test Case 2: int a2[] = { 13, 11, 45, 32, 89, 21 }; miniMaxSum(a2); // Test Case 3: int a3[] = { 6, 3, 15, 27, 9 }; miniMaxSum(a3); }}", "e": 9504, "s": 8035, "text": null }, { "code": "# Python3 program to find the minimum and# maximum sum from a list. # Function to calculate minimum and maximum sumdef miniMaxSum(arr, n): # Initialize the minElement, maxElement # and sum by 0. minElement = 0 maxElement = 0 sum = 0 # Assigning maxElement, minElement # and sum as the first list element minElement = arr[0] maxElement = minElement sum = minElement # Traverse the entire list for i in range(1, n): # Calculate the sum of # list elements sum += arr[i] # Keep updating the # minimum element if (arr[i] < minElement): minElement = arr[i] # Keep updating the # maximum element if (arr[i] > maxElement): maxElement = arr[i] # Print the minimum and maximum sum print(sum - maxElement, sum - minElement) # Driver Code # Test Case 1:a1 = [ 13, 5, 11, 9, 7 ]n = len(a1) # Call miniMaxSum()miniMaxSum(a1, n) # Test Case 2:a2 = [ 13, 11, 45, 32, 89, 21 ]n = len(a2)miniMaxSum(a2, n) # Test Case 3:a3 = [ 6, 3, 15, 27, 9 ]n = len(a3)miniMaxSum(a3, n) # This code is contributed by vishu2908", "e": 10642, "s": 9504, "text": null }, { "code": "// C# program to find the minimum and maximum// sum from an array.using System; class GFG{ // Function to calculate minimum and maximum sumstatic void miniMaxSum(int[] arr){ // Initialize the minElement, maxElement // and sum by 0. int minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(int i = 1; i < arr.Length; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // Print the minimum and maximum sum Console.WriteLine((sum - maxElement) + \" \" + (sum - minElement));} // Driver Codepublic static void Main(){ // Test Case 1: int[] a1 = new int[]{ 13, 5, 11, 9, 7 }; // Call miniMaxSum() miniMaxSum(a1); // Test Case 2: int[] a2 = new int[]{ 13, 11, 45, 32, 89, 21 }; miniMaxSum(a2); // Test Case 3: int[] a3 = new int[]{ 6, 3, 15, 27, 9 }; miniMaxSum(a3);}} // This code is contributed by sanjoy_62", "e": 12035, "s": 10642, "text": null }, { "code": "<script> // Function to calculate minimum and maximum sumfunction miniMaxSum( arr, n){ // Initialize the minElement, maxElement // and sum by 0. var minElement = 0, maxElement = 0, sum = 0; // Assigning maxElement, minElement // and sum as the first array element minElement = arr[0]; maxElement = minElement; sum = minElement; // Traverse the entire array for(var i = 1; i < n; i++) { // Calculate the sum of // array elements sum += arr[i]; // Keep updating the // minimum element if (arr[i] < minElement) { minElement = arr[i]; } // Keep updating the // maximum element if (arr[i] > maxElement) { maxElement = arr[i]; } } // print the minimum and maximum sum document.write((sum - maxElement)+ \" \"+ (sum - minElement) + \"<br>\");} // Driver Code var a1= [ 13, 5, 11, 9, 7 ]; // Call miniMaxSum() miniMaxSum(a1, 5); // Test Case 2: var a2 = [13, 11, 45, 32, 89, 21 ]; miniMaxSum(a2, 6); // Test Case 3: var a3 = [ 6, 3, 15, 27, 9 ]; miniMaxSum(a3, 5); </script>", "e": 13211, "s": 12035, "text": null }, { "code": null, "e": 13231, "s": 13211, "text": "32 40\n122 200\n33 57" }, { "code": null, "e": 13253, "s": 13231, "text": "Time complexity: O(N)" }, { "code": null, "e": 13275, "s": 13255, "text": "prashantsrivastava1" }, { "code": null, "e": 13281, "s": 13275, "text": "ukasp" }, { "code": null, "e": 13291, "s": 13281, "text": "vishu2908" }, { "code": null, "e": 13301, "s": 13291, "text": "sanjoy_62" }, { "code": null, "e": 13313, "s": 13301, "text": "rahuljrj642" }, { "code": null, "e": 13329, "s": 13313, "text": "akshitsaxenaa09" }, { "code": null, "e": 13350, "s": 13329, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13358, "s": 13350, "text": "rag2127" }, { "code": null, "e": 13365, "s": 13358, "text": "ab2127" }, { "code": null, "e": 13378, "s": 13365, "text": "shinjanpatra" }, { "code": null, "e": 13398, "s": 13378, "text": "Java-Array-Programs" }, { "code": null, "e": 13405, "s": 13398, "text": "Arrays" }, { "code": null, "e": 13429, "s": 13405, "text": "Competitive Programming" }, { "code": null, "e": 13448, "s": 13429, "text": "School Programming" }, { "code": null, "e": 13455, "s": 13448, "text": "Arrays" }, { "code": null, "e": 13553, "s": 13455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13621, "s": 13553, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 13665, "s": 13621, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 13697, "s": 13665, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13745, "s": 13697, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 13759, "s": 13745, "text": "Linear Search" }, { "code": null, "e": 13802, "s": 13759, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 13845, "s": 13802, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 13886, "s": 13845, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 13913, "s": 13886, "text": "Modulo 10^9+7 (1000000007)" } ]
Chatbot: A Complete PyCharm App. Chatterbot, Django, Python and Pycharm... | by Jesko Rehberg | Towards Data Science
Motivation: Are you looking for a completely ready to go chatbot, which you can easily adapt to your needs? Look no further, if you are willing to use Python, Pycharm, Django and Chatterbot all combined. Top of that, there is even a SQLite database added to this app, so you can analyze user’s input and Chatbot’s output. This post focuses on how to get a FAQ chatbot up and running, without going into theoretical background of chatterbot, which will be the topic of another related post. Solution: First of all please make sure you have PyCharm installed. If not, please do so now: go to www.jetbrains.com and install the free community edition. Afterwards, before starting a new project in PyCharm, please copy all files from my Google Drive folder: https://drive.google.com/drive/folders/1IXXJzNr8pbGFSIYpWj92fXnQX35eZOFT?usp=sharing ..and copy that into your PyCharm Projects folder (usually in your users folder): Then open PyCharm and click on “New Project”: Choose the ChatbotProject folder (which you have downloaded from my Google Cloud just before) as the location for your new virtual environment (virtualenv) project. Make also sure that the Python Interpreter is directed to Python 3.7: After confirming you want to create from existing sources: As a next step, add Configuration: ..and click on the plus symbol in the left top corner: where these settings have to be entered: From now on you can simply start Manage.py by clicking the Run button: ..and click on the localhost link which will be started after a few seconds: In case there are now import errors popping up, similar to this: ..all you have to do is to go to settings and import the necessary packages in the Python Interpreter section: Please make sure that Django 2.2 and Chatterbot 1.0.2. is installed. That will ensure to work well with Python 3.7 for our chatterbot: If you now run “manage.py” again, you might receive this message the first time you want to start your chatbot: In this case please go to your Terminal and enter: python manage.py migrate Now run manage.py again and your Chatbot should work in your browser: You enter a question and our bot will hopefully give us the right answer: You can enter a question and your chatbot will give you an answer to this question. The reason the chatbot might know the right answer is due to your chats.txt, which you can adapt here: If you prefer yaml files instead of the chats.txt, you can also adapt any of these corpus files: Please note that all of them are chatterbot modules, except the FAQ. That one has been created by myself, for learning purposes: Chatterbot is an extremely interesting chatbot which uses machine learning techniques. Please have a look at the Chatterbot website if you are looking for more details behind chatterbot. Anything more to add? Everything is now working well. But wouldn’t it be cool to even add a database connectivity, so we can analyze chatbot’s output to that user’s input? Therefore we have to go to settings again, but this time we will install in the Plugin sector. Search for Database Navigator and install that plugin: Then enter a new DB Connection: Choose SQLite and add db.sqlite3 as Database file: Looking into the table “statement”, we can see all trained conversations, after we have run our Chatbot the first time after we have installed Database Navigator: Congratulations, we have a complete chatbot running! We will discuss the chatterbot learning in detail in another post. For the time being, many thanks for reading, hope this was supportive! Any questions, please let me know. You can connect with me on LinkedIn or Twitter. Originally published on my website DAR-Analytics.
[ { "code": null, "e": 184, "s": 172, "text": "Motivation:" }, { "code": null, "e": 494, "s": 184, "text": "Are you looking for a completely ready to go chatbot, which you can easily adapt to your needs? Look no further, if you are willing to use Python, Pycharm, Django and Chatterbot all combined. Top of that, there is even a SQLite database added to this app, so you can analyze user’s input and Chatbot’s output." }, { "code": null, "e": 662, "s": 494, "text": "This post focuses on how to get a FAQ chatbot up and running, without going into theoretical background of chatterbot, which will be the topic of another related post." }, { "code": null, "e": 672, "s": 662, "text": "Solution:" }, { "code": null, "e": 756, "s": 672, "text": "First of all please make sure you have PyCharm installed. If not, please do so now:" }, { "code": null, "e": 820, "s": 756, "text": "go to www.jetbrains.com and install the free community edition." }, { "code": null, "e": 1010, "s": 820, "text": "Afterwards, before starting a new project in PyCharm, please copy all files from my Google Drive folder: https://drive.google.com/drive/folders/1IXXJzNr8pbGFSIYpWj92fXnQX35eZOFT?usp=sharing" }, { "code": null, "e": 1092, "s": 1010, "text": "..and copy that into your PyCharm Projects folder (usually in your users folder):" }, { "code": null, "e": 1138, "s": 1092, "text": "Then open PyCharm and click on “New Project”:" }, { "code": null, "e": 1373, "s": 1138, "text": "Choose the ChatbotProject folder (which you have downloaded from my Google Cloud just before) as the location for your new virtual environment (virtualenv) project. Make also sure that the Python Interpreter is directed to Python 3.7:" }, { "code": null, "e": 1432, "s": 1373, "text": "After confirming you want to create from existing sources:" }, { "code": null, "e": 1467, "s": 1432, "text": "As a next step, add Configuration:" }, { "code": null, "e": 1522, "s": 1467, "text": "..and click on the plus symbol in the left top corner:" }, { "code": null, "e": 1563, "s": 1522, "text": "where these settings have to be entered:" }, { "code": null, "e": 1634, "s": 1563, "text": "From now on you can simply start Manage.py by clicking the Run button:" }, { "code": null, "e": 1711, "s": 1634, "text": "..and click on the localhost link which will be started after a few seconds:" }, { "code": null, "e": 1776, "s": 1711, "text": "In case there are now import errors popping up, similar to this:" }, { "code": null, "e": 1887, "s": 1776, "text": "..all you have to do is to go to settings and import the necessary packages in the Python Interpreter section:" }, { "code": null, "e": 2022, "s": 1887, "text": "Please make sure that Django 2.2 and Chatterbot 1.0.2. is installed. That will ensure to work well with Python 3.7 for our chatterbot:" }, { "code": null, "e": 2134, "s": 2022, "text": "If you now run “manage.py” again, you might receive this message the first time you want to start your chatbot:" }, { "code": null, "e": 2185, "s": 2134, "text": "In this case please go to your Terminal and enter:" }, { "code": null, "e": 2210, "s": 2185, "text": "python manage.py migrate" }, { "code": null, "e": 2280, "s": 2210, "text": "Now run manage.py again and your Chatbot should work in your browser:" }, { "code": null, "e": 2354, "s": 2280, "text": "You enter a question and our bot will hopefully give us the right answer:" }, { "code": null, "e": 2541, "s": 2354, "text": "You can enter a question and your chatbot will give you an answer to this question. The reason the chatbot might know the right answer is due to your chats.txt, which you can adapt here:" }, { "code": null, "e": 2638, "s": 2541, "text": "If you prefer yaml files instead of the chats.txt, you can also adapt any of these corpus files:" }, { "code": null, "e": 2767, "s": 2638, "text": "Please note that all of them are chatterbot modules, except the FAQ. That one has been created by myself, for learning purposes:" }, { "code": null, "e": 2954, "s": 2767, "text": "Chatterbot is an extremely interesting chatbot which uses machine learning techniques. Please have a look at the Chatterbot website if you are looking for more details behind chatterbot." }, { "code": null, "e": 2976, "s": 2954, "text": "Anything more to add?" }, { "code": null, "e": 3126, "s": 2976, "text": "Everything is now working well. But wouldn’t it be cool to even add a database connectivity, so we can analyze chatbot’s output to that user’s input?" }, { "code": null, "e": 3276, "s": 3126, "text": "Therefore we have to go to settings again, but this time we will install in the Plugin sector. Search for Database Navigator and install that plugin:" }, { "code": null, "e": 3308, "s": 3276, "text": "Then enter a new DB Connection:" }, { "code": null, "e": 3359, "s": 3308, "text": "Choose SQLite and add db.sqlite3 as Database file:" }, { "code": null, "e": 3522, "s": 3359, "text": "Looking into the table “statement”, we can see all trained conversations, after we have run our Chatbot the first time after we have installed Database Navigator:" }, { "code": null, "e": 3796, "s": 3522, "text": "Congratulations, we have a complete chatbot running! We will discuss the chatterbot learning in detail in another post. For the time being, many thanks for reading, hope this was supportive! Any questions, please let me know. You can connect with me on LinkedIn or Twitter." } ]
C++ Basic Input/Output
The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation. There are following header files important to C++ programs − <iostream> This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively. <iomanip> This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision. <fstream> This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter. The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example. #include <iostream> using namespace std; int main() { char str[] = "Hello C++"; cout << "Value of str is : " << str << endl; } When the above code is compiled and executed, it produces the following result − Value of str is : Hello C++ The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values. The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line. The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example. #include <iostream> using namespace std; int main() { char name[50]; cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl; } When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result − Please enter your name: cplusplus Your name is: cplusplus The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables. The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following − cin >> name >> age; This will be equivalent to the following two statements − cin >> name; cin >> age; The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately. The cerr is also used in conjunction with the stream insertion operator as shown in the following example. #include <iostream> using namespace std; int main() { char str[] = "Unable to read...."; cerr << "Error message : " << str << endl; } When the above code is compiled and executed, it produces the following result − Error message : Unable to read.... The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed. The clog is also used in conjunction with the stream insertion operator as shown in the following example. #include <iostream> using namespace std; int main() { char str[] = "Unable to read...."; clog << "Error message : " << str << endl; } When the above code is compiled and executed, it produces the following result − Error message : Unable to read.... You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2539, "s": 2318, "text": "The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming." }, { "code": null, "e": 2891, "s": 2539, "text": "C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation." }, { "code": null, "e": 2952, "s": 2891, "text": "There are following header files important to C++ programs −" }, { "code": null, "e": 2963, "s": 2952, "text": "<iostream>" }, { "code": null, "e": 3186, "s": 2963, "text": "This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively." }, { "code": null, "e": 3196, "s": 3186, "text": "<iomanip>" }, { "code": null, "e": 3341, "s": 3196, "text": "This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision." }, { "code": null, "e": 3351, "s": 3341, "text": "<fstream>" }, { "code": null, "e": 3487, "s": 3351, "text": "This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter." }, { "code": null, "e": 3813, "s": 3487, "text": "The predefined object cout is an instance of ostream class. The cout object is said to be \"connected to\" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example." }, { "code": null, "e": 3952, "s": 3813, "text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Hello C++\";\n \n cout << \"Value of str is : \" << str << endl;\n}" }, { "code": null, "e": 4033, "s": 3952, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4062, "s": 4033, "text": "Value of str is : Hello C++\n" }, { "code": null, "e": 4332, "s": 4062, "text": "The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values." }, { "code": null, "e": 4481, "s": 4332, "text": "The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line." }, { "code": null, "e": 4799, "s": 4481, "text": "The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example." }, { "code": null, "e": 4981, "s": 4799, "text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char name[50];\n \n cout << \"Please enter your name: \";\n cin >> name;\n cout << \"Your name is: \" << name << endl;\n \n}" }, { "code": null, "e": 5130, "s": 4981, "text": "When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −" }, { "code": null, "e": 5189, "s": 5130, "text": "Please enter your name: cplusplus\nYour name is: cplusplus\n" }, { "code": null, "e": 5370, "s": 5189, "text": "The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables." }, { "code": null, "e": 5513, "s": 5370, "text": "The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −" }, { "code": null, "e": 5534, "s": 5513, "text": "cin >> name >> age;\n" }, { "code": null, "e": 5592, "s": 5534, "text": "This will be equivalent to the following two statements −" }, { "code": null, "e": 5618, "s": 5592, "text": "cin >> name;\ncin >> age;\n" }, { "code": null, "e": 5888, "s": 5618, "text": "The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately." }, { "code": null, "e": 5995, "s": 5888, "text": "The cerr is also used in conjunction with the stream insertion operator as shown in the following example." }, { "code": null, "e": 6141, "s": 5995, "text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Unable to read....\";\n \n cerr << \"Error message : \" << str << endl;\n}" }, { "code": null, "e": 6222, "s": 6141, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6258, "s": 6222, "text": "Error message : Unable to read....\n" }, { "code": null, "e": 6595, "s": 6258, "text": "The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed." }, { "code": null, "e": 6702, "s": 6595, "text": "The clog is also used in conjunction with the stream insertion operator as shown in the following example." }, { "code": null, "e": 6848, "s": 6702, "text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Unable to read....\";\n \n clog << \"Error message : \" << str << endl;\n}" }, { "code": null, "e": 6929, "s": 6848, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6965, "s": 6929, "text": "Error message : Unable to read....\n" }, { "code": null, "e": 7269, "s": 6965, "text": "You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used." }, { "code": null, "e": 7306, "s": 7269, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 7325, "s": 7306, "text": " Arnab Chakraborty" }, { "code": null, "e": 7357, "s": 7325, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 7380, "s": 7357, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7416, "s": 7380, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 7433, "s": 7416, "text": " Frahaan Hussain" }, { "code": null, "e": 7468, "s": 7433, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7485, "s": 7468, "text": " Frahaan Hussain" }, { "code": null, "e": 7520, "s": 7485, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7537, "s": 7520, "text": " Frahaan Hussain" }, { "code": null, "e": 7572, "s": 7537, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7589, "s": 7572, "text": " Frahaan Hussain" }, { "code": null, "e": 7596, "s": 7589, "text": " Print" }, { "code": null, "e": 7607, "s": 7596, "text": " Add Notes" } ]
Is there any way to check if there is a null value in an object or array in JavaScript?
To check if there is a null value in an object or array, use the concept of includes(). Following is the code − var nameArray1 = ["John", "David", "Mike", "Sam", null]; if (nameArray1.includes(null) == true) { console.log("array1 contains null value"); } else { console.log("array1 does not contains null value"); } var nameArray2 = ["Adam", "Bob", "Robert"]; if (nameArray2.includes(null) == true) { console.log("array2 contains null value"); } else { console.log("array2 does not contains null value"); } var objectData = { name: null }; if (Object.values(objectData).includes(null)) { console.log("object contains null value"); } else { console.log("object does not contains null value"); } To run the above program, you need to use the below command − node fileName.js. Here, my file name is demo314.js. This will produce the following output − PS C:\Users\Amit\javascript-code> node demo314.js array1 contains null value array2 does not contains null value object contains null value
[ { "code": null, "e": 1150, "s": 1062, "text": "To check if there is a null value in an object or array, use the concept of includes()." }, { "code": null, "e": 1174, "s": 1150, "text": "Following is the code −" }, { "code": null, "e": 1780, "s": 1174, "text": "var nameArray1 = [\"John\", \"David\", \"Mike\", \"Sam\", null];\nif (nameArray1.includes(null) == true) {\n console.log(\"array1 contains null value\");\n} else {\n console.log(\"array1 does not contains null value\");\n}\nvar nameArray2 = [\"Adam\", \"Bob\", \"Robert\"];\nif (nameArray2.includes(null) == true) {\n console.log(\"array2 contains null value\");\n} else {\n console.log(\"array2 does not contains null value\");\n}\nvar objectData = { name: null };\nif (Object.values(objectData).includes(null)) {\n console.log(\"object contains null value\");\n } else {\n console.log(\"object does not contains null value\");\n}" }, { "code": null, "e": 1842, "s": 1780, "text": "To run the above program, you need to use the below command −" }, { "code": null, "e": 1860, "s": 1842, "text": "node fileName.js." }, { "code": null, "e": 1894, "s": 1860, "text": "Here, my file name is demo314.js." }, { "code": null, "e": 1935, "s": 1894, "text": "This will produce the following output −" }, { "code": null, "e": 2075, "s": 1935, "text": "PS C:\\Users\\Amit\\javascript-code> node demo314.js\narray1 contains null value\narray2 does not contains null value\nobject contains null value" } ]
Data Visualization with Bokeh in Python, Part III: Making a Complete Dashboard | by Will Koehrsen | Towards Data Science
Creating an interactive visualization application in Bokeh Sometimes I learn a data science technique to solve a specific problem. Other times, as with Bokeh, I try out a new tool because I see some cool projects on Twitter and think: “That looks pretty neat. I’m not sure when I’ll use it, but it could come in handy.” Nearly every time I say this, I end up finding a use for the tool. Data science requires knowledge of many different skills and you never know where that next idea you will use will come from! In the case of Bokeh, several weeks after trying it out, I found a perfect use case in my work as a data science researcher. My research project involves increasing the energy efficiency of commercial buildings using data science, and, for a recent conference, we needed a way to show off the results of the many techniques we apply. The usual suggestion of a powerpoint gets the job done, but doesn’t really stand out. By the time most people at a conference see their third slide deck, they have already stopped paying attention. Although I didn’t yet know Bokeh very well, I volunteered to try and make an interactive application with the library, thinking it would allow me to expand my skill-set and create an engaging way to show off our project. Skeptical, our team prepared a back-up presentation, but after I showed them some prototypes, they gave it their full support. The final interactive dashboard was a stand-out at the conference and will be adopted by our team for future use: While not every idea you see on Twitter is probably going to be helpful to your career, I think it’s safe to say that knowing more data science techniques can’t possibly hurt. Along these lines, I started this series to share the capabilities of Bokeh, a powerful plotting library in Python that allows you to make interactive plots and dashboards. Although I can’t share the dashboard for my research, I can show the basics of building visualizations in Bokeh using a publicly available dataset. This third post is a continuation of my Bokeh series, with Part I focused on building a simple graph, and Part II showing how to add interactions to a Bokeh plot. In this post, we will see how to set up a full Bokeh application and run a local Bokeh server accessible in your browser! This article will focus on the structure of a Bokeh application rather than the plot details, but the full code for everything can be found on GitHub. We will continue to use the NYCFlights13 dataset, a real collection of flight information from flights departing 3 NYC airports in 2013. There are over 300,000 flights in the dataset, and for our dashboard, we will focus primarily on exploring the arrival delay information. To run the full application for yourself, make sure you have Bokeh installed ( using pip install bokeh), download the bokeh_app.zip folder from GitHub, unzip it, open a command window in the directory, and type bokeh serve --show bokeh_app. This will set-up a local Bokeh server and open the application in your browser (you can also make Bokeh plots available publicly online, but for now we will stick to local hosting). Before we get into the details, let’s take a look at the end product we’re aiming for so we can see how the pieces fit together. Following is a short clip showing how we can interact with the complete dashboard: Here I am using the Bokeh application in a browser (in Chrome’s fullscreen mode) that is running on a local server. At the top we see a number of tabs, each of which contains a different section of the application. The idea of a dashboard is that while each tab can stand on its own, we can join many of them together to enable a complete exploration of the data. The video shows the range of charts we can make with Bokeh, from histograms and density plots, to data tables that we can sort by column, to fully interactive maps. Besides the range of figures we can create in Bokeh, another benefit of using this library is interactions. Each tab has an interactive element which lets users engage with the data and make their own discoveries. From experience, when exploring a dataset, people like to come to insights on their own, which we can allow by letting them select and filter data through various controls. Now that we have an idea of the dashboard we are aiming for, let’s take a look at how to create a Bokeh application. I highly recommend downloading the code for yourself to follow along! Before writing any code, it’s important to establish a framework for our application. In any project, it’s easy to get carried away coding and soon become lost in a mess of half-finished scripts and out-of-place data files, so we want to create a structure beforehand for all our codes and data to slot into. This organization will help us keep track of all the elements in our application and assist in debugging when things inevitably go wrong. Also, we can re-use this framework for future projects so our initial investment in the planning stage will pay off down the road. To set up a Bokeh application, I create one parent directory to hold everything called bokeh_app . Within this directory, we will have a sub-directory for our data (called data), a sub-directory for our scripts (scripts), and a main.py script to pull everything together. Generally, to manage all the code, I have found it best to keep the code for each tab in a separate Python script and call them all from a single main script. Following is the file structure I use for a Bokeh application, adapted from the official documentation. bokeh_app|+--- data| +--- info.csv| +--- info2.csv|+--- scripts| +--- plot.py| +--- plot2.py|+--- main.py For the flights application, the structure follows the general outline: There are three main parts: data, scripts, and main.py, under one parentbokeh_app directory. When it comes time to run the server, we tell Bokeh to serve the bokeh_app directory and it will automatically search for and run the main.py script. With the general structure in place, let’s take a look at main.py which is what I like to call the executive of the Bokeh application (not a technical term)! The main.py script is like the executive of a Bokeh application. It loads in the data, passes it out to the other scripts, gets back the resulting plots, and organizes them into one single display. This will be the only script I show in its entirety because of how critical it is to the application: We start out with the necessary imports including the functions to make the tabs, each of which is stored in a separate script within the scripts directory. If you look at the file structure, notice that there is an __init__.py file in the scripts directory. This is a completely blank file that needs to be placed in the directory to allow us to import the appropriate functions using relative statements (e.g. from scripts.histogram import histogram_tab ). I’m not quite sure why this is needed, but it works (here’s the Stack Overflow answer I used to figure this out). After the library and script imports, we read in the necessary data with help from the Python __file__ attribute. In this case, we are using two pandas dataframes ( flights and map_data ) as well as US states data that is included in Bokeh. Once the data has been read in, the script proceeds to delegation: it passes the appropriate data to each function, the functions each draw and return a tab, and the main script organizes all these tabs in a single layout called tabs. As an example of what each of these separate tab functions does, let’s look at the function that draws the map_tab. This function takes in map_data (a formatted version of the flights data) and the US state data and produces a map of flight routes for selected airlines: We covered interactive plots in Part II of this series, and this plot is just an implementation of that idea. The overall structure of the function is: def map_tab(map_data, states): ... def make_dataset(airline_list): ... return new_src def make_plot(src): ... return p def update(attr, old, new): ... new_src = make_dataset(airline_list) src.data.update(new_src.data) controls = ... tab = Panel(child = layout, title = 'Flight Map') return tab We see the familiar make_dataset, make_plot, and update functions used to draw the plot with interactive controls. Once we have the plot set up, the final line returns the entire plot to the main script. Each individual script (there are 5 for the 5 tabs) follows the same pattern. Returning to the main script, the final touch is to gather the tabs and add them to a single document. # Put all the tabs into one applicationtabs = Tabs(tabs = [tab1, tab2, tab3, tab4, tab5])# Put the tabs in the current document for displaycurdoc().add_root(tabs) The tabs appear at the top of the application, and much like tabs in any browser, we can easily switch between them to explore the data. After all the set-up and coding required to make the plots, running the Bokeh server locally is quite simple. We open up a command line interface (I prefer Git Bash but any one will work), change to the directory containing bokeh_app and run bokeh serve --show bokeh_app. Assuming everything is coded correctly, the application will automatically open in our browser at the address http://localhost:5006/bokeh_app. We can then access the application and explore our dashboard! If something goes wrong (as it undoubtedly will the first few times we write a dashboard) it can be frustrating to have to stop the server, make changes to the files, and restart the server to see if our changes had the desired effect. To quickly iterate and resolve problems, I generally develop plots in a Jupyter Notebook. The Jupyter Notebook is a great environment for Bokeh development because you can create and test fully interactive plots from within the notebook. The syntax is a little different, but once you have a completed plot, the code just needs to be slightly modified and can then be copied and pasted into a standalone .py script. To see this in action, take a look at the Jupyter Notebook I used to develop the application. A fully interactive Bokeh dashboard makes any data science project stand out. Oftentimes, I see my colleagues do a lot of great statistical work but then fail to clearly communicate the results, which means all that work doesn’t get the recognition it deserves. From personal experience, I have also seen how effective Bokeh applications can be in communicating results. While making a full dashboard is a lot of work (this one is over 600 lines of code!) the results are worthwhile. Moreover, once we have an application, we can quickly share it using GitHub and if we are smart about our structure, we can re-use the framework for additional projects. The key points to take away from this project are applicable to many data science projects in general: Having the proper framework/structure in place before you start on a data science task — Bokeh or anything else — is crucial. This way, you won’t find yourself lost in a forest of code trying to find errors. Also, once we develop a framework that works, it can be re-used with minimal effort, leading to dividends far down the road.Finding a debugging cycle that allows you to quickly iterate through ideas is crucial. The write code —see results — fix errors loop allowed by the Jupyter Notebook makes for a productive development cycle (at least for small scale projects).Interactive applications in Bokeh will elevate your project and encourage user engagement. A dashboard can be a stand alone exploratory project, or highlight all the tough analysis work you’ve already done!You never know where you will find the next tool you will use in your work or side projects. Keep your eyes open, and don’t be afraid to experiment with new software and techniques! Having the proper framework/structure in place before you start on a data science task — Bokeh or anything else — is crucial. This way, you won’t find yourself lost in a forest of code trying to find errors. Also, once we develop a framework that works, it can be re-used with minimal effort, leading to dividends far down the road. Finding a debugging cycle that allows you to quickly iterate through ideas is crucial. The write code —see results — fix errors loop allowed by the Jupyter Notebook makes for a productive development cycle (at least for small scale projects). Interactive applications in Bokeh will elevate your project and encourage user engagement. A dashboard can be a stand alone exploratory project, or highlight all the tough analysis work you’ve already done! You never know where you will find the next tool you will use in your work or side projects. Keep your eyes open, and don’t be afraid to experiment with new software and techniques! That’s all for this post and for this series, although I plan on releasing additional stand-alone tutorials on Bokeh in the future. With libraries like Bokeh and plot.ly it’s becoming easier to make interactive figures and having a way to present your data science results in a compelling manner is crucial. Check out this Bokeh GitHub repo for all my work and feel free to fork and get started with your own projects. For now, I’m eager to see what everyone else can create! As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 231, "s": 172, "text": "Creating an interactive visualization application in Bokeh" }, { "code": null, "e": 685, "s": 231, "text": "Sometimes I learn a data science technique to solve a specific problem. Other times, as with Bokeh, I try out a new tool because I see some cool projects on Twitter and think: “That looks pretty neat. I’m not sure when I’ll use it, but it could come in handy.” Nearly every time I say this, I end up finding a use for the tool. Data science requires knowledge of many different skills and you never know where that next idea you will use will come from!" }, { "code": null, "e": 1679, "s": 685, "text": "In the case of Bokeh, several weeks after trying it out, I found a perfect use case in my work as a data science researcher. My research project involves increasing the energy efficiency of commercial buildings using data science, and, for a recent conference, we needed a way to show off the results of the many techniques we apply. The usual suggestion of a powerpoint gets the job done, but doesn’t really stand out. By the time most people at a conference see their third slide deck, they have already stopped paying attention. Although I didn’t yet know Bokeh very well, I volunteered to try and make an interactive application with the library, thinking it would allow me to expand my skill-set and create an engaging way to show off our project. Skeptical, our team prepared a back-up presentation, but after I showed them some prototypes, they gave it their full support. The final interactive dashboard was a stand-out at the conference and will be adopted by our team for future use:" }, { "code": null, "e": 2461, "s": 1679, "text": "While not every idea you see on Twitter is probably going to be helpful to your career, I think it’s safe to say that knowing more data science techniques can’t possibly hurt. Along these lines, I started this series to share the capabilities of Bokeh, a powerful plotting library in Python that allows you to make interactive plots and dashboards. Although I can’t share the dashboard for my research, I can show the basics of building visualizations in Bokeh using a publicly available dataset. This third post is a continuation of my Bokeh series, with Part I focused on building a simple graph, and Part II showing how to add interactions to a Bokeh plot. In this post, we will see how to set up a full Bokeh application and run a local Bokeh server accessible in your browser!" }, { "code": null, "e": 2887, "s": 2461, "text": "This article will focus on the structure of a Bokeh application rather than the plot details, but the full code for everything can be found on GitHub. We will continue to use the NYCFlights13 dataset, a real collection of flight information from flights departing 3 NYC airports in 2013. There are over 300,000 flights in the dataset, and for our dashboard, we will focus primarily on exploring the arrival delay information." }, { "code": null, "e": 3310, "s": 2887, "text": "To run the full application for yourself, make sure you have Bokeh installed ( using pip install bokeh), download the bokeh_app.zip folder from GitHub, unzip it, open a command window in the directory, and type bokeh serve --show bokeh_app. This will set-up a local Bokeh server and open the application in your browser (you can also make Bokeh plots available publicly online, but for now we will stick to local hosting)." }, { "code": null, "e": 3522, "s": 3310, "text": "Before we get into the details, let’s take a look at the end product we’re aiming for so we can see how the pieces fit together. Following is a short clip showing how we can interact with the complete dashboard:" }, { "code": null, "e": 4438, "s": 3522, "text": "Here I am using the Bokeh application in a browser (in Chrome’s fullscreen mode) that is running on a local server. At the top we see a number of tabs, each of which contains a different section of the application. The idea of a dashboard is that while each tab can stand on its own, we can join many of them together to enable a complete exploration of the data. The video shows the range of charts we can make with Bokeh, from histograms and density plots, to data tables that we can sort by column, to fully interactive maps. Besides the range of figures we can create in Bokeh, another benefit of using this library is interactions. Each tab has an interactive element which lets users engage with the data and make their own discoveries. From experience, when exploring a dataset, people like to come to insights on their own, which we can allow by letting them select and filter data through various controls." }, { "code": null, "e": 4625, "s": 4438, "text": "Now that we have an idea of the dashboard we are aiming for, let’s take a look at how to create a Bokeh application. I highly recommend downloading the code for yourself to follow along!" }, { "code": null, "e": 5203, "s": 4625, "text": "Before writing any code, it’s important to establish a framework for our application. In any project, it’s easy to get carried away coding and soon become lost in a mess of half-finished scripts and out-of-place data files, so we want to create a structure beforehand for all our codes and data to slot into. This organization will help us keep track of all the elements in our application and assist in debugging when things inevitably go wrong. Also, we can re-use this framework for future projects so our initial investment in the planning stage will pay off down the road." }, { "code": null, "e": 5738, "s": 5203, "text": "To set up a Bokeh application, I create one parent directory to hold everything called bokeh_app . Within this directory, we will have a sub-directory for our data (called data), a sub-directory for our scripts (scripts), and a main.py script to pull everything together. Generally, to manage all the code, I have found it best to keep the code for each tab in a separate Python script and call them all from a single main script. Following is the file structure I use for a Bokeh application, adapted from the official documentation." }, { "code": null, "e": 5852, "s": 5738, "text": "bokeh_app|+--- data| +--- info.csv| +--- info2.csv|+--- scripts| +--- plot.py| +--- plot2.py|+--- main.py" }, { "code": null, "e": 5924, "s": 5852, "text": "For the flights application, the structure follows the general outline:" }, { "code": null, "e": 6325, "s": 5924, "text": "There are three main parts: data, scripts, and main.py, under one parentbokeh_app directory. When it comes time to run the server, we tell Bokeh to serve the bokeh_app directory and it will automatically search for and run the main.py script. With the general structure in place, let’s take a look at main.py which is what I like to call the executive of the Bokeh application (not a technical term)!" }, { "code": null, "e": 6625, "s": 6325, "text": "The main.py script is like the executive of a Bokeh application. It loads in the data, passes it out to the other scripts, gets back the resulting plots, and organizes them into one single display. This will be the only script I show in its entirety because of how critical it is to the application:" }, { "code": null, "e": 7198, "s": 6625, "text": "We start out with the necessary imports including the functions to make the tabs, each of which is stored in a separate script within the scripts directory. If you look at the file structure, notice that there is an __init__.py file in the scripts directory. This is a completely blank file that needs to be placed in the directory to allow us to import the appropriate functions using relative statements (e.g. from scripts.histogram import histogram_tab ). I’m not quite sure why this is needed, but it works (here’s the Stack Overflow answer I used to figure this out)." }, { "code": null, "e": 7790, "s": 7198, "text": "After the library and script imports, we read in the necessary data with help from the Python __file__ attribute. In this case, we are using two pandas dataframes ( flights and map_data ) as well as US states data that is included in Bokeh. Once the data has been read in, the script proceeds to delegation: it passes the appropriate data to each function, the functions each draw and return a tab, and the main script organizes all these tabs in a single layout called tabs. As an example of what each of these separate tab functions does, let’s look at the function that draws the map_tab." }, { "code": null, "e": 7945, "s": 7790, "text": "This function takes in map_data (a formatted version of the flights data) and the US state data and produces a map of flight routes for selected airlines:" }, { "code": null, "e": 8097, "s": 7945, "text": "We covered interactive plots in Part II of this series, and this plot is just an implementation of that idea. The overall structure of the function is:" }, { "code": null, "e": 8445, "s": 8097, "text": "def map_tab(map_data, states): ... def make_dataset(airline_list): ... return new_src def make_plot(src): ... return p def update(attr, old, new): ... new_src = make_dataset(airline_list) src.data.update(new_src.data) controls = ... tab = Panel(child = layout, title = 'Flight Map') return tab" }, { "code": null, "e": 8727, "s": 8445, "text": "We see the familiar make_dataset, make_plot, and update functions used to draw the plot with interactive controls. Once we have the plot set up, the final line returns the entire plot to the main script. Each individual script (there are 5 for the 5 tabs) follows the same pattern." }, { "code": null, "e": 8830, "s": 8727, "text": "Returning to the main script, the final touch is to gather the tabs and add them to a single document." }, { "code": null, "e": 8993, "s": 8830, "text": "# Put all the tabs into one applicationtabs = Tabs(tabs = [tab1, tab2, tab3, tab4, tab5])# Put the tabs in the current document for displaycurdoc().add_root(tabs)" }, { "code": null, "e": 9130, "s": 8993, "text": "The tabs appear at the top of the application, and much like tabs in any browser, we can easily switch between them to explore the data." }, { "code": null, "e": 9607, "s": 9130, "text": "After all the set-up and coding required to make the plots, running the Bokeh server locally is quite simple. We open up a command line interface (I prefer Git Bash but any one will work), change to the directory containing bokeh_app and run bokeh serve --show bokeh_app. Assuming everything is coded correctly, the application will automatically open in our browser at the address http://localhost:5006/bokeh_app. We can then access the application and explore our dashboard!" }, { "code": null, "e": 10353, "s": 9607, "text": "If something goes wrong (as it undoubtedly will the first few times we write a dashboard) it can be frustrating to have to stop the server, make changes to the files, and restart the server to see if our changes had the desired effect. To quickly iterate and resolve problems, I generally develop plots in a Jupyter Notebook. The Jupyter Notebook is a great environment for Bokeh development because you can create and test fully interactive plots from within the notebook. The syntax is a little different, but once you have a completed plot, the code just needs to be slightly modified and can then be copied and pasted into a standalone .py script. To see this in action, take a look at the Jupyter Notebook I used to develop the application." }, { "code": null, "e": 11007, "s": 10353, "text": "A fully interactive Bokeh dashboard makes any data science project stand out. Oftentimes, I see my colleagues do a lot of great statistical work but then fail to clearly communicate the results, which means all that work doesn’t get the recognition it deserves. From personal experience, I have also seen how effective Bokeh applications can be in communicating results. While making a full dashboard is a lot of work (this one is over 600 lines of code!) the results are worthwhile. Moreover, once we have an application, we can quickly share it using GitHub and if we are smart about our structure, we can re-use the framework for additional projects." }, { "code": null, "e": 11110, "s": 11007, "text": "The key points to take away from this project are applicable to many data science projects in general:" }, { "code": null, "e": 12072, "s": 11110, "text": "Having the proper framework/structure in place before you start on a data science task — Bokeh or anything else — is crucial. This way, you won’t find yourself lost in a forest of code trying to find errors. Also, once we develop a framework that works, it can be re-used with minimal effort, leading to dividends far down the road.Finding a debugging cycle that allows you to quickly iterate through ideas is crucial. The write code —see results — fix errors loop allowed by the Jupyter Notebook makes for a productive development cycle (at least for small scale projects).Interactive applications in Bokeh will elevate your project and encourage user engagement. A dashboard can be a stand alone exploratory project, or highlight all the tough analysis work you’ve already done!You never know where you will find the next tool you will use in your work or side projects. Keep your eyes open, and don’t be afraid to experiment with new software and techniques!" }, { "code": null, "e": 12405, "s": 12072, "text": "Having the proper framework/structure in place before you start on a data science task — Bokeh or anything else — is crucial. This way, you won’t find yourself lost in a forest of code trying to find errors. Also, once we develop a framework that works, it can be re-used with minimal effort, leading to dividends far down the road." }, { "code": null, "e": 12648, "s": 12405, "text": "Finding a debugging cycle that allows you to quickly iterate through ideas is crucial. The write code —see results — fix errors loop allowed by the Jupyter Notebook makes for a productive development cycle (at least for small scale projects)." }, { "code": null, "e": 12855, "s": 12648, "text": "Interactive applications in Bokeh will elevate your project and encourage user engagement. A dashboard can be a stand alone exploratory project, or highlight all the tough analysis work you’ve already done!" }, { "code": null, "e": 13037, "s": 12855, "text": "You never know where you will find the next tool you will use in your work or side projects. Keep your eyes open, and don’t be afraid to experiment with new software and techniques!" }, { "code": null, "e": 13513, "s": 13037, "text": "That’s all for this post and for this series, although I plan on releasing additional stand-alone tutorials on Bokeh in the future. With libraries like Bokeh and plot.ly it’s becoming easier to make interactive figures and having a way to present your data science results in a compelling manner is crucial. Check out this Bokeh GitHub repo for all my work and feel free to fork and get started with your own projects. For now, I’m eager to see what everyone else can create!" } ]
C++ STL | Set 3 (map) | Practice | GeeksforGeeks
Implement different operations on maps. Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries . A query can be of three types 1. a x y (adds a value with key x and value y to the map) 2. b x (print value of x is present in the map else print -1. ) 3. c (prints values x and y separated by space i.e., contents of map) Output: The output for each test case will be space separated integers denoting the results of each query . Constraints: 1<=T<=100 1<=Q<=100 Example: Input 2 4 a 1 2 a 66 3 b 66 c 3 a 1 66 b 5 c Output 3 1 2 66 3 -1 1 66 Explanation : For the first test case There are four queries. Queries are performed in this order 1. a 1 2 --> map has a key 1 with value 2 2. a 66 3 --> map has a key 66 with value 3 3. b 66 --> prints the value of key 66 if its present in the map ie 3. 4. c --> print the contents of map separated by space ie ( 1 2 66 3 ) For the sec test case There are three queries. Queries are performed in this order 1. a 1 66 --> adds a key 1 with a value of 66 in the map 2. b 5 --> since the key 5 is not present in the map hence -1 is printed. 3. c --> prints contents of map separated by space ie(1 66) Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 deepaksahu424 This comment was deleted. 0 karntiwari3 months ago void add_value(map<int,int> &m,int x,int y){ //Your code here m[x] = y;} /* Returns the value of the keyx if present else returns -1 */int find_value(map<int,int> &m,int x){ //Your code here if(m.find(x)!=m.end()) return m[x]; return -1;} /* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &m){ //Your code here' for(auto x: m) { cout<<x.first<<" "<<x.second<<" "; }} 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.01 /* Adds a value with key x and value y to the map*/void add_value(map<int,int> &mp,int x,int y){ mp[x] = y;}/* Returns the value of the key x if present else returns -1 */int find_value(map<int,int> &mp, int x){ if(mp.find(x) != mp.end()) { return mp[x]; } return -1;}/* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &mp){ for(auto x: mp) { cout << x.first << " " << x.second << " "; }} 0 Amar Prakash1 year ago Amar Prakash void add_value(map<int,int> &m,int x,int y){ m[x] = y; //Your code here} /* Returns the value of the key x if present else returns -1 */int find_value(map<int,int> &m,int x){ if(m.find(x) != m.end()) { return m[x]; } return -1; //Your code here} /* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &m){ for( auto x : m) { cout<<x.first<<" "<<x.second<<"="" ";="" }="" your="" code="" here="" }=""> 0 penny53402 years ago penny5340 shortest sol ET= 0.01upvote me for more .https://ide.geeksforgeeks.o... 0 Ditikrushna Giri3 years ago Ditikrushna Giri Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed: Input:34b 27 b 43 b 36 a 21 49 c b 40 b 13 b 40 a 36 22 c c a 32 29 c c b 17 b 29 a 8 22 c a 6 43 b 42 a 21 23 c c b 48 c c a 26 13 b 30 c a 20 12 b 31 a 34 25 a 5 36 b 29 Its Correct output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 26 13 32 29 36 22 -1 -1 And Your Code's output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 26 13 32 29 36 22 -1 -1Need Help? What 's wrong with my output can anybody point it out ? 0 Deepak Yadav4 years ago Deepak Yadav see the logic of add_new_valuevoid add_value(map<int,int> &m,int x,int y){ pair<map<int,int>::iterator,bool> ret; ret=m.insert(pair<int,int>(x,y)); if(ret.second==false) { m[x]=y; }} 0 Dewanshu Singhal4 years ago Dewanshu Singhal In Test Case34b 27 b 43 b 36 a 21 49 c b 40 b 13 b 40 a 36 22 c c a 32 29 c c b 17 b 29 a 8 22 c a 6 43 b 42 a 21 23 c c b 48 c c a 26 13 b 30 c a 20 12 b 31 a 34 25 a 5 36 b 29 Its Correct output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 26 13 32 29 36 22 -1 -1 And My Code's Output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 26 13 32 29 36 22 -1 -1 First in test case it is inserting "a 21 49" and later again it is inserting "a 21 23". But in map we can not insert two values with same index. So a 21 23 will not get inserted in map. So how in Correct Output it is displaying 21 23?In my output it is displaying 21 49, which is think is correct 0 Naman Soni5 years ago Naman Soni http://ide.geeksforgeeks.or... What is wrong with my code?Giving the o/p as expected but wrong answer. 0 Quandray5 years ago Quandray The example input is missing a line. It should say24a 1 2 a 66 3 b 66 c3a 1 66 b 5 c 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": 898, "s": 238, "text": "Implement different operations on maps.\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of three types \n1. a x y (adds a value with key x and value y to the map)\n2. b x (print value of x is present in the map else print -1. )\n3. c (prints values x and y separated by space i.e., contents of map)\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:" }, { "code": null, "e": 970, "s": 898, "text": "Input\n2\n4\na 1 2 a 66 3 b 66 c\n3\na 1 66 b 5 c\n\nOutput\n3 1 2 66 3\n-1 1 66" }, { "code": null, "e": 1900, "s": 970, "text": "\nExplanation :\nFor the first test case\nThere are four queries. Queries are performed in this order\n1. a 1 2 --> map has a key 1 with value 2 \n2. a 66 3 --> map has a key 66 with value 3\n3. b 66 --> prints the value of key 66 if its present in the map ie 3.\n4. c --> print the contents of map separated by space ie ( 1 2 66 3 )\nFor the sec test case \nThere are three queries. Queries are performed in this order\n1. a 1 66 --> adds a key 1 with a value of 66 in the map\n2. b 5 --> since the key 5 is not present in the map hence -1 is printed.\n3. c --> prints contents of map separated by space ie(1 66)\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1902, "s": 1900, "text": "0" }, { "code": null, "e": 1916, "s": 1902, "text": "deepaksahu424" }, { "code": null, "e": 1942, "s": 1916, "text": "This comment was deleted." }, { "code": null, "e": 1944, "s": 1942, "text": "0" }, { "code": null, "e": 1967, "s": 1944, "text": "karntiwari3 months ago" }, { "code": null, "e": 2044, "s": 1967, "text": "void add_value(map<int,int> &m,int x,int y){ //Your code here m[x] = y;}" }, { "code": null, "e": 2210, "s": 2044, "text": "/* Returns the value of the keyx if present else returns -1 */int find_value(map<int,int> &m,int x){ //Your code here if(m.find(x)!=m.end()) return m[x]; return -1;}" }, { "code": null, "e": 2380, "s": 2210, "text": "/* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &m){ //Your code here' for(auto x: m) { cout<<x.first<<\" \"<<x.second<<\" \"; }}" }, { "code": null, "e": 2382, "s": 2380, "text": "0" }, { "code": null, "e": 2408, "s": 2382, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 2424, "s": 2408, "text": "Debojyoti Sinha" }, { "code": null, "e": 2473, "s": 2424, "text": "Correct Answer.Correct AnswerExecution Time:0.01" }, { "code": null, "e": 2936, "s": 2473, "text": "/* Adds a value with key x and value y to the map*/void add_value(map<int,int> &mp,int x,int y){ mp[x] = y;}/* Returns the value of the key x if present else returns -1 */int find_value(map<int,int> &mp, int x){ if(mp.find(x) != mp.end()) { return mp[x]; } return -1;}/* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &mp){ for(auto x: mp) { cout << x.first << \" \" << x.second << \" \"; }}" }, { "code": null, "e": 2938, "s": 2936, "text": "0" }, { "code": null, "e": 2961, "s": 2938, "text": "Amar Prakash1 year ago" }, { "code": null, "e": 2974, "s": 2961, "text": "Amar Prakash" }, { "code": null, "e": 3053, "s": 2974, "text": "void add_value(map<int,int> &m,int x,int y){ m[x] = y; //Your code here}" }, { "code": null, "e": 3246, "s": 3053, "text": "/* Returns the value of the key x if present else returns -1 */int find_value(map<int,int> &m,int x){ if(m.find(x) != m.end()) { return m[x]; } return -1; //Your code here}" }, { "code": null, "e": 3442, "s": 3246, "text": "/* Prints contents of the map ie keys and values*/void print_contents(map<int,int> &m){ for( auto x : m) { cout<<x.first<<\" \"<<x.second<<\"=\"\" \";=\"\" }=\"\" your=\"\" code=\"\" here=\"\" }=\"\">" }, { "code": null, "e": 3444, "s": 3442, "text": "0" }, { "code": null, "e": 3465, "s": 3444, "text": "penny53402 years ago" }, { "code": null, "e": 3475, "s": 3465, "text": "penny5340" }, { "code": null, "e": 3547, "s": 3475, "text": "shortest sol ET= 0.01upvote me for more .https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3549, "s": 3547, "text": "0" }, { "code": null, "e": 3577, "s": 3549, "text": "Ditikrushna Giri3 years ago" }, { "code": null, "e": 3594, "s": 3577, "text": "Ditikrushna Giri" }, { "code": null, "e": 3739, "s": 3594, "text": "Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:" }, { "code": null, "e": 3911, "s": 3739, "text": "Input:34b 27 b 43 b 36 a 21 49 c b 40 b 13 b 40 a 36 22 c c a 32 29 c c b 17 b 29 a 8 22 c a 6 43 b 42 a 21 23 c c b 48 c c a 26 13 b 30 c a 20 12 b 31 a 34 25 a 5 36 b 29" }, { "code": null, "e": 4207, "s": 3911, "text": "Its Correct output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 26 13 32 29 36 22 -1 -1" }, { "code": null, "e": 4517, "s": 4207, "text": "And Your Code's output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 26 13 32 29 36 22 -1 -1Need Help?" }, { "code": null, "e": 4574, "s": 4517, "text": "What 's wrong with my output can anybody point it out ?" }, { "code": null, "e": 4576, "s": 4574, "text": "0" }, { "code": null, "e": 4600, "s": 4576, "text": "Deepak Yadav4 years ago" }, { "code": null, "e": 4613, "s": 4600, "text": "Deepak Yadav" }, { "code": null, "e": 4818, "s": 4613, "text": "see the logic of add_new_valuevoid add_value(map<int,int> &m,int x,int y){ pair<map<int,int>::iterator,bool> ret; ret=m.insert(pair<int,int>(x,y)); if(ret.second==false) { m[x]=y; }}" }, { "code": null, "e": 4820, "s": 4818, "text": "0" }, { "code": null, "e": 4848, "s": 4820, "text": "Dewanshu Singhal4 years ago" }, { "code": null, "e": 4865, "s": 4848, "text": "Dewanshu Singhal" }, { "code": null, "e": 5043, "s": 4865, "text": "In Test Case34b 27 b 43 b 36 a 21 49 c b 40 b 13 b 40 a 36 22 c c a 32 29 c c b 17 b 29 a 8 22 c a 6 43 b 42 a 21 23 c c b 48 c c a 26 13 b 30 c a 20 12 b 31 a 34 25 a 5 36 b 29" }, { "code": null, "e": 5339, "s": 5043, "text": "Its Correct output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 32 29 36 22 6 43 8 22 21 23 32 29 36 22 -1 6 43 8 22 21 23 26 13 32 29 36 22 -1 -1" }, { "code": null, "e": 5637, "s": 5339, "text": "And My Code's Output is:-1 -1 -1 21 49 -1 -1 -1 21 49 36 22 21 49 36 22 21 49 32 29 36 22 21 49 32 29 36 22 -1 -1 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 32 29 36 22 6 43 8 22 21 49 32 29 36 22 -1 6 43 8 22 21 49 26 13 32 29 36 22 -1 -1" }, { "code": null, "e": 5935, "s": 5637, "text": "First in test case it is inserting \"a 21 49\" and later again it is inserting \"a 21 23\". But in map we can not insert two values with same index. So a 21 23 will not get inserted in map. So how in Correct Output it is displaying 21 23?In my output it is displaying 21 49, which is think is correct" }, { "code": null, "e": 5937, "s": 5935, "text": "0" }, { "code": null, "e": 5959, "s": 5937, "text": "Naman Soni5 years ago" }, { "code": null, "e": 5970, "s": 5959, "text": "Naman Soni" }, { "code": null, "e": 6001, "s": 5970, "text": "http://ide.geeksforgeeks.or..." }, { "code": null, "e": 6073, "s": 6001, "text": "What is wrong with my code?Giving the o/p as expected but wrong answer." }, { "code": null, "e": 6075, "s": 6073, "text": "0" }, { "code": null, "e": 6095, "s": 6075, "text": "Quandray5 years ago" }, { "code": null, "e": 6104, "s": 6095, "text": "Quandray" }, { "code": null, "e": 6189, "s": 6104, "text": "The example input is missing a line. It should say24a 1 2 a 66 3 b 66 c3a 1 66 b 5 c" }, { "code": null, "e": 6335, "s": 6189, "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": 6371, "s": 6335, "text": " Login to access your submissions. " }, { "code": null, "e": 6381, "s": 6371, "text": "\nProblem\n" }, { "code": null, "e": 6391, "s": 6381, "text": "\nContest\n" }, { "code": null, "e": 6454, "s": 6391, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6602, "s": 6454, "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": 6810, "s": 6602, "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": 6916, "s": 6810, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Pandas - Multi-index and groupbys - GeeksforGeeks
07 Mar, 2022 In this article, we will discuss Multi-index for Pandas Dataframe and Groupby operations . Multi-index allows you to select more than one row and column in your index. It is a multi-level or hierarchical object for pandas object. Now there are various methods of multi-index that are used such as MultiIndex.from_arrays, MultiIndex.from_tuples, MultiIndex.from_product, MultiIndex.from_frame, etc which helps us to create multiple indexes from arrays, tuples, dataframes, etc. Syntax: pandas.MultiIndex(levels=None, codes=None, sortorder=None, names=None, dtype=None, copy=False, name=None, verify_integrity=True) levels: It is a sequence of arrays which shows the unique labels for each level. codes: It is also a sequence of arrays where integers at each level helps us to designate the labels in that location. sortorder: optional int. It helps us to sort the levels lexicographically. dtype:data-type(size of the data which can be of 32 bits or 64 bits) copy: It is a boolean type parameter with default value as False. It helps us to copy the metadata. verify_integrity: It is a boolean type parameter with default value as True. It checks the integrity of the levels and codes i.t if they are valid. Let us see some examples to understand the concept better. Example 1: In this example, we will be creating multi-index from arrays. Arrays are preferred over tuples because tuples are immutable whereas if we want to change a value of an element in an array, we can do that. So let us move to the code and its explanation: After importing all the important libraries, we are creating an array of names along with arrays of marks and age respectively. Now with the help of MultiIndex.from_arrays, we are combining all the three arrays together such that elements from all the three arrays form multiple indexes together. After that, we are showing the above result. Python3 # importing pandas library from# pythonimport pandas as pd # Creating an array of namesarrays = ['Sohom','Suresh','kumkum','subrata'] # Creating an array of agesage= [10, 11, 12, 13] # Creating an array of marksmarks=[90,92,23,64] # Using MultiIndex.from_arrays, we are# combining the arrays together along# with their names and creating multi-index# with each element from the 3 arrays into# different rowspd.MultiIndex.from_arrays([arrays,age,marks], names=('names', 'age','marks')) Output: Example 2: In this example, we will be creating multi-index from dataframe using pandas. We will be creating manual data and then using pd.dataframe, we will create a dataframe with the set of data. Now using the Multi-index syntax we will create a multi-index with a dataframe. In this example, we are doing the same thing as the previous example. The difference is that, in the previous example, we were creating multi-Index from a list of arrays whereas over here we created a dataframe using pd.dataframe and after that, we are creating multi-index from that dataframe using multi-index.from_frame() along with the names. Python3 # importing pandas library from# pythonimport pandas as pd # Creating dataInformation = {'name': ["Saikat", "Shrestha", "Sandi", "Abinash"], 'Jobs': ["Software Developer", "System Engineer", "Footballer", "Singer"], 'Annual Salary(L.P.A)': [12.4, 5.6, 9.3, 10]} # Dataframing the whole datadf = pd.DataFrame(dict) # Showing the above dataprint(df) Output: Now using MultiIndex.from_frame , we are creating multiple indexes with this dataframe. Python3 # creating multiple indexes from# the dataframepd.MultiIndex.from_frame(df) Example 3: In this example we will be learning about dataframe.set_index([col1,col2,..]), where we will be learning about multiple indexes. This is another concept of multi-index. After importing the required library ie pandas we are creating data and then with the help of pandas.DataFrame we are converting it into a tabular format. After that using Dataframe.set_index we are setting some columns as the index columns(Multi-Index). Drop parameter is kept as false which will not drop the columns mentioned as index column and thereafter append parameter is used for appending passed columns to the already existing index columns. Python3 # importing the pandas libraryimport pandas as pd # making data for dataframingdata = { 'series': ['Peaky blinders', 'Sherlock', 'The crown', 'Queens Gambit', 'Friends'], 'Ratings': [4.5, 5, 3.9, 4.2, 5], 'Date': [2013, 2010, 2016, 2020, 1994]} # Dataframing the whole data createddf = pd.DataFrame(data) # setting first and the second name# as index columndf.set_index(["series", "Ratings"], inplace=True, append=True, drop=False)# display the dataframeprint(df) Output: Now, we are printing the index of dataframe in the form of multi-index. Python3 print(df.index) Output: A groupby operation in Pandas helps us to split the object by applying a function and there-after combine the results. After grouping the columns according to our choice, we can perform various operations which can eventually help us in the analysis of the data. Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True) by: It helps us to group by a specific or multiple columns in the dataframe. axis: It has a default value of 0 where 0 stands for index and 1 stands for columns. level: Let us consider that the dataframe we are working with has hierarchical indexing. In that case level helps us to determine the level of the index we are working with. as_index: It is a boolean data-type with default value as true.It returns object with group labels as index. sort: It helps us to sort the key values. It is preferable to keep it as false for better performance. group_keys: It is also a boolean value with default value as true. It adds group keys to indexes to identify pieces dropna: It helps to drop the ‘NA‘ values in a dataset Example 1: In the example below, we will be exploring the concepts of groupby using data created by us. Let us move into the code implementation. Python3 # importing pandas libraryimport numpy as np # Creating pandas dataframedf = pd.DataFrame( [ ("Corona Positive", 65, 99), ("Corona Negative", 52, 98.7), ("Corona Positive", 43, 100.1), ("Corona Positive", 26, 99.6), ("Corona Negative", 30, 98.1), ], index=["Patient 1", "Patient 2", "Patient 3", "Patient 4", "Patient 5"], columns=("Status", "Age(in Years)", "Temperature"),) # show dataframeprint(df) Output: Now let us group them according to some features: Python3 # Grouping with only statusgrouped1 = df.groupby("Status") # Grouping with temperature and statusgrouped3 = df.groupby(["Temperature", "Status"]) As we can see, we have grouped them according to ‘Status‘ and ‘Temperature and Status‘. Let us perform some functions now: Python3 # Finding the mean of the# patients reports according to# the statusgrouped1.mean() This will create the mean of the numerical values according to the ‘status‘. Python3 # Grouping temperature and status together# results in giving us the index values of# the particular patientgrouped3.groups Output: {(98.1, ‘Corona Negative’): [‘Patient 5’], (98.7, ‘Corona Negative’): [‘Patient 2’], (99.0, ‘Corona Positive’): [‘Patient 1’], (99.6, ‘Corona Positive’): [‘Patient 4’], (100.1, ‘Corona Positive’): [‘Patient 3’]} simranarora5sos Picked Python pandas-groupby Python pandas-indexing 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 ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n07 Mar, 2022" }, { "code": null, "e": 23992, "s": 23901, "text": "In this article, we will discuss Multi-index for Pandas Dataframe and Groupby operations ." }, { "code": null, "e": 24378, "s": 23992, "text": "Multi-index allows you to select more than one row and column in your index. It is a multi-level or hierarchical object for pandas object. Now there are various methods of multi-index that are used such as MultiIndex.from_arrays, MultiIndex.from_tuples, MultiIndex.from_product, MultiIndex.from_frame, etc which helps us to create multiple indexes from arrays, tuples, dataframes, etc." }, { "code": null, "e": 24515, "s": 24378, "text": "Syntax: pandas.MultiIndex(levels=None, codes=None, sortorder=None, names=None, dtype=None, copy=False, name=None, verify_integrity=True)" }, { "code": null, "e": 24596, "s": 24515, "text": "levels: It is a sequence of arrays which shows the unique labels for each level." }, { "code": null, "e": 24715, "s": 24596, "text": "codes: It is also a sequence of arrays where integers at each level helps us to designate the labels in that location." }, { "code": null, "e": 24790, "s": 24715, "text": "sortorder: optional int. It helps us to sort the levels lexicographically." }, { "code": null, "e": 24859, "s": 24790, "text": "dtype:data-type(size of the data which can be of 32 bits or 64 bits)" }, { "code": null, "e": 24959, "s": 24859, "text": "copy: It is a boolean type parameter with default value as False. It helps us to copy the metadata." }, { "code": null, "e": 25107, "s": 24959, "text": "verify_integrity: It is a boolean type parameter with default value as True. It checks the integrity of the levels and codes i.t if they are valid." }, { "code": null, "e": 25166, "s": 25107, "text": "Let us see some examples to understand the concept better." }, { "code": null, "e": 25177, "s": 25166, "text": "Example 1:" }, { "code": null, "e": 25429, "s": 25177, "text": "In this example, we will be creating multi-index from arrays. Arrays are preferred over tuples because tuples are immutable whereas if we want to change a value of an element in an array, we can do that. So let us move to the code and its explanation:" }, { "code": null, "e": 25771, "s": 25429, "text": "After importing all the important libraries, we are creating an array of names along with arrays of marks and age respectively. Now with the help of MultiIndex.from_arrays, we are combining all the three arrays together such that elements from all the three arrays form multiple indexes together. After that, we are showing the above result." }, { "code": null, "e": 25779, "s": 25771, "text": "Python3" }, { "code": "# importing pandas library from# pythonimport pandas as pd # Creating an array of namesarrays = ['Sohom','Suresh','kumkum','subrata'] # Creating an array of agesage= [10, 11, 12, 13] # Creating an array of marksmarks=[90,92,23,64] # Using MultiIndex.from_arrays, we are# combining the arrays together along# with their names and creating multi-index# with each element from the 3 arrays into# different rowspd.MultiIndex.from_arrays([arrays,age,marks], names=('names', 'age','marks'))", "e": 26264, "s": 25779, "text": null }, { "code": null, "e": 26276, "s": 26268, "text": "Output:" }, { "code": null, "e": 26291, "s": 26280, "text": "Example 2:" }, { "code": null, "e": 26562, "s": 26293, "text": "In this example, we will be creating multi-index from dataframe using pandas. We will be creating manual data and then using pd.dataframe, we will create a dataframe with the set of data. Now using the Multi-index syntax we will create a multi-index with a dataframe. " }, { "code": null, "e": 26912, "s": 26564, "text": "In this example, we are doing the same thing as the previous example. The difference is that, in the previous example, we were creating multi-Index from a list of arrays whereas over here we created a dataframe using pd.dataframe and after that, we are creating multi-index from that dataframe using multi-index.from_frame() along with the names. " }, { "code": null, "e": 26922, "s": 26914, "text": "Python3" }, { "code": "# importing pandas library from# pythonimport pandas as pd # Creating dataInformation = {'name': [\"Saikat\", \"Shrestha\", \"Sandi\", \"Abinash\"], 'Jobs': [\"Software Developer\", \"System Engineer\", \"Footballer\", \"Singer\"], 'Annual Salary(L.P.A)': [12.4, 5.6, 9.3, 10]} # Dataframing the whole datadf = pd.DataFrame(dict) # Showing the above dataprint(df)", "e": 27353, "s": 26922, "text": null }, { "code": null, "e": 27361, "s": 27353, "text": "Output:" }, { "code": null, "e": 27449, "s": 27361, "text": "Now using MultiIndex.from_frame , we are creating multiple indexes with this dataframe." }, { "code": null, "e": 27457, "s": 27449, "text": "Python3" }, { "code": "# creating multiple indexes from# the dataframepd.MultiIndex.from_frame(df)", "e": 27533, "s": 27457, "text": null }, { "code": null, "e": 27544, "s": 27533, "text": "Example 3:" }, { "code": null, "e": 27713, "s": 27544, "text": "In this example we will be learning about dataframe.set_index([col1,col2,..]), where we will be learning about multiple indexes. This is another concept of multi-index." }, { "code": null, "e": 28167, "s": 27713, "text": "After importing the required library ie pandas we are creating data and then with the help of pandas.DataFrame we are converting it into a tabular format. After that using Dataframe.set_index we are setting some columns as the index columns(Multi-Index). Drop parameter is kept as false which will not drop the columns mentioned as index column and thereafter append parameter is used for appending passed columns to the already existing index columns. " }, { "code": null, "e": 28175, "s": 28167, "text": "Python3" }, { "code": "# importing the pandas libraryimport pandas as pd # making data for dataframingdata = { 'series': ['Peaky blinders', 'Sherlock', 'The crown', 'Queens Gambit', 'Friends'], 'Ratings': [4.5, 5, 3.9, 4.2, 5], 'Date': [2013, 2010, 2016, 2020, 1994]} # Dataframing the whole data createddf = pd.DataFrame(data) # setting first and the second name# as index columndf.set_index([\"series\", \"Ratings\"], inplace=True, append=True, drop=False)# display the dataframeprint(df)", "e": 28684, "s": 28175, "text": null }, { "code": null, "e": 28692, "s": 28684, "text": "Output:" }, { "code": null, "e": 28764, "s": 28692, "text": "Now, we are printing the index of dataframe in the form of multi-index." }, { "code": null, "e": 28772, "s": 28764, "text": "Python3" }, { "code": "print(df.index)", "e": 28788, "s": 28772, "text": null }, { "code": null, "e": 28800, "s": 28792, "text": "Output:" }, { "code": null, "e": 29067, "s": 28804, "text": "A groupby operation in Pandas helps us to split the object by applying a function and there-after combine the results. After grouping the columns according to our choice, we can perform various operations which can eventually help us in the analysis of the data." }, { "code": null, "e": 29221, "s": 29069, "text": "Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)" }, { "code": null, "e": 29298, "s": 29221, "text": "by: It helps us to group by a specific or multiple columns in the dataframe." }, { "code": null, "e": 29383, "s": 29298, "text": "axis: It has a default value of 0 where 0 stands for index and 1 stands for columns." }, { "code": null, "e": 29557, "s": 29383, "text": "level: Let us consider that the dataframe we are working with has hierarchical indexing. In that case level helps us to determine the level of the index we are working with." }, { "code": null, "e": 29666, "s": 29557, "text": "as_index: It is a boolean data-type with default value as true.It returns object with group labels as index." }, { "code": null, "e": 29769, "s": 29666, "text": "sort: It helps us to sort the key values. It is preferable to keep it as false for better performance." }, { "code": null, "e": 29885, "s": 29769, "text": "group_keys: It is also a boolean value with default value as true. It adds group keys to indexes to identify pieces" }, { "code": null, "e": 29939, "s": 29885, "text": "dropna: It helps to drop the ‘NA‘ values in a dataset" }, { "code": null, "e": 29952, "s": 29941, "text": "Example 1:" }, { "code": null, "e": 30089, "s": 29954, "text": "In the example below, we will be exploring the concepts of groupby using data created by us. Let us move into the code implementation." }, { "code": null, "e": 30099, "s": 30091, "text": "Python3" }, { "code": "# importing pandas libraryimport numpy as np # Creating pandas dataframedf = pd.DataFrame( [ (\"Corona Positive\", 65, 99), (\"Corona Negative\", 52, 98.7), (\"Corona Positive\", 43, 100.1), (\"Corona Positive\", 26, 99.6), (\"Corona Negative\", 30, 98.1), ], index=[\"Patient 1\", \"Patient 2\", \"Patient 3\", \"Patient 4\", \"Patient 5\"], columns=(\"Status\", \"Age(in Years)\", \"Temperature\"),) # show dataframeprint(df)", "e": 30568, "s": 30099, "text": null }, { "code": null, "e": 30576, "s": 30568, "text": "Output:" }, { "code": null, "e": 30626, "s": 30576, "text": "Now let us group them according to some features:" }, { "code": null, "e": 30634, "s": 30626, "text": "Python3" }, { "code": "# Grouping with only statusgrouped1 = df.groupby(\"Status\") # Grouping with temperature and statusgrouped3 = df.groupby([\"Temperature\", \"Status\"])", "e": 30780, "s": 30634, "text": null }, { "code": null, "e": 30907, "s": 30784, "text": "As we can see, we have grouped them according to ‘Status‘ and ‘Temperature and Status‘. Let us perform some functions now:" }, { "code": null, "e": 30917, "s": 30909, "text": "Python3" }, { "code": "# Finding the mean of the# patients reports according to# the statusgrouped1.mean()", "e": 31001, "s": 30917, "text": null }, { "code": null, "e": 31082, "s": 31005, "text": "This will create the mean of the numerical values according to the ‘status‘." }, { "code": null, "e": 31094, "s": 31086, "text": "Python3" }, { "code": "# Grouping temperature and status together# results in giving us the index values of# the particular patientgrouped3.groups", "e": 31218, "s": 31094, "text": null }, { "code": null, "e": 31230, "s": 31222, "text": "Output:" }, { "code": null, "e": 31318, "s": 31232, "text": "{(98.1, ‘Corona Negative’): [‘Patient 5’], (98.7, ‘Corona Negative’): [‘Patient 2’], " }, { "code": null, "e": 31404, "s": 31318, "text": " (99.0, ‘Corona Positive’): [‘Patient 1’], (99.6, ‘Corona Positive’): [‘Patient 4’], " }, { "code": null, "e": 31448, "s": 31404, "text": " (100.1, ‘Corona Positive’): [‘Patient 3’]}" }, { "code": null, "e": 31466, "s": 31450, "text": "simranarora5sos" }, { "code": null, "e": 31473, "s": 31466, "text": "Picked" }, { "code": null, "e": 31495, "s": 31473, "text": "Python pandas-groupby" }, { "code": null, "e": 31518, "s": 31495, "text": "Python pandas-indexing" }, { "code": null, "e": 31532, "s": 31518, "text": "Python-pandas" }, { "code": null, "e": 31539, "s": 31532, "text": "Python" }, { "code": null, "e": 31637, "s": 31539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31646, "s": 31637, "text": "Comments" }, { "code": null, "e": 31659, "s": 31646, "text": "Old Comments" }, { "code": null, "e": 31691, "s": 31659, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31747, "s": 31691, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31789, "s": 31747, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31831, "s": 31789, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31867, "s": 31831, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 31889, "s": 31867, "text": "Defaultdict in Python" }, { "code": null, "e": 31928, "s": 31889, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31955, "s": 31928, "text": "Python Classes and Objects" }, { "code": null, "e": 31986, "s": 31955, "text": "Python | os.path.join() method" } ]
Angle between a chord and a tangent when angle in the alternate segment is given - GeeksforGeeks
10 Mar, 2021 Given a circle whose chord and tangent meet at a particular point. The angle in the alternate segment is given. The task here is to find the angle between the chord and the tangent.Examples: Input: z = 48 Output: 48 degrees Input: z = 64 Output: 64 degrees Approach: Let, angle BAC is the given angle in the alternate segment. let, the angle between the chord and circle = angle CBY = z as line drawn from center on the tangent is perpendicular, so, angle OBC = 90-z as, OB = OC = radius of the circle so, angle OCB = 90-z now, in triangle OBC, angle OBC + angle OCB + angle BOC = 180 angle BOC = 180 – (90-z) – (90-z) angle BOC = 2z as angle at the circumference of a circle is half the angle at the centre subtended by the same arc, so, angle BAC = z hence, angle BAC = angle CBY Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the angle// between a chord and a tangent// when angle in the alternate segment is given #include <bits/stdc++.h>using namespace std; void anglechordtang(int z){ cout << "The angle between tangent" << " and the chord is " << z << " degrees" << endl;} // Driver codeint main(){ int z = 48; anglechordtang(z); return 0;} // Java program to find the angle// between a chord and a tangent// when angle in the alternate segment is givenimport java.io.*; class GFG{ static void anglechordtang(int z) { System.out.print( "The angle between tangent" + " and the chord is " + z + " degrees"); } // Driver code public static void main (String[] args) { int z = 48; anglechordtang(z); }} // This code is contributed by anuj_67.. # Python3 program to find the angle# between a chord and a tangent# when angle in the alternate segment is givendef anglechordtang(z): print("The angle between tangent", "and the chord is", z , "degrees"); # Driver codez = 48;anglechordtang(z); # This code is contributed# by Princi Singh // C# program to find the angle// between a chord and a tangent// when angle in the alternate segment is givenusing System; class GFG{ static void anglechordtang(int z) { Console.WriteLine( "The angle between tangent" + " and the chord is " + z + " degrees"); } // Driver code public static void Main () { int z = 48; anglechordtang(z); }} // This code is contributed by anuj_67.. <script>// javascript program to find the angle// between a chord and a tangent// when angle in the alternate segment is given function anglechordtang(z){document.write( "The angle between tangent" + " and the chord is " + z + " degrees");} // Driver code var z = 48;anglechordtang(z); // This code is contributed by Amit Katiyar </script> The angle between tangent and the chord is 48 degrees vt_m princi singh amit143katiyar Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26707, "s": 26679, "text": "\n10 Mar, 2021" }, { "code": null, "e": 26900, "s": 26707, "text": "Given a circle whose chord and tangent meet at a particular point. The angle in the alternate segment is given. The task here is to find the angle between the chord and the tangent.Examples: " }, { "code": null, "e": 26967, "s": 26900, "text": "Input: z = 48\nOutput: 48 degrees\n\nInput: z = 64\nOutput: 64 degrees" }, { "code": null, "e": 26981, "s": 26969, "text": "Approach: " }, { "code": null, "e": 27041, "s": 26981, "text": "Let, angle BAC is the given angle in the alternate segment." }, { "code": null, "e": 27101, "s": 27041, "text": "let, the angle between the chord and circle = angle CBY = z" }, { "code": null, "e": 27160, "s": 27101, "text": "as line drawn from center on the tangent is perpendicular," }, { "code": null, "e": 27181, "s": 27160, "text": "so, angle OBC = 90-z" }, { "code": null, "e": 27216, "s": 27181, "text": "as, OB = OC = radius of the circle" }, { "code": null, "e": 27237, "s": 27216, "text": "so, angle OCB = 90-z" }, { "code": null, "e": 27348, "s": 27237, "text": "now, in triangle OBC, angle OBC + angle OCB + angle BOC = 180 angle BOC = 180 – (90-z) – (90-z) angle BOC = 2z" }, { "code": null, "e": 27467, "s": 27348, "text": "as angle at the circumference of a circle is half the angle at the centre subtended by the same arc, so, angle BAC = z" }, { "code": null, "e": 27496, "s": 27467, "text": "hence, angle BAC = angle CBY" }, { "code": null, "e": 27549, "s": 27496, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27553, "s": 27549, "text": "C++" }, { "code": null, "e": 27558, "s": 27553, "text": "Java" }, { "code": null, "e": 27566, "s": 27558, "text": "Python3" }, { "code": null, "e": 27569, "s": 27566, "text": "C#" }, { "code": null, "e": 27580, "s": 27569, "text": "Javascript" }, { "code": "// C++ program to find the angle// between a chord and a tangent// when angle in the alternate segment is given #include <bits/stdc++.h>using namespace std; void anglechordtang(int z){ cout << \"The angle between tangent\" << \" and the chord is \" << z << \" degrees\" << endl;} // Driver codeint main(){ int z = 48; anglechordtang(z); return 0;}", "e": 27950, "s": 27580, "text": null }, { "code": "// Java program to find the angle// between a chord and a tangent// when angle in the alternate segment is givenimport java.io.*; class GFG{ static void anglechordtang(int z) { System.out.print( \"The angle between tangent\" + \" and the chord is \" + z + \" degrees\"); } // Driver code public static void main (String[] args) { int z = 48; anglechordtang(z); }} // This code is contributed by anuj_67..", "e": 28419, "s": 27950, "text": null }, { "code": "# Python3 program to find the angle# between a chord and a tangent# when angle in the alternate segment is givendef anglechordtang(z): print(\"The angle between tangent\", \"and the chord is\", z , \"degrees\"); # Driver codez = 48;anglechordtang(z); # This code is contributed# by Princi Singh", "e": 28721, "s": 28419, "text": null }, { "code": "// C# program to find the angle// between a chord and a tangent// when angle in the alternate segment is givenusing System; class GFG{ static void anglechordtang(int z) { Console.WriteLine( \"The angle between tangent\" + \" and the chord is \" + z + \" degrees\"); } // Driver code public static void Main () { int z = 48; anglechordtang(z); }} // This code is contributed by anuj_67..", "e": 29172, "s": 28721, "text": null }, { "code": "<script>// javascript program to find the angle// between a chord and a tangent// when angle in the alternate segment is given function anglechordtang(z){document.write( \"The angle between tangent\" + \" and the chord is \" + z + \" degrees\");} // Driver code var z = 48;anglechordtang(z); // This code is contributed by Amit Katiyar </script>", "e": 29540, "s": 29172, "text": null }, { "code": null, "e": 29594, "s": 29540, "text": "The angle between tangent and the chord is 48 degrees" }, { "code": null, "e": 29601, "s": 29596, "text": "vt_m" }, { "code": null, "e": 29614, "s": 29601, "text": "princi singh" }, { "code": null, "e": 29629, "s": 29614, "text": "amit143katiyar" }, { "code": null, "e": 29639, "s": 29629, "text": "Geometric" }, { "code": null, "e": 29652, "s": 29639, "text": "Mathematical" }, { "code": null, "e": 29665, "s": 29652, "text": "Mathematical" }, { "code": null, "e": 29675, "s": 29665, "text": "Geometric" }, { "code": null, "e": 29773, "s": 29675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29822, "s": 29773, "text": "Program for distance between two points on earth" }, { "code": null, "e": 29875, "s": 29822, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 29926, "s": 29875, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 29960, "s": 29926, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 30018, "s": 29960, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 30048, "s": 30018, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30108, "s": 30048, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30123, "s": 30108, "text": "C++ Data Types" }, { "code": null, "e": 30166, "s": 30123, "text": "Set in C++ Standard Template Library (STL)" } ]
How To Convert Data Types in Python 3? - GeeksforGeeks
25 Aug, 2021 Prerequisites: Python Data Types Type conversion is the process of converting one data type to another. There can be two types of type conversion in Python – Implicit Type Conversion Explicit Type Conversion It is a type of type conversion in which handles automatically convert one data type to another without any user involvement. Example: Python3 # Python program to demonstrate# implicit type conversion # Python automatically converts# a to inta = 5print(type(a)) # Python automatically converts# b to floatb = 1.0print(type(b)) # Python automatically converts# c to int as it is a floor divisionc = a//bprint(c)print(type(c)) Output: <class 'int'> <class 'float'> 5.0 <class 'float'> In the above example, it can be seen that Python handles all the type conversion automatically without any user involvement. In Explicit type conversion, user involvement is required. The user converts one data type to another according to his own need. This can be done with the help of str(), int(), float(), etc. functions. Let’s see the handling of various type conversions. A string is generally a sequence of one or more characters. We are often required to convert string to numbers and vice versa. Let’s see each of them in detail. A number can be converted to string using the str() function. To do this pass a number or a variable containing the numeric value to this function. Example: Python3 # Python program to demonstrate# type conversion of number to# string a = 10 # Converting number to strings = str(a)print(s)print(type(s)) Output: 10 <class 'str'> This can be useful when we want to print some string containing a number to the console. Consider the below example. Example: Python3 s = "GFG"n = 50 print("String: " + s + "\nNumber: " + str(n)) Output: String: GFG Number: 50 A string can be converted to a number using int() or float() method. To do this pass a valid string containing the numerical value to either of these functions (depending upon the need). Note: If A string containing not containing a numeric value is passed then an error is raised. Example: Python3 # Python program to demonstrate# type conversion of string to# number s = '50' # Converting to intn = int(s)print(n)print(type(n)) # Converting to floatf = float(s)print(f)print(type(f)) Output: 50 <class 'int'> 50.0 <class 'float'> There are basically two types of numbers in Python – integers and floating-point numbers. Weare often required to change from one type to another. Let’s see their conversion in detail. A floating-point can be converted to an integer using the int() function. To do this pass a floating-point inside the int() method. Example: Python3 # Python program to demonstrate# floating point to integer f = 10.0 # Converting to integern = int(f)print(n)print(type(n)) Output: 10 <class 'int'> An integer can be converted to float using the float() method. To do this pass an integer inside the float() method. Example: Python3 # Python program to demonstrate# integer to float n = 10 # Converting to floatf = float(n)print(f)print(type(f)) Output: 10.0 <class 'float'> In Python, Both tuple and list can be converted to one another. It can be done by using the tuple() and list() method. See the below examples for better understanding. Example: Python3 # Python program to demonstrate# type conversion between list# and tuples t = (1, 2, 3, 4)l = [5, 6, 7, 8] # Converting to tupleT = tuple(l)print(T)print(type(T)) # Converting to listL = list(t)print(L)print(type(L)) Output: (5, 6, 7, 8) <class 'tuple'> [1, 2, 3, 4] <class 'list'> ruhelaa48 sagar0719kumar Python-Data Type Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25952, "s": 25924, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25985, "s": 25952, "text": "Prerequisites: Python Data Types" }, { "code": null, "e": 26110, "s": 25985, "text": "Type conversion is the process of converting one data type to another. There can be two types of type conversion in Python –" }, { "code": null, "e": 26135, "s": 26110, "text": "Implicit Type Conversion" }, { "code": null, "e": 26160, "s": 26135, "text": "Explicit Type Conversion" }, { "code": null, "e": 26286, "s": 26160, "text": "It is a type of type conversion in which handles automatically convert one data type to another without any user involvement." }, { "code": null, "e": 26295, "s": 26286, "text": "Example:" }, { "code": null, "e": 26303, "s": 26295, "text": "Python3" }, { "code": "# Python program to demonstrate# implicit type conversion # Python automatically converts# a to inta = 5print(type(a)) # Python automatically converts# b to floatb = 1.0print(type(b)) # Python automatically converts# c to int as it is a floor divisionc = a//bprint(c)print(type(c))", "e": 26585, "s": 26303, "text": null }, { "code": null, "e": 26593, "s": 26585, "text": "Output:" }, { "code": null, "e": 26643, "s": 26593, "text": "<class 'int'>\n<class 'float'>\n5.0\n<class 'float'>" }, { "code": null, "e": 26768, "s": 26643, "text": "In the above example, it can be seen that Python handles all the type conversion automatically without any user involvement." }, { "code": null, "e": 27022, "s": 26768, "text": "In Explicit type conversion, user involvement is required. The user converts one data type to another according to his own need. This can be done with the help of str(), int(), float(), etc. functions. Let’s see the handling of various type conversions." }, { "code": null, "e": 27183, "s": 27022, "text": "A string is generally a sequence of one or more characters. We are often required to convert string to numbers and vice versa. Let’s see each of them in detail." }, { "code": null, "e": 27331, "s": 27183, "text": "A number can be converted to string using the str() function. To do this pass a number or a variable containing the numeric value to this function." }, { "code": null, "e": 27340, "s": 27331, "text": "Example:" }, { "code": null, "e": 27348, "s": 27340, "text": "Python3" }, { "code": "# Python program to demonstrate# type conversion of number to# string a = 10 # Converting number to strings = str(a)print(s)print(type(s))", "e": 27487, "s": 27348, "text": null }, { "code": null, "e": 27495, "s": 27487, "text": "Output:" }, { "code": null, "e": 27512, "s": 27495, "text": "10\n<class 'str'>" }, { "code": null, "e": 27629, "s": 27512, "text": "This can be useful when we want to print some string containing a number to the console. Consider the below example." }, { "code": null, "e": 27638, "s": 27629, "text": "Example:" }, { "code": null, "e": 27646, "s": 27638, "text": "Python3" }, { "code": "s = \"GFG\"n = 50 print(\"String: \" + s + \"\\nNumber: \" + str(n))", "e": 27708, "s": 27646, "text": null }, { "code": null, "e": 27716, "s": 27708, "text": "Output:" }, { "code": null, "e": 27739, "s": 27716, "text": "String: GFG\nNumber: 50" }, { "code": null, "e": 27926, "s": 27739, "text": "A string can be converted to a number using int() or float() method. To do this pass a valid string containing the numerical value to either of these functions (depending upon the need)." }, { "code": null, "e": 28021, "s": 27926, "text": "Note: If A string containing not containing a numeric value is passed then an error is raised." }, { "code": null, "e": 28030, "s": 28021, "text": "Example:" }, { "code": null, "e": 28038, "s": 28030, "text": "Python3" }, { "code": "# Python program to demonstrate# type conversion of string to# number s = '50' # Converting to intn = int(s)print(n)print(type(n)) # Converting to floatf = float(s)print(f)print(type(f))", "e": 28225, "s": 28038, "text": null }, { "code": null, "e": 28233, "s": 28225, "text": "Output:" }, { "code": null, "e": 28271, "s": 28233, "text": "50\n<class 'int'>\n50.0\n<class 'float'>" }, { "code": null, "e": 28456, "s": 28271, "text": "There are basically two types of numbers in Python – integers and floating-point numbers. Weare often required to change from one type to another. Let’s see their conversion in detail." }, { "code": null, "e": 28588, "s": 28456, "text": "A floating-point can be converted to an integer using the int() function. To do this pass a floating-point inside the int() method." }, { "code": null, "e": 28597, "s": 28588, "text": "Example:" }, { "code": null, "e": 28605, "s": 28597, "text": "Python3" }, { "code": "# Python program to demonstrate# floating point to integer f = 10.0 # Converting to integern = int(f)print(n)print(type(n))", "e": 28729, "s": 28605, "text": null }, { "code": null, "e": 28737, "s": 28729, "text": "Output:" }, { "code": null, "e": 28754, "s": 28737, "text": "10\n<class 'int'>" }, { "code": null, "e": 28871, "s": 28754, "text": "An integer can be converted to float using the float() method. To do this pass an integer inside the float() method." }, { "code": null, "e": 28880, "s": 28871, "text": "Example:" }, { "code": null, "e": 28888, "s": 28880, "text": "Python3" }, { "code": "# Python program to demonstrate# integer to float n = 10 # Converting to floatf = float(n)print(f)print(type(f))", "e": 29001, "s": 28888, "text": null }, { "code": null, "e": 29009, "s": 29001, "text": "Output:" }, { "code": null, "e": 29030, "s": 29009, "text": "10.0\n<class 'float'>" }, { "code": null, "e": 29198, "s": 29030, "text": "In Python, Both tuple and list can be converted to one another. It can be done by using the tuple() and list() method. See the below examples for better understanding." }, { "code": null, "e": 29207, "s": 29198, "text": "Example:" }, { "code": null, "e": 29215, "s": 29207, "text": "Python3" }, { "code": "# Python program to demonstrate# type conversion between list# and tuples t = (1, 2, 3, 4)l = [5, 6, 7, 8] # Converting to tupleT = tuple(l)print(T)print(type(T)) # Converting to listL = list(t)print(L)print(type(L))", "e": 29432, "s": 29215, "text": null }, { "code": null, "e": 29440, "s": 29432, "text": "Output:" }, { "code": null, "e": 29497, "s": 29440, "text": "(5, 6, 7, 8)\n<class 'tuple'>\n[1, 2, 3, 4]\n<class 'list'>" }, { "code": null, "e": 29507, "s": 29497, "text": "ruhelaa48" }, { "code": null, "e": 29522, "s": 29507, "text": "sagar0719kumar" }, { "code": null, "e": 29539, "s": 29522, "text": "Python-Data Type" }, { "code": null, "e": 29546, "s": 29539, "text": "Python" }, { "code": null, "e": 29644, "s": 29546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29679, "s": 29644, "text": "Read a file line by line in Python" }, { "code": null, "e": 29711, "s": 29679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29733, "s": 29711, "text": "Enumerate() in Python" }, { "code": null, "e": 29775, "s": 29733, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29805, "s": 29775, "text": "Iterate over a list in Python" }, { "code": null, "e": 29831, "s": 29805, "text": "Python String | replace()" }, { "code": null, "e": 29875, "s": 29831, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29904, "s": 29875, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29941, "s": 29904, "text": "Create a Pandas DataFrame from Lists" } ]
Python program to remove the nth index character from a non-empty string - GeeksforGeeks
19 Dec, 2021 Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stable. Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approach uses a new string variable for storing the modified string. We keep a track of the characters of the string and as soon as we encounter a character at nth index, we don’t copy it to the modified string variable. Else, we copy it to a new variable. Python3 # declaring a string variablestr = "Geeksforgeeks is fun." # index to remove character atn = 4 # declaring an empty string variable for storing modified stringmodified_str = '' # iterating over the stringfor char in range(0, len(str)): # checking if the char index is equivalent to n if(char != n): # append original string character modified_str += str[char] print("Modified string after removing ", n, "th character ")print(modified_str) Output: Modified string after removing 4 th character Geekforgeeks is fun. Time Complexity = O(n), where n is the length of the string. Space Complexity = O(n) The second approach uses the idea of extraction of a sequence of characters within a range of index values. The syntax used in Python is as follows : string_name[start_index : end_index] – extracts the characters starting at start_index and less than end_index, that is, up to end_index-1. If we don’t specify the end_index, it computes till the length of the string. Therefore, we extract all the characters of a string in two parts, first until nth index and the other beginning with n+1th index. We then append these two parts together. Python3 # declaring a string variablestr = "Geeksforgeeks is fun." # index to remove character atn = 8 # extracts 0 to n-1th indexfirst_part = str[0:n] # extracts characters from n+1th index until the endsecond_part = str[n+1:]print("Modified string after removing ", n, "th character ") # combining both the parts togetherprint(first_part+second_part) Output: Modified string after removing 8 th character Geeksforeeks is fun. Time Complexity = O(n), where n is the length of the string. Space Complexity = O(n) kk9826225 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25647, "s": 25619, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25759, "s": 25647, "text": "Given a String, the task is to write a Python program to remove the nth index character from a non-empty string" }, { "code": null, "e": 25769, "s": 25759, "text": "Examples:" }, { "code": null, "e": 25939, "s": 25769, "text": "Input: str = \"Stable\"\nOutput: Modified string after removing 4 th character \nStable.\n \nInput: str = \"Arrow\"\nOutput: Modified string after removing 4 th character \nArro" }, { "code": null, "e": 26207, "s": 25939, "text": "The first approach uses a new string variable for storing the modified string. We keep a track of the characters of the string and as soon as we encounter a character at nth index, we don’t copy it to the modified string variable. Else, we copy it to a new variable. " }, { "code": null, "e": 26215, "s": 26207, "text": "Python3" }, { "code": "# declaring a string variablestr = \"Geeksforgeeks is fun.\" # index to remove character atn = 4 # declaring an empty string variable for storing modified stringmodified_str = '' # iterating over the stringfor char in range(0, len(str)): # checking if the char index is equivalent to n if(char != n): # append original string character modified_str += str[char] print(\"Modified string after removing \", n, \"th character \")print(modified_str)", "e": 26676, "s": 26215, "text": null }, { "code": null, "e": 26684, "s": 26676, "text": "Output:" }, { "code": null, "e": 26754, "s": 26684, "text": "Modified string after removing 4 th character \nGeekforgeeks is fun." }, { "code": null, "e": 26816, "s": 26754, "text": "Time Complexity = O(n), where n is the length of the string. " }, { "code": null, "e": 26840, "s": 26816, "text": "Space Complexity = O(n)" }, { "code": null, "e": 26991, "s": 26840, "text": "The second approach uses the idea of extraction of a sequence of characters within a range of index values. The syntax used in Python is as follows : " }, { "code": null, "e": 27209, "s": 26991, "text": "string_name[start_index : end_index] – extracts the characters starting at start_index and less than end_index, that is, up to end_index-1. If we don’t specify the end_index, it computes till the length of the string." }, { "code": null, "e": 27382, "s": 27209, "text": "Therefore, we extract all the characters of a string in two parts, first until nth index and the other beginning with n+1th index. We then append these two parts together. " }, { "code": null, "e": 27390, "s": 27382, "text": "Python3" }, { "code": "# declaring a string variablestr = \"Geeksforgeeks is fun.\" # index to remove character atn = 8 # extracts 0 to n-1th indexfirst_part = str[0:n] # extracts characters from n+1th index until the endsecond_part = str[n+1:]print(\"Modified string after removing \", n, \"th character \") # combining both the parts togetherprint(first_part+second_part)", "e": 27735, "s": 27390, "text": null }, { "code": null, "e": 27743, "s": 27735, "text": "Output:" }, { "code": null, "e": 27813, "s": 27743, "text": "Modified string after removing 8 th character \nGeeksforeeks is fun." }, { "code": null, "e": 27874, "s": 27813, "text": "Time Complexity = O(n), where n is the length of the string." }, { "code": null, "e": 27898, "s": 27874, "text": "Space Complexity = O(n)" }, { "code": null, "e": 27908, "s": 27898, "text": "kk9826225" }, { "code": null, "e": 27931, "s": 27908, "text": "Python string-programs" }, { "code": null, "e": 27938, "s": 27931, "text": "Python" }, { "code": null, "e": 27954, "s": 27938, "text": "Python Programs" }, { "code": null, "e": 28052, "s": 27954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28084, "s": 28052, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28126, "s": 28084, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28168, "s": 28126, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28224, "s": 28168, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28251, "s": 28224, "text": "Python Classes and Objects" }, { "code": null, "e": 28273, "s": 28251, "text": "Defaultdict in Python" }, { "code": null, "e": 28312, "s": 28273, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28358, "s": 28312, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28396, "s": 28358, "text": "Python | Convert a list to dictionary" } ]
Remove elements from a JavaScript Array - GeeksforGeeks
11 Aug, 2021 JavaScript array is a single variable that is used to store the elements or a group of values. You can add or remove elements from array in any position. In this article, we will discuss different ways to remove elements from array. There are many methods that is used to remove elements from JavaScript array which are discussed below: pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array. filter() function: This method is use to remove elements in programmatically way. Note: There are some other methods that are created by JavaScript inbuilt methods.Below examples illustrate the methods to remove elements from a JavaScript array:Remove Array elements by using pop() method: This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1. Example 1: javascript <script>// JavaScript code to illustrate pop() function// to remove array elements function func() { var arr = ["shift", "splice", "filter", "pop"]; // Popping the last element from the array var popped = arr.pop(); document.write("Removed element: " + popped + "<br>"); document.write("Remaining elements: " + arr);}func();</script> Output: Removed element: pop Remaining elements: shift, splice, filter Example 2: javascript <script>// Declare and initialize an arrayvar array = ["pop", "splice", "filter", "shift"] document.write("Original array: " + array + "<br>") // Loop run while array length not zerowhile (array.length) { // Remove elements from array array.pop();}document.write("Array Length: " + array.length ) </script> Output: Original array: pop, splice, filter, shift Array Length: 0 Remove Array elements by using shift() method: This method is used to remove the first element of the array and reducing the size of original array by 1. Example: javascript <script>// JavaScript code to illustrate shift() method// to remove elements from arrayfunction func() { var arr = ["shift", "splice", "filter", "pop"]; // Removing the first element from array var shifted = arr.shift(); document.write("Removed element: " + shifted + "<br>"); document.write("Remaining elements: " + arr);}func();</script> Output: Removed element: shift Remaining elements: splice, filter, pop Remove Array elements by using splice() method: This method is used to modify the contents of an array by removing the existing elements and/or by adding new elements. To remove elements by splice() method you can specify the elements in different ways. Example 1: Use the indexing of splice method to remove elements from a JavaScript array. javascript <script>// JavaScript code to illustrate splice() function function func() { var arr = ["shift", "splice", "filter", "pop"]; // Removing the specified element from the array var spliced = arr.splice(1, 1); document.write("Removed element: " + spliced + "<br>"); document.write("Remaining elements: " + arr);}func();</script> Output: Removed element: splice Remaining elements: shift, filter, pop Example 2: Using the value of splice method to remove elements from a JavaScript array. javascript <script> // JavaScript code to illustrate splice() functionfunction func() { var arr = ["shift", "splice", "filter", "pop"]; // Removing the specified element by value from the array for (var i = 0; i < arr.length; i++) { if (arr[i] === "splice") { var spliced = arr.splice(i, 1); document.write("Removed element: " + spliced + "<br>"); document.write("Remaining elements: " + arr); } }}func();</script> Output: Removed element: splice Remaining elements: shift, filter, pop Example 3: Using the splice method to remove each elements from a JavaScript array. javascript <script>// Declare and initialize arrayvar array = ["pop", "splice", "filter", "shift"] document.write("Original array: " + array + "<br>") // Making the length of array to 0 by using splice methodarray.splice(0, array.length);document.write("Empty array: " + array )</script> Output: Original array: pop, splice, filter, shift Empty array: Remove Array elements by using filter() method: This method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. To remove elements by filter() method you can specify the elements in different ways. Example: Use the value of filter method to remove elements from a JavaScript array. javascript <script> // JavaScript to illustrate filter() methodfunction isPositive( value ) { return value > 0;} function func() { var filtered = [101, 98, 12, -1, 848].filter( isPositive ); document.write("Positive elements in array: " + filtered);}func();</script> Output: Positive elements in array: 101, 98, 12, 848 Remove Array elements by using Remove Method: Creating a remove method using filter method to remove elements from a JavaScript array. This methods works in reverse order. Example: javascript <script> // Declare and initialize an arrayvar array = ["lowdash", "remove", "delete", "reset"] // Using filter method to create a remove methodfunction arrayRemove(arr, value) { return arr.filter(function(geeks){ return geeks != value; }); } var result = arrayRemove(array, "delete");document.write("Remaining elements: " + result)</script> Output: Remaining elements: lowdash, remove, reset Remove Array elements by Delete Operator: Use the delete operator to remove elements from a JavaScript array. Example: javascript <script> // Declare and initialize an arrayvar array = ["lowdash", "remove", "delete", "reset"] // Delete element at index 2var deleted = delete array[2]; document.write("Removed: " + deleted + "<br>");document.write("Remaining elements: " + array);</script> Output: Removed: true Remaining elements: lowdash, remove,,reset Remove Array elements by Clear and Reset Operator: Use clear and reset operator to remove elements from a JavaScript array. Example 1: javascript <script> // Declare and initialize an arrayvar array = ["lowdash", "remove", "delete", "reset"] // Sorting array in another arrayvar arraygeeks = array // Delete each element of arrayarray = []document.write("Empty array: " + array + "<br>")document.write("Original array: " + arraygeeks) </script> Output: Empty array: Original array: lowdash, remove, delete, reset Example 2: javascript <script> // Declare and initialize an arrayvar array = ["lowdash", "remove", "delete", "reset"] document.write("Original array: " + array + "<br>") // Making the array length to 0array.length = 0;document.write("Empty array: " + array ) </script> Output: Original array: lowdash, remove, delete, reset Empty array: Remove Array elements by lowdash library: Use the lowdash library to remove elements from a JavaScript array. To use lowdash library you need to install it locally on your system. Example: html <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"> // Declare and initialize an arrayvar array = [101, 98, 12, -1, 848];var evens= _.remove(array, function(n) { return n % 2 == 0;}); console.log("odd elements: " + array + "<br>");console.log("even elements: " + evens); </script> Output: odd elements: 101, -1 even elements: 98, 12, 848 gabaa406 javascript-array JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26032, "s": 26004, "text": "\n11 Aug, 2021" }, { "code": null, "e": 26371, "s": 26032, "text": "JavaScript array is a single variable that is used to store the elements or a group of values. You can add or remove elements from array in any position. In this article, we will discuss different ways to remove elements from array. There are many methods that is used to remove elements from JavaScript array which are discussed below: " }, { "code": null, "e": 26451, "s": 26371, "text": "pop() function: This method is use to remove elements from the end of an array." }, { "code": null, "e": 26535, "s": 26451, "text": "shift() function: This method is use to remove elements from the start of an array." }, { "code": null, "e": 26629, "s": 26535, "text": "splice() function: This method is use to remove elements from the specific index of an array." }, { "code": null, "e": 26711, "s": 26629, "text": "filter() function: This method is use to remove elements in programmatically way." }, { "code": null, "e": 27068, "s": 26711, "text": "Note: There are some other methods that are created by JavaScript inbuilt methods.Below examples illustrate the methods to remove elements from a JavaScript array:Remove Array elements by using pop() method: This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1. " }, { "code": null, "e": 27080, "s": 27068, "text": "Example 1: " }, { "code": null, "e": 27091, "s": 27080, "text": "javascript" }, { "code": "<script>// JavaScript code to illustrate pop() function// to remove array elements function func() { var arr = [\"shift\", \"splice\", \"filter\", \"pop\"]; // Popping the last element from the array var popped = arr.pop(); document.write(\"Removed element: \" + popped + \"<br>\"); document.write(\"Remaining elements: \" + arr);}func();</script>", "e": 27441, "s": 27091, "text": null }, { "code": null, "e": 27451, "s": 27441, "text": "Output: " }, { "code": null, "e": 27515, "s": 27451, "text": "Removed element: pop\nRemaining elements: shift, splice, filter\n" }, { "code": null, "e": 27527, "s": 27515, "text": "Example 2: " }, { "code": null, "e": 27538, "s": 27527, "text": "javascript" }, { "code": "<script>// Declare and initialize an arrayvar array = [\"pop\", \"splice\", \"filter\", \"shift\"] document.write(\"Original array: \" + array + \"<br>\") // Loop run while array length not zerowhile (array.length) { // Remove elements from array array.pop();}document.write(\"Array Length: \" + array.length ) </script>", "e": 27852, "s": 27538, "text": null }, { "code": null, "e": 27862, "s": 27852, "text": "Output: " }, { "code": null, "e": 27921, "s": 27862, "text": "Original array: pop, splice, filter, shift\nArray Length: 0" }, { "code": null, "e": 28077, "s": 27921, "text": "Remove Array elements by using shift() method: This method is used to remove the first element of the array and reducing the size of original array by 1. " }, { "code": null, "e": 28087, "s": 28077, "text": "Example: " }, { "code": null, "e": 28098, "s": 28087, "text": "javascript" }, { "code": "<script>// JavaScript code to illustrate shift() method// to remove elements from arrayfunction func() { var arr = [\"shift\", \"splice\", \"filter\", \"pop\"]; // Removing the first element from array var shifted = arr.shift(); document.write(\"Removed element: \" + shifted + \"<br>\"); document.write(\"Remaining elements: \" + arr);}func();</script> ", "e": 28473, "s": 28098, "text": null }, { "code": null, "e": 28483, "s": 28473, "text": "Output: " }, { "code": null, "e": 28546, "s": 28483, "text": "Removed element: shift\nRemaining elements: splice, filter, pop" }, { "code": null, "e": 28802, "s": 28546, "text": "Remove Array elements by using splice() method: This method is used to modify the contents of an array by removing the existing elements and/or by adding new elements. To remove elements by splice() method you can specify the elements in different ways. " }, { "code": null, "e": 28892, "s": 28802, "text": "Example 1: Use the indexing of splice method to remove elements from a JavaScript array. " }, { "code": null, "e": 28903, "s": 28892, "text": "javascript" }, { "code": "<script>// JavaScript code to illustrate splice() function function func() { var arr = [\"shift\", \"splice\", \"filter\", \"pop\"]; // Removing the specified element from the array var spliced = arr.splice(1, 1); document.write(\"Removed element: \" + spliced + \"<br>\"); document.write(\"Remaining elements: \" + arr);}func();</script> ", "e": 29263, "s": 28903, "text": null }, { "code": null, "e": 29273, "s": 29263, "text": "Output: " }, { "code": null, "e": 29336, "s": 29273, "text": "Removed element: splice\nRemaining elements: shift, filter, pop" }, { "code": null, "e": 29425, "s": 29336, "text": "Example 2: Using the value of splice method to remove elements from a JavaScript array. " }, { "code": null, "e": 29436, "s": 29425, "text": "javascript" }, { "code": "<script> // JavaScript code to illustrate splice() functionfunction func() { var arr = [\"shift\", \"splice\", \"filter\", \"pop\"]; // Removing the specified element by value from the array for (var i = 0; i < arr.length; i++) { if (arr[i] === \"splice\") { var spliced = arr.splice(i, 1); document.write(\"Removed element: \" + spliced + \"<br>\"); document.write(\"Remaining elements: \" + arr); } }}func();</script> ", "e": 29915, "s": 29436, "text": null }, { "code": null, "e": 29925, "s": 29915, "text": "Output: " }, { "code": null, "e": 29988, "s": 29925, "text": "Removed element: splice\nRemaining elements: shift, filter, pop" }, { "code": null, "e": 30073, "s": 29988, "text": "Example 3: Using the splice method to remove each elements from a JavaScript array. " }, { "code": null, "e": 30084, "s": 30073, "text": "javascript" }, { "code": "<script>// Declare and initialize arrayvar array = [\"pop\", \"splice\", \"filter\", \"shift\"] document.write(\"Original array: \" + array + \"<br>\") // Making the length of array to 0 by using splice methodarray.splice(0, array.length);document.write(\"Empty array: \" + array )</script>", "e": 30361, "s": 30084, "text": null }, { "code": null, "e": 30371, "s": 30361, "text": "Output: " }, { "code": null, "e": 30427, "s": 30371, "text": "Original array: pop, splice, filter, shift\nEmpty array:" }, { "code": null, "e": 30735, "s": 30427, "text": "Remove Array elements by using filter() method: This method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. To remove elements by filter() method you can specify the elements in different ways. " }, { "code": null, "e": 30820, "s": 30735, "text": "Example: Use the value of filter method to remove elements from a JavaScript array. " }, { "code": null, "e": 30831, "s": 30820, "text": "javascript" }, { "code": "<script> // JavaScript to illustrate filter() methodfunction isPositive( value ) { return value > 0;} function func() { var filtered = [101, 98, 12, -1, 848].filter( isPositive ); document.write(\"Positive elements in array: \" + filtered);}func();</script>", "e": 31096, "s": 30831, "text": null }, { "code": null, "e": 31106, "s": 31096, "text": "Output: " }, { "code": null, "e": 31152, "s": 31106, "text": "Positive elements in array: 101, 98, 12, 848\n" }, { "code": null, "e": 31326, "s": 31152, "text": "Remove Array elements by using Remove Method: Creating a remove method using filter method to remove elements from a JavaScript array. This methods works in reverse order. " }, { "code": null, "e": 31336, "s": 31326, "text": "Example: " }, { "code": null, "e": 31347, "s": 31336, "text": "javascript" }, { "code": "<script> // Declare and initialize an arrayvar array = [\"lowdash\", \"remove\", \"delete\", \"reset\"] // Using filter method to create a remove methodfunction arrayRemove(arr, value) { return arr.filter(function(geeks){ return geeks != value; }); } var result = arrayRemove(array, \"delete\");document.write(\"Remaining elements: \" + result)</script>", "e": 31700, "s": 31347, "text": null }, { "code": null, "e": 31710, "s": 31700, "text": "Output: " }, { "code": null, "e": 31753, "s": 31710, "text": "Remaining elements: lowdash, remove, reset" }, { "code": null, "e": 31865, "s": 31753, "text": "Remove Array elements by Delete Operator: Use the delete operator to remove elements from a JavaScript array. " }, { "code": null, "e": 31875, "s": 31865, "text": "Example: " }, { "code": null, "e": 31886, "s": 31875, "text": "javascript" }, { "code": "<script> // Declare and initialize an arrayvar array = [\"lowdash\", \"remove\", \"delete\", \"reset\"] // Delete element at index 2var deleted = delete array[2]; document.write(\"Removed: \" + deleted + \"<br>\");document.write(\"Remaining elements: \" + array);</script> ", "e": 32153, "s": 31886, "text": null }, { "code": null, "e": 32163, "s": 32153, "text": "Output: " }, { "code": null, "e": 32221, "s": 32163, "text": "Removed: true\nRemaining elements: lowdash, remove,,reset\n" }, { "code": null, "e": 32346, "s": 32221, "text": "Remove Array elements by Clear and Reset Operator: Use clear and reset operator to remove elements from a JavaScript array. " }, { "code": null, "e": 32358, "s": 32346, "text": "Example 1: " }, { "code": null, "e": 32369, "s": 32358, "text": "javascript" }, { "code": "<script> // Declare and initialize an arrayvar array = [\"lowdash\", \"remove\", \"delete\", \"reset\"] // Sorting array in another arrayvar arraygeeks = array // Delete each element of arrayarray = []document.write(\"Empty array: \" + array + \"<br>\")document.write(\"Original array: \" + arraygeeks) </script> ", "e": 32683, "s": 32369, "text": null }, { "code": null, "e": 32693, "s": 32683, "text": "Output: " }, { "code": null, "e": 32754, "s": 32693, "text": "Empty array:\nOriginal array: lowdash, remove, delete, reset\n" }, { "code": null, "e": 32767, "s": 32754, "text": "Example 2: " }, { "code": null, "e": 32778, "s": 32767, "text": "javascript" }, { "code": "<script> // Declare and initialize an arrayvar array = [\"lowdash\", \"remove\", \"delete\", \"reset\"] document.write(\"Original array: \" + array + \"<br>\") // Making the array length to 0array.length = 0;document.write(\"Empty array: \" + array ) </script> ", "e": 33056, "s": 32778, "text": null }, { "code": null, "e": 33066, "s": 33056, "text": "Output: " }, { "code": null, "e": 33126, "s": 33066, "text": "Original array: lowdash, remove, delete, reset\nEmpty array:" }, { "code": null, "e": 33308, "s": 33126, "text": "Remove Array elements by lowdash library: Use the lowdash library to remove elements from a JavaScript array. To use lowdash library you need to install it locally on your system. " }, { "code": null, "e": 33318, "s": 33308, "text": "Example: " }, { "code": null, "e": 33323, "s": 33318, "text": "html" }, { "code": "<script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js\"> // Declare and initialize an arrayvar array = [101, 98, 12, -1, 848];var evens= _.remove(array, function(n) { return n % 2 == 0;}); console.log(\"odd elements: \" + array + \"<br>\");console.log(\"even elements: \" + evens); </script> ", "e": 33676, "s": 33323, "text": null }, { "code": null, "e": 33685, "s": 33676, "text": "Output: " }, { "code": null, "e": 33734, "s": 33685, "text": "odd elements: 101, -1\neven elements: 98, 12, 848" }, { "code": null, "e": 33743, "s": 33734, "text": "gabaa406" }, { "code": null, "e": 33760, "s": 33743, "text": "javascript-array" }, { "code": null, "e": 33771, "s": 33760, "text": "JavaScript" }, { "code": null, "e": 33788, "s": 33771, "text": "Web Technologies" }, { "code": null, "e": 33815, "s": 33788, "text": "Web technologies Questions" }, { "code": null, "e": 33913, "s": 33815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33958, "s": 33913, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34019, "s": 33958, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34091, "s": 34019, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34143, "s": 34091, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 34189, "s": 34143, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 34222, "s": 34189, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34267, "s": 34222, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34310, "s": 34267, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34360, "s": 34310, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CLOC - Count number of lines of code in file - GeeksforGeeks
23 Aug, 2021 cloc is a command-line-based tool. It counts the blank lines, comment lines, actual code lines written in many programming languages. cloc is completely written in the Perl language, and it has no external dependencies. cloc can run on many operating systems like Linux, macOS, Windows, OpenBSD and many more. Now let’s see how we can install the cloc on different operating systems. Use one of the following commands according to your operating system: sudo apt install cloc sudo yum install cloc sudo dnf install cloc sudo pacman -S cloc sudo emerge -av dev-util/cloc sudo apk add cloc doas pkg_add cloc sudo pkg install cloc sudo port install cloc brew install cloc choco install cloc scoop install cloc To install the cloc using npm use the following command: npm install -g cloc Now we have installed the cloc on the system. Let’s see how to use the cloc. The general syntax of using cloc is as follows cloc [options] <FILE|DIR> ... Now let’s see understand by one example. We have one source file written in CPP and contains the following code: // hello.C #include <iostream> int main () { std::cout << "hello" << std::endl; // comment 1 std::cout << "again" << std::endl; /* comment 2 */ } Now let’s use the cloc to count the line As we can see, the cloc has correctly counted the comments and code lines. cloc can also count the number of lines physical, commented, an empty line written in different languages in compressed files cloc compressed_file Let’s see one example, we have one compressed file which contains some files written in JS and markdown, Let’s use the cloc on that compressed file. To get the line of code count file-wise in folder or zip file use the –by-file option with the cloc command. cloc --by-file folder/compressedFile cloc can also count the codes written in different files in the GitHub repository. Now let’s clone cloc GitHub repository. To count the number of lines in the GitHub repo the following command: cloc commit First, clone the repository and use the cloc. git clone https://github.com/AlDanial/cloc cd cloc cloc ec44eb0 cloc provide many other options. To know more about the cloc read the man page of cloc. man cloc Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ Basic Operators in Shell Scripting nohup Command in Linux with Examples Array Basics in Shell Scripting | Set 1 Named Pipe or FIFO with example C program chown command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction Start/Stop/Restart Services Using Systemctl in Linux SED command in Linux | Set 2
[ { "code": null, "e": 24326, "s": 24298, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24636, "s": 24326, "text": "cloc is a command-line-based tool. It counts the blank lines, comment lines, actual code lines written in many programming languages. cloc is completely written in the Perl language, and it has no external dependencies. cloc can run on many operating systems like Linux, macOS, Windows, OpenBSD and many more." }, { "code": null, "e": 24780, "s": 24636, "text": "Now let’s see how we can install the cloc on different operating systems. Use one of the following commands according to your operating system:" }, { "code": null, "e": 24812, "s": 24780, "text": "sudo apt install cloc " }, { "code": null, "e": 24846, "s": 24812, "text": "sudo yum install cloc " }, { "code": null, "e": 24880, "s": 24846, "text": "sudo dnf install cloc " }, { "code": null, "e": 24914, "s": 24880, "text": "sudo pacman -S cloc " }, { "code": null, "e": 24948, "s": 24914, "text": "sudo emerge -av dev-util/cloc " }, { "code": null, "e": 24982, "s": 24948, "text": "sudo apk add cloc " }, { "code": null, "e": 25016, "s": 24982, "text": "doas pkg_add cloc " }, { "code": null, "e": 25050, "s": 25016, "text": "sudo pkg install cloc " }, { "code": null, "e": 25084, "s": 25050, "text": "sudo port install cloc " }, { "code": null, "e": 25118, "s": 25084, "text": "brew install cloc " }, { "code": null, "e": 25152, "s": 25118, "text": "choco install cloc " }, { "code": null, "e": 25186, "s": 25152, "text": "scoop install cloc " }, { "code": null, "e": 25243, "s": 25186, "text": "To install the cloc using npm use the following command:" }, { "code": null, "e": 25277, "s": 25243, "text": "npm install -g cloc " }, { "code": null, "e": 25401, "s": 25277, "text": "Now we have installed the cloc on the system. Let’s see how to use the cloc. The general syntax of using cloc is as follows" }, { "code": null, "e": 25431, "s": 25401, "text": "cloc [options] <FILE|DIR> ..." }, { "code": null, "e": 25544, "s": 25431, "text": "Now let’s see understand by one example. We have one source file written in CPP and contains the following code:" }, { "code": null, "e": 25692, "s": 25544, "text": "// hello.C\n#include <iostream>\nint main ()\n{\nstd::cout << \"hello\" << std::endl; // comment 1\nstd::cout << \"again\" << std::endl; /* comment\n2 */\n}" }, { "code": null, "e": 25733, "s": 25692, "text": "Now let’s use the cloc to count the line" }, { "code": null, "e": 25808, "s": 25733, "text": "As we can see, the cloc has correctly counted the comments and code lines." }, { "code": null, "e": 25934, "s": 25808, "text": "cloc can also count the number of lines physical, commented, an empty line written in different languages in compressed files" }, { "code": null, "e": 25955, "s": 25934, "text": "cloc compressed_file" }, { "code": null, "e": 26104, "s": 25955, "text": "Let’s see one example, we have one compressed file which contains some files written in JS and markdown, Let’s use the cloc on that compressed file." }, { "code": null, "e": 26213, "s": 26104, "text": "To get the line of code count file-wise in folder or zip file use the –by-file option with the cloc command." }, { "code": null, "e": 26250, "s": 26213, "text": "cloc --by-file folder/compressedFile" }, { "code": null, "e": 26444, "s": 26250, "text": "cloc can also count the codes written in different files in the GitHub repository. Now let’s clone cloc GitHub repository. To count the number of lines in the GitHub repo the following command:" }, { "code": null, "e": 26456, "s": 26444, "text": "cloc commit" }, { "code": null, "e": 26502, "s": 26456, "text": "First, clone the repository and use the cloc." }, { "code": null, "e": 26566, "s": 26502, "text": "git clone https://github.com/AlDanial/cloc\ncd cloc\ncloc ec44eb0" }, { "code": null, "e": 26654, "s": 26566, "text": "cloc provide many other options. To know more about the cloc read the man page of cloc." }, { "code": null, "e": 26663, "s": 26654, "text": "man cloc" }, { "code": null, "e": 26675, "s": 26663, "text": "Linux-Tools" }, { "code": null, "e": 26686, "s": 26675, "text": "Linux-Unix" }, { "code": null, "e": 26784, "s": 26686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26793, "s": 26784, "text": "Comments" }, { "code": null, "e": 26806, "s": 26793, "text": "Old Comments" }, { "code": null, "e": 26832, "s": 26806, "text": "Thread functions in C/C++" }, { "code": null, "e": 26867, "s": 26832, "text": "Basic Operators in Shell Scripting" }, { "code": null, "e": 26904, "s": 26867, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26944, "s": 26904, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 26986, "s": 26944, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27023, "s": 26986, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27057, "s": 27023, "text": "mv command in Linux with examples" }, { "code": null, "e": 27083, "s": 27057, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27136, "s": 27083, "text": "Start/Stop/Restart Services Using Systemctl in Linux" } ]
Program to find the mid-point of a line - GeeksforGeeks
12 Apr, 2021 Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = –1, y1 = 2, x2 = 3, y2 = –6 Output : 1,–2 Input : x1 = 6.4, y1 = 3 x2 = –10.7, y2 = 4 Output : –2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M found by the following formula: M = ((x1+x2)/2 , (y1+y2)/2) C++ Java Python3 C# PHP Javascript // C++ program to find// the midpoint of a line#include<iostream>using namespace std; // function to find the// midpoint of a linevoid midpoint(int x1, int x2, int y1, int y2){ cout << (float)(x1+x2)/2 << " , "<< (float)(y1+y2)/2 ;} // Driver Function to test aboveint main(){ int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); return 0;} // Java program to find// the midpoint of a lineimport java.io.*; class GFG{ // function to find the // midpoint of a line static void midpoint(int x1, int x2, int y1, int y2) { System.out.print((x1 + x2) / 2 + " , " + (y1 + y2) / 2) ; } // Driver code public static void main (String[] args) { int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); }} // This code is contributed by vt_m. # Python3 program to find# the midpoint of a line # Function to find the# midpoint of a linedef midpoint(x1, x2, y1, y2): print((x1 + x2) // 2, " , ", (y1 + y2) // 2) # Driver Codex1, y1, x2, y2 = -1, 2, 3, -6midpoint(x1, x2, y1, y2) # This code is contributed by Anant Agarwal. // C# program to find// the midpoint of a lineusing System; class GFG{ // function to find the // midpoint of a line static void midpoint(int x1, int x2, int y1, int y2) { Console.WriteLine((x1 + x2) / 2 + " , " + (y1 + y2) / 2) ; } // Driver code public static void Main () { int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); }} // This code is contributed by vt_m. <?php// PHP program to find// the midpoint of a line // function to find the// midpoint of a linefunction midpoint($x1, $x2, $y1, $y2){ echo((float)($x1 + $x2)/2 . " , " . (float)($y1 + $y2)/2) ;} // Driver Code$x1 = -1; $y1 = 2 ;$x2 = 3; $y2 = -6 ; midpoint($x1, $x2, $y1, $y2); // This code is contributed by Ajit.?> <script> // JavaScript program to find// the midpoint of a line // function to find the // midpoint of a line function midpoint(x1, x2, y1, y2) { document.write((x1 + x2) / 2 + " , " + (y1 + y2) / 2) ; } // Driver code let x1 =-1, y1 = 2 ; let x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); </script> Output : 1 , -2 jit_t souravghosh0416 Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Closest Pair of Points | O(nlogn) Implementation Given n line segments, find if any two segments intersect Convex Hull | Set 2 (Graham Scan) Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24995, "s": 24967, "text": "\n12 Apr, 2021" }, { "code": null, "e": 25116, "s": 24995, "text": "Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : " }, { "code": null, "e": 25258, "s": 25116, "text": "Input : x1 = –1, y1 = 2, \n x2 = 3, y2 = –6\nOutput : 1,–2\n\nInput : x1 = 6.4, y1 = 3 \n x2 = –10.7, y2 = 4\nOutput : –2.15, 3.5" }, { "code": null, "e": 25410, "s": 25262, "text": "The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M found by the following formula: M = ((x1+x2)/2 , (y1+y2)/2) " }, { "code": null, "e": 25414, "s": 25410, "text": "C++" }, { "code": null, "e": 25419, "s": 25414, "text": "Java" }, { "code": null, "e": 25427, "s": 25419, "text": "Python3" }, { "code": null, "e": 25430, "s": 25427, "text": "C#" }, { "code": null, "e": 25434, "s": 25430, "text": "PHP" }, { "code": null, "e": 25445, "s": 25434, "text": "Javascript" }, { "code": "// C++ program to find// the midpoint of a line#include<iostream>using namespace std; // function to find the// midpoint of a linevoid midpoint(int x1, int x2, int y1, int y2){ cout << (float)(x1+x2)/2 << \" , \"<< (float)(y1+y2)/2 ;} // Driver Function to test aboveint main(){ int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); return 0;}", "e": 25850, "s": 25445, "text": null }, { "code": "// Java program to find// the midpoint of a lineimport java.io.*; class GFG{ // function to find the // midpoint of a line static void midpoint(int x1, int x2, int y1, int y2) { System.out.print((x1 + x2) / 2 + \" , \" + (y1 + y2) / 2) ; } // Driver code public static void main (String[] args) { int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); }} // This code is contributed by vt_m.", "e": 26371, "s": 25850, "text": null }, { "code": "# Python3 program to find# the midpoint of a line # Function to find the# midpoint of a linedef midpoint(x1, x2, y1, y2): print((x1 + x2) // 2, \" , \", (y1 + y2) // 2) # Driver Codex1, y1, x2, y2 = -1, 2, 3, -6midpoint(x1, x2, y1, y2) # This code is contributed by Anant Agarwal.", "e": 26671, "s": 26371, "text": null }, { "code": "// C# program to find// the midpoint of a lineusing System; class GFG{ // function to find the // midpoint of a line static void midpoint(int x1, int x2, int y1, int y2) { Console.WriteLine((x1 + x2) / 2 + \" , \" + (y1 + y2) / 2) ; } // Driver code public static void Main () { int x1 =-1, y1 = 2 ; int x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); }} // This code is contributed by vt_m.", "e": 27181, "s": 26671, "text": null }, { "code": "<?php// PHP program to find// the midpoint of a line // function to find the// midpoint of a linefunction midpoint($x1, $x2, $y1, $y2){ echo((float)($x1 + $x2)/2 . \" , \" . (float)($y1 + $y2)/2) ;} // Driver Code$x1 = -1; $y1 = 2 ;$x2 = 3; $y2 = -6 ; midpoint($x1, $x2, $y1, $y2); // This code is contributed by Ajit.?>", "e": 27521, "s": 27181, "text": null }, { "code": "<script> // JavaScript program to find// the midpoint of a line // function to find the // midpoint of a line function midpoint(x1, x2, y1, y2) { document.write((x1 + x2) / 2 + \" , \" + (y1 + y2) / 2) ; } // Driver code let x1 =-1, y1 = 2 ; let x2 = 3, y2 = -6 ; midpoint(x1, x2, y1, y2); </script>", "e": 27934, "s": 27521, "text": null }, { "code": null, "e": 27944, "s": 27934, "text": "Output : " }, { "code": null, "e": 27951, "s": 27944, "text": "1 , -2" }, { "code": null, "e": 27959, "s": 27953, "text": "jit_t" }, { "code": null, "e": 27975, "s": 27959, "text": "souravghosh0416" }, { "code": null, "e": 27985, "s": 27975, "text": "Geometric" }, { "code": null, "e": 28004, "s": 27985, "text": "School Programming" }, { "code": null, "e": 28014, "s": 28004, "text": "Geometric" }, { "code": null, "e": 28112, "s": 28014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28121, "s": 28112, "text": "Comments" }, { "code": null, "e": 28134, "s": 28121, "text": "Old Comments" }, { "code": null, "e": 28187, "s": 28134, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 28238, "s": 28187, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 28287, "s": 28238, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 28345, "s": 28287, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28379, "s": 28345, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28397, "s": 28379, "text": "Python Dictionary" }, { "code": null, "e": 28413, "s": 28397, "text": "Arrays in C/C++" }, { "code": null, "e": 28432, "s": 28413, "text": "Inheritance in C++" }, { "code": null, "e": 28457, "s": 28432, "text": "Reverse a string in Java" } ]
How to use JavaScript in Selenium to click an Element?
We can use the JavaScript Executor in Selenium to click an element. Selenium can execute JavaScript commands with the help of the method executeScript. Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click. The parameters to be passed to the executeScript method to click an element are - arguments[0].click(); and the web element locator. WebElement m=driver.findElement(By.linkText("Company")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", m); Let us click the link Company on the below page − import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ClickLnkJS{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement m = driver.findElement(By.linkText("Company")); // click with Javascript Executor JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", m); System.out.println("Page navigated to:" + driver.getTitle()); driver.quit(); } }
[ { "code": null, "e": 1130, "s": 1062, "text": "We can use the JavaScript Executor in Selenium to click an element." }, { "code": null, "e": 1214, "s": 1130, "text": "Selenium can execute JavaScript commands with the help of the method executeScript." }, { "code": null, "e": 1500, "s": 1214, "text": "Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click. The parameters to be passed to the executeScript method to click an element are - arguments[0].click(); and the web element locator." }, { "code": null, "e": 1656, "s": 1500, "text": "WebElement m=driver.findElement(By.linkText(\"Company\"));\nJavascriptExecutor js = (JavascriptExecutor) driver;\njs.executeScript(\"arguments[0].click();\", m);" }, { "code": null, "e": 1706, "s": 1656, "text": "Let us click the link Company on the below page −" }, { "code": null, "e": 2676, "s": 1706, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ClickLnkJS{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement m = driver.findElement(By.linkText(\"Company\"));\n // click with Javascript Executor\n JavascriptExecutor js = (JavascriptExecutor) driver;\n js.executeScript(\"arguments[0].click();\", m);\n System.out.println(\"Page navigated to:\" + driver.getTitle());\n driver.quit();\n }\n}" } ]
Delete a Doubly Linked List node at a given position - GeeksforGeeks
26 Oct, 2021 Given a doubly linked list and a position n. The task is to delete the node at the given position n from the beginning.Initial doubly linked list Doubly Linked List after deletion of node at position n = 2 Approach: Following are the steps: Get the pointer to the node at position n by traversing the doubly linked list up to the nth node from the beginning.Delete the node using the pointer obtained in Step 1. Refer this post. Get the pointer to the node at position n by traversing the doubly linked list up to the nth node from the beginning. Delete the node using the pointer obtained in Step 1. Refer this post. C++ Java Python C# Javascript /* C++ implementation to delete a doubly Linked List node at the given position */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* Function to delete the node at the given position in the doubly linked list */void deleteNodeAtGivenPos(struct Node** head_ref, int n){ /* if list in NULL or invalid position is given */ if (*head_ref == NULL || n <= 0) return; struct Node* current = *head_ref; int i; /* traverse up to the node at position 'n' from the beginning */ for (int i = 1; current != NULL && i < n; i++) current = current->next; /* if 'n' is greater than the number of nodes in the doubly linked list */ if (current == NULL) return; /* delete the node pointed to by 'current' */ deleteNode(head_ref, current);} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list 10<->8<->4<->2<->5 */ push(&head, 5); push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << "Doubly linked list before deletion:n"; printList(head); int n = 2; /* delete node at the given position 'n' */ deleteNodeAtGivenPos(&head, n); cout << "\nDoubly linked list after deletion:n"; printList(head); return 0;} /* Java implementation to delete a doubly Linked List node at the given position */ // A node of the doubly linked listclass Node{ int data; Node next, prev;} class GFG{ static Node head = null; // Function to delete a node // in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. static Node deleteNode(Node del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list static void deleteNodeAtGivenPos(int n) { /* if list in NULL or invalid position is given */ if (head == null || n <= 0) return; Node current = head; int i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(current); } // Function to insert a node // at the beginning of the Doubly Linked List static void push(int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; } // Function to print nodes in a // given doubly linked list static void printList() { Node temp = head; if (temp == null) System.out.print("Doubly Linked list empty"); while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } // Driver code public static void main(String[] args) { // Create the doubly linked list: // 10<->8<->4<->2<->5 push(5); push(2); push(4); push(8); push(10); System.out.println("Doubly linked " +"list before deletion:"); printList(); int n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(n); System.out.println("Doubly linked " +"list after deletion:"); printList(); }} // Thia code is contributed by Vivekkumar Singh # Python implementation to delete# a doubly Linked List node# at the given position # A node of the doubly linked listclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None # Function to delete a node in a Doubly Linked List.# head_ref -. pointer to head node pointer.# del -. pointer to node to be deleted.def deleteNode(head_ref, del_): # base case if (head_ref == None or del_ == None): return # If node to be deleted is head node if (head_ref == del_): head_ref = del_.next # Change next only if node to be deleted is NOT # the last node if (del_.next != None): del_.next.prev = del_.prev # Change prev only if node to be deleted is NOT # the first node if (del_.prev != None): del_.prev.next = del_.next return head_ref # Function to delete the node at the given position# in the doubly linked listdef deleteNodeAtGivenPos(head_ref,n): # if list in None or invalid position is given if (head_ref == None or n <= 0): return current = head_ref i = 1 # traverse up to the node at position 'n' from # the beginning while ( current != None and i < n ): current = current.next i = i + 1 # if 'n' is greater than the number of nodes # in the doubly linked list if (current == None): return # delete the node pointed to by 'current' deleteNode(head_ref, current) return head_ref # Function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # since we are adding at the beginning, #prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly# linked listdef printList(head): while (head != None) : print( head.data ,end= " ") head = head.next # Driver program to test above functions # Start with the empty listhead = None # Create the doubly linked list 10<.8<.4<.2<.5head = push(head, 5)head = push(head, 2)head = push(head, 4)head = push(head, 8)head = push(head, 10) print("Doubly linked list before deletion:")printList(head) n = 2 # delete node at the given position 'n'head = deleteNodeAtGivenPos(head, n) print("\nDoubly linked list after deletion:") printList(head) # This code is contributed by Arnab Kundu /* C# implementation to delete a doubly Linked List nodeat the given position */using System; // A node of the doubly linked listpublic class Node{ public int data; public Node next, prev;} class GFG{ // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list static void deleteNodeAtGivenPos(Node head, int n) { /* if list in NULL or invalid position is given */ if (head == null || n <= 0) return; Node current = head; int i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(head, current); } // Function to insert a node // at the beginning of the Doubly Linked List static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // Function to print nodes in a // given doubly linked list static void printList(Node temp) { if (temp == null) Console.Write("Doubly Linked list empty"); while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; // Create the doubly linked list: // 2<->2<->10<->8<->4<->2<->5<->2 head = push(head, 2); head = push(head, 5); head = push(head, 4); head = push(head, 8); head = push(head, 10); Console.WriteLine("Doubly linked list before deletion:"); printList(head); int n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(head, n); Console.WriteLine("Doubly linked list after deletion:"); printList(head); }} // This code is contributed by Arnab Kundu <script>/* javascript implementation to delete a doubly Linked List node at the given position */ // A node of the doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; } }var head = null; // Function to delete a node // in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. function deleteNode(del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list function deleteNodeAtGivenPos(n) { /* * if list in NULL or invalid position is given */ if (head == null || n <= 0) return; var current = head; var i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(current); } // Function to insert a node // at the beginning of the Doubly Linked List function push(new_data) { // allocate nodevar new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; } // Function to print nodes in a // given doubly linked list function printList() {var temp = head; if (temp == null) document.write("Doubly Linked list empty"); while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write(); } // Driver code // Create the doubly linked list: // 10<->8<->4<->2<->5 push(5); push(2); push(4); push(8); push(10); document.write("Doubly linked " + "list before deletion:<br/>"); printList(); var n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(n); document.write("<br/>Doubly linked " + "list after deletion:<br/>"); printList(); // This code contributed by gauravrajput1</script> Output: Doubly linked list before deletion: 10 8 4 2 5 Doubly linked list after deletion: 10 4 2 5 Time Complexity: O(n), in the worst case where n is the number of nodes in the doubly linked list. This article is contributed by Ayush Jauhari. 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. Vivekkumar Singh andrew1234 ananya sen GauravRajput1 khushboogoyal499 doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List vs Array Delete a Linked List node at a given position Merge two sorted linked lists Find the middle of a given linked list Implementing a Linked List in Java using Class Queue - Linked List Implementation Implement a stack using singly linked list Circular Linked List | Set 1 (Introduction and Applications) Merge Sort for Linked Lists Remove duplicates from a sorted linked list
[ { "code": null, "e": 25249, "s": 25221, "text": "\n26 Oct, 2021" }, { "code": null, "e": 25396, "s": 25249, "text": "Given a doubly linked list and a position n. The task is to delete the node at the given position n from the beginning.Initial doubly linked list " }, { "code": null, "e": 25457, "s": 25396, "text": "Doubly Linked List after deletion of node at position n = 2 " }, { "code": null, "e": 25492, "s": 25457, "text": "Approach: Following are the steps:" }, { "code": null, "e": 25680, "s": 25492, "text": "Get the pointer to the node at position n by traversing the doubly linked list up to the nth node from the beginning.Delete the node using the pointer obtained in Step 1. Refer this post." }, { "code": null, "e": 25798, "s": 25680, "text": "Get the pointer to the node at position n by traversing the doubly linked list up to the nth node from the beginning." }, { "code": null, "e": 25869, "s": 25798, "text": "Delete the node using the pointer obtained in Step 1. Refer this post." }, { "code": null, "e": 25873, "s": 25869, "text": "C++" }, { "code": null, "e": 25878, "s": 25873, "text": "Java" }, { "code": null, "e": 25885, "s": 25878, "text": "Python" }, { "code": null, "e": 25888, "s": 25885, "text": "C#" }, { "code": null, "e": 25899, "s": 25888, "text": "Javascript" }, { "code": "/* C++ implementation to delete a doubly Linked List node at the given position */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* Function to delete the node at the given position in the doubly linked list */void deleteNodeAtGivenPos(struct Node** head_ref, int n){ /* if list in NULL or invalid position is given */ if (*head_ref == NULL || n <= 0) return; struct Node* current = *head_ref; int i; /* traverse up to the node at position 'n' from the beginning */ for (int i = 1; current != NULL && i < n; i++) current = current->next; /* if 'n' is greater than the number of nodes in the doubly linked list */ if (current == NULL) return; /* delete the node pointed to by 'current' */ deleteNode(head_ref, current);} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list 10<->8<->4<->2<->5 */ push(&head, 5); push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << \"Doubly linked list before deletion:n\"; printList(head); int n = 2; /* delete node at the given position 'n' */ deleteNodeAtGivenPos(&head, n); cout << \"\\nDoubly linked list after deletion:n\"; printList(head); return 0;}", "e": 28887, "s": 25899, "text": null }, { "code": "/* Java implementation to delete a doubly Linked List node at the given position */ // A node of the doubly linked listclass Node{ int data; Node next, prev;} class GFG{ static Node head = null; // Function to delete a node // in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. static Node deleteNode(Node del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list static void deleteNodeAtGivenPos(int n) { /* if list in NULL or invalid position is given */ if (head == null || n <= 0) return; Node current = head; int i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(current); } // Function to insert a node // at the beginning of the Doubly Linked List static void push(int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; } // Function to print nodes in a // given doubly linked list static void printList() { Node temp = head; if (temp == null) System.out.print(\"Doubly Linked list empty\"); while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } // Driver code public static void main(String[] args) { // Create the doubly linked list: // 10<->8<->4<->2<->5 push(5); push(2); push(4); push(8); push(10); System.out.println(\"Doubly linked \" +\"list before deletion:\"); printList(); int n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(n); System.out.println(\"Doubly linked \" +\"list after deletion:\"); printList(); }} // Thia code is contributed by Vivekkumar Singh", "e": 32133, "s": 28887, "text": null }, { "code": "# Python implementation to delete# a doubly Linked List node# at the given position # A node of the doubly linked listclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None # Function to delete a node in a Doubly Linked List.# head_ref -. pointer to head node pointer.# del -. pointer to node to be deleted.def deleteNode(head_ref, del_): # base case if (head_ref == None or del_ == None): return # If node to be deleted is head node if (head_ref == del_): head_ref = del_.next # Change next only if node to be deleted is NOT # the last node if (del_.next != None): del_.next.prev = del_.prev # Change prev only if node to be deleted is NOT # the first node if (del_.prev != None): del_.prev.next = del_.next return head_ref # Function to delete the node at the given position# in the doubly linked listdef deleteNodeAtGivenPos(head_ref,n): # if list in None or invalid position is given if (head_ref == None or n <= 0): return current = head_ref i = 1 # traverse up to the node at position 'n' from # the beginning while ( current != None and i < n ): current = current.next i = i + 1 # if 'n' is greater than the number of nodes # in the doubly linked list if (current == None): return # delete the node pointed to by 'current' deleteNode(head_ref, current) return head_ref # Function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # since we are adding at the beginning, #prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly# linked listdef printList(head): while (head != None) : print( head.data ,end= \" \") head = head.next # Driver program to test above functions # Start with the empty listhead = None # Create the doubly linked list 10<.8<.4<.2<.5head = push(head, 5)head = push(head, 2)head = push(head, 4)head = push(head, 8)head = push(head, 10) print(\"Doubly linked list before deletion:\")printList(head) n = 2 # delete node at the given position 'n'head = deleteNodeAtGivenPos(head, n) print(\"\\nDoubly linked list after deletion:\") printList(head) # This code is contributed by Arnab Kundu", "e": 34857, "s": 32133, "text": null }, { "code": "/* C# implementation to delete a doubly Linked List nodeat the given position */using System; // A node of the doubly linked listpublic class Node{ public int data; public Node next, prev;} class GFG{ // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list static void deleteNodeAtGivenPos(Node head, int n) { /* if list in NULL or invalid position is given */ if (head == null || n <= 0) return; Node current = head; int i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(head, current); } // Function to insert a node // at the beginning of the Doubly Linked List static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // Function to print nodes in a // given doubly linked list static void printList(Node temp) { if (temp == null) Console.Write(\"Doubly Linked list empty\"); while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; // Create the doubly linked list: // 2<->2<->10<->8<->4<->2<->5<->2 head = push(head, 2); head = push(head, 5); head = push(head, 4); head = push(head, 8); head = push(head, 10); Console.WriteLine(\"Doubly linked list before deletion:\"); printList(head); int n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(head, n); Console.WriteLine(\"Doubly linked list after deletion:\"); printList(head); }} // This code is contributed by Arnab Kundu", "e": 38198, "s": 34857, "text": null }, { "code": "<script>/* javascript implementation to delete a doubly Linked List node at the given position */ // A node of the doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; } }var head = null; // Function to delete a node // in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. function deleteNode(del) { // base case if (head == null || del == null) return null; // If node to be deleted is head node if (head == del) head = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; del = null; return head; } // Function to delete the node at the // given position in the doubly linked list function deleteNodeAtGivenPos(n) { /* * if list in NULL or invalid position is given */ if (head == null || n <= 0) return; var current = head; var i; /* * traverse up to the node at position 'n' from the beginning */ for (i = 1; current != null && i < n; i++) { current = current.next; } // if 'n' is greater than the number of nodes // in the doubly linked list if (current == null) return; // delete the node pointed to by 'current' deleteNode(current); } // Function to insert a node // at the beginning of the Doubly Linked List function push(new_data) { // allocate nodevar new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; } // Function to print nodes in a // given doubly linked list function printList() {var temp = head; if (temp == null) document.write(\"Doubly Linked list empty\"); while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(); } // Driver code // Create the doubly linked list: // 10<->8<->4<->2<->5 push(5); push(2); push(4); push(8); push(10); document.write(\"Doubly linked \" + \"list before deletion:<br/>\"); printList(); var n = 2; // delete node at the given position 'n' deleteNodeAtGivenPos(n); document.write(\"<br/>Doubly linked \" + \"list after deletion:<br/>\"); printList(); // This code contributed by gauravrajput1</script>", "e": 41333, "s": 38198, "text": null }, { "code": null, "e": 41342, "s": 41333, "text": "Output: " }, { "code": null, "e": 41433, "s": 41342, "text": "Doubly linked list before deletion:\n10 8 4 2 5\nDoubly linked list after deletion:\n10 4 2 5" }, { "code": null, "e": 41532, "s": 41433, "text": "Time Complexity: O(n), in the worst case where n is the number of nodes in the doubly linked list." }, { "code": null, "e": 41953, "s": 41532, "text": "This article is contributed by Ayush Jauhari. 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": 41970, "s": 41953, "text": "Vivekkumar Singh" }, { "code": null, "e": 41981, "s": 41970, "text": "andrew1234" }, { "code": null, "e": 41992, "s": 41981, "text": "ananya sen" }, { "code": null, "e": 42006, "s": 41992, "text": "GauravRajput1" }, { "code": null, "e": 42023, "s": 42006, "text": "khushboogoyal499" }, { "code": null, "e": 42042, "s": 42023, "text": "doubly linked list" }, { "code": null, "e": 42054, "s": 42042, "text": "Linked List" }, { "code": null, "e": 42066, "s": 42054, "text": "Linked List" }, { "code": null, "e": 42164, "s": 42066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42185, "s": 42164, "text": "Linked List vs Array" }, { "code": null, "e": 42231, "s": 42185, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 42261, "s": 42231, "text": "Merge two sorted linked lists" }, { "code": null, "e": 42300, "s": 42261, "text": "Find the middle of a given linked list" }, { "code": null, "e": 42347, "s": 42300, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 42382, "s": 42347, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 42425, "s": 42382, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 42486, "s": 42425, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 42514, "s": 42486, "text": "Merge Sort for Linked Lists" } ]
How to run Cron Jobs in Node.js ? - GeeksforGeeks
28 Jan, 2020 Cron Jobs: These are the tasks that run periodically by the operating system. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging, sending newsletters, subscription emails and more. Prerequisites: Node.js installed NPM installed Basic knowledge of Node.js syntax We will use a package called node-cron which is a task scheduler in pure JavaScript for node.js. We are also using express as a server. Install the required packages using the command npm install express node-cron Syntax: cron.schedule("* * * * *", function() { // Task to do }); Time formatting for Cron jobs: Descriptors with their ranges: Seconds (optional): 0 – 59 Minute: 0 – 59 Hour: 0 – 23 Day of the Month: 1 – 31 Month: 1 – 12 Day of the week: 0 – 7 (0 and 7 both represent Sunday) Examples: (*/10 * * * *) – Runs on every 10 minutes (* * 21 * *) – Runs 21th of every month (0 8 * * 1) – Runs 8 AM on every Monday Example: Create a new file named index.js and add the following code: // Importing required librariesconst cron = require("node-cron");const express = require("express"); app = express(); // Initializing app // Creating a cron job which runs on every 10 secondcron.schedule("*/10 * * * * *", function() { console.log("running a task every 10 second");}); app.listen(3000); Run the file using command node index, you will see the output like below: Writing to a log file: Cron jobs can be used to schedule logging tasks in a system. We can log server status for a given time for monitoring purposes. Example: // Importing required packagesconst cron = require("node-cron");const express = require("express");const fs = require("fs"); app = express(); // Setting a cron jobcron.schedule("*/10 * * * * *", function() { // Data to write on file let data = `${new Date().toUTCString()} : Server is working\n`; // Appending data to logs.txt file fs.appendFile("logs.txt", data, function(err) { if (err) throw err; console.log("Status Logged!"); });}); app.listen(3000); After running above file for 30-40 seconds, you will see a file created named logs.txt having content somewhat similar to the following: Monthly Newsletters: Sending monthly newsletters are also a use case for cron jobs in which an email will be sent to the users monthly with the latest products or blog information on the website. You can learn more about sending email in Node.js here. Example: // Importing packagesconst cron = require("node-cron");const express = require("express");const nodemailer = require("nodemailer"); app = express(); // Calling sendEmail() function every 1 minutecron.schedule("*/1 * * * *", function() {sendMail();}); // Send Mail function using Nodemailerfunction sendMail() { let mailTransporter = nodemailer.createTransport({ service: "gmail", auth: { user: "<your-email>@gmail.com", pass: "**********" } }); // Setting credentials let mailDetails = { from: "<your-email>@gmail.com", to: "<user-email>@gmail.com", subject: "Test mail using Cron job", text: "Node.js cron job email" + " testing for GeeksforGeeks" }; // Sending Email mailTransporter.sendMail(mailDetails, function(err, data) { if (err) { console.log("Error Occurs", err); } else { console.log("Email sent successfully"); } });} app.listen(3000); The above script will send emails every minute. Note: Open this link to Allow less secure apps: ON. Now run the file using node index.js, you will see the output like below: In console: In Gmail Inbox: Node.js-Misc Technical Scripter 2019 Node.js Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.writeFile() Method Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function Mongoose | findByIdAndUpdate() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24775, "s": 24747, "text": "\n28 Jan, 2020" }, { "code": null, "e": 25073, "s": 24775, "text": "Cron Jobs: These are the tasks that run periodically by the operating system. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging, sending newsletters, subscription emails and more." }, { "code": null, "e": 25088, "s": 25073, "text": "Prerequisites:" }, { "code": null, "e": 25106, "s": 25088, "text": "Node.js installed" }, { "code": null, "e": 25120, "s": 25106, "text": "NPM installed" }, { "code": null, "e": 25154, "s": 25120, "text": "Basic knowledge of Node.js syntax" }, { "code": null, "e": 25338, "s": 25154, "text": "We will use a package called node-cron which is a task scheduler in pure JavaScript for node.js. We are also using express as a server. Install the required packages using the command" }, { "code": null, "e": 25368, "s": 25338, "text": "npm install express node-cron" }, { "code": null, "e": 25376, "s": 25368, "text": "Syntax:" }, { "code": null, "e": 25438, "s": 25376, "text": "cron.schedule(\"* * * * *\", function() {\n // Task to do\n});" }, { "code": null, "e": 25469, "s": 25438, "text": "Time formatting for Cron jobs:" }, { "code": null, "e": 25500, "s": 25469, "text": "Descriptors with their ranges:" }, { "code": null, "e": 25527, "s": 25500, "text": "Seconds (optional): 0 – 59" }, { "code": null, "e": 25542, "s": 25527, "text": "Minute: 0 – 59" }, { "code": null, "e": 25555, "s": 25542, "text": "Hour: 0 – 23" }, { "code": null, "e": 25580, "s": 25555, "text": "Day of the Month: 1 – 31" }, { "code": null, "e": 25594, "s": 25580, "text": "Month: 1 – 12" }, { "code": null, "e": 25649, "s": 25594, "text": "Day of the week: 0 – 7 (0 and 7 both represent Sunday)" }, { "code": null, "e": 25659, "s": 25649, "text": "Examples:" }, { "code": null, "e": 25701, "s": 25659, "text": "(*/10 * * * *) – Runs on every 10 minutes" }, { "code": null, "e": 25741, "s": 25701, "text": "(* * 21 * *) – Runs 21th of every month" }, { "code": null, "e": 25781, "s": 25741, "text": "(0 8 * * 1) – Runs 8 AM on every Monday" }, { "code": null, "e": 25851, "s": 25781, "text": "Example: Create a new file named index.js and add the following code:" }, { "code": "// Importing required librariesconst cron = require(\"node-cron\");const express = require(\"express\"); app = express(); // Initializing app // Creating a cron job which runs on every 10 secondcron.schedule(\"*/10 * * * * *\", function() { console.log(\"running a task every 10 second\");}); app.listen(3000);", "e": 26160, "s": 25851, "text": null }, { "code": null, "e": 26235, "s": 26160, "text": "Run the file using command node index, you will see the output like below:" }, { "code": null, "e": 26386, "s": 26235, "text": "Writing to a log file: Cron jobs can be used to schedule logging tasks in a system. We can log server status for a given time for monitoring purposes." }, { "code": null, "e": 26395, "s": 26386, "text": "Example:" }, { "code": "// Importing required packagesconst cron = require(\"node-cron\");const express = require(\"express\");const fs = require(\"fs\"); app = express(); // Setting a cron jobcron.schedule(\"*/10 * * * * *\", function() { // Data to write on file let data = `${new Date().toUTCString()} : Server is working\\n`; // Appending data to logs.txt file fs.appendFile(\"logs.txt\", data, function(err) { if (err) throw err; console.log(\"Status Logged!\"); });}); app.listen(3000);", "e": 26927, "s": 26395, "text": null }, { "code": null, "e": 27064, "s": 26927, "text": "After running above file for 30-40 seconds, you will see a file created named logs.txt having content somewhat similar to the following:" }, { "code": null, "e": 27260, "s": 27064, "text": "Monthly Newsletters: Sending monthly newsletters are also a use case for cron jobs in which an email will be sent to the users monthly with the latest products or blog information on the website." }, { "code": null, "e": 27316, "s": 27260, "text": "You can learn more about sending email in Node.js here." }, { "code": null, "e": 27325, "s": 27316, "text": "Example:" }, { "code": "// Importing packagesconst cron = require(\"node-cron\");const express = require(\"express\");const nodemailer = require(\"nodemailer\"); app = express(); // Calling sendEmail() function every 1 minutecron.schedule(\"*/1 * * * *\", function() {sendMail();}); // Send Mail function using Nodemailerfunction sendMail() { let mailTransporter = nodemailer.createTransport({ service: \"gmail\", auth: { user: \"<your-email>@gmail.com\", pass: \"**********\" } }); // Setting credentials let mailDetails = { from: \"<your-email>@gmail.com\", to: \"<user-email>@gmail.com\", subject: \"Test mail using Cron job\", text: \"Node.js cron job email\" + \" testing for GeeksforGeeks\" }; // Sending Email mailTransporter.sendMail(mailDetails, function(err, data) { if (err) { console.log(\"Error Occurs\", err); } else { console.log(\"Email sent successfully\"); } });} app.listen(3000);", "e": 28355, "s": 27325, "text": null }, { "code": null, "e": 28403, "s": 28355, "text": "The above script will send emails every minute." }, { "code": null, "e": 28455, "s": 28403, "text": "Note: Open this link to Allow less secure apps: ON." }, { "code": null, "e": 28529, "s": 28455, "text": "Now run the file using node index.js, you will see the output like below:" }, { "code": null, "e": 28541, "s": 28529, "text": "In console:" }, { "code": null, "e": 28557, "s": 28541, "text": "In Gmail Inbox:" }, { "code": null, "e": 28570, "s": 28557, "text": "Node.js-Misc" }, { "code": null, "e": 28594, "s": 28570, "text": "Technical Scripter 2019" }, { "code": null, "e": 28602, "s": 28594, "text": "Node.js" }, { "code": null, "e": 28621, "s": 28602, "text": "Technical Scripter" }, { "code": null, "e": 28638, "s": 28621, "text": "Web Technologies" }, { "code": null, "e": 28665, "s": 28638, "text": "Web technologies Questions" }, { "code": null, "e": 28763, "s": 28665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28772, "s": 28763, "text": "Comments" }, { "code": null, "e": 28785, "s": 28772, "text": "Old Comments" }, { "code": null, "e": 28815, "s": 28785, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28869, "s": 28815, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28906, "s": 28869, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28941, "s": 28906, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 28981, "s": 28941, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 29037, "s": 28981, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29099, "s": 29037, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29142, "s": 29099, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29192, "s": 29142, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C++ List Library - push_front() Function
The C++ function std::list::push_front() inserts new element at the beginning of list and increases size of list by one. Following is the declaration for std::list::push_front() function form std::list header. void push_front (const value_type& val); void push_front (const value_type& val); val − Value of element to be inserted into list. None. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::list::push_front() function. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l; for (int i = 0; i < 5; ++i) l.push_front(i + 1); cout << "List contains following elements" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − List contains following elements 5 4 3 2 1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2724, "s": 2603, "text": "The C++ function std::list::push_front() inserts new element at the beginning of list and increases size of list by one." }, { "code": null, "e": 2813, "s": 2724, "text": "Following is the declaration for std::list::push_front() function form std::list header." }, { "code": null, "e": 2855, "s": 2813, "text": "void push_front (const value_type& val);\n" }, { "code": null, "e": 2897, "s": 2855, "text": "void push_front (const value_type& val);\n" }, { "code": null, "e": 2946, "s": 2897, "text": "val − Value of element to be inserted into list." }, { "code": null, "e": 2952, "s": 2946, "text": "None." }, { "code": null, "e": 2997, "s": 2952, "text": "This member function never throws exception." }, { "code": null, "e": 3016, "s": 2997, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3091, "s": 3016, "text": "The following example shows the usage of std::list::push_front() function." }, { "code": null, "e": 3392, "s": 3091, "text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l;\n\n for (int i = 0; i < 5; ++i)\n l.push_front(i + 1);\n\n cout << \"List contains following elements\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3475, "s": 3392, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3519, "s": 3475, "text": "List contains following elements\n5\n4\n3\n2\n1\n" }, { "code": null, "e": 3526, "s": 3519, "text": " Print" }, { "code": null, "e": 3537, "s": 3526, "text": " Add Notes" } ]
Shortest path to reach one prime to other by changing single digit at a time - GeeksforGeeks
16 Sep, 2019 Given two four digit prime numbers, suppose 1033 and 8179, we need to find the shortest path from 1033 to 8179 by altering only single digit at a time such that every number that we get after changing a digit is prime. For example a solution is 1033, 1733, 3733, 3739, 3779, 8779, 8179 Examples: Input : 1033 8179 Output :6 Input : 1373 8017 Output : 7 Input : 1033 1033 Output : 0 The question can be solved by BFS and it is a pretty interesting to solve as a starting problem for beginners. We first find out all 4 digit prime numbers till 9999 using technique of Sieve of Eratosthenes. And then using those numbers formed the graph using adjacency list. After forming the adjacency list, we used simple BFS to solve the problem. C++ Python3 // CPP program to reach a prime number from // another by changing single digits and // using only prime numbers.#include <bits/stdc++.h> using namespace std; class graph { int V; list<int>* l; public: graph(int V) { this->V = V; l = new list<int>[V]; } void addedge(int V1, int V2) { l[V1].push_back(V2); l[V2].push_back(V1); } int bfs(int in1, int in2);}; // Finding all 4 digit prime numbersvoid SieveOfEratosthenes(vector<int>& v) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. int n = 9999; bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Forming a vector of prime numbers for (int p = 1000; p <= n; p++) if (prime[p]) v.push_back(p); } // in1 and in2 are two vertices of graph which are // actually indexes in pset[]int graph::bfs(int in1, int in2) { int visited[V]; memset(visited, 0, sizeof(visited)); queue<int> que; visited[in1] = 1; que.push(in1); list<int>::iterator i; while (!que.empty()) { int p = que.front(); que.pop(); for (i = l[p].begin(); i != l[p].end(); i++) { if (!visited[*i]) { visited[*i] = visited[p] + 1; que.push(*i); } if (*i == in2) { return visited[*i] - 1; } } }} // Returns true if num1 and num2 differ // by single digit.bool compare(int num1, int num2){ // To compare the digits string s1 = to_string(num1); string s2 = to_string(num2); int c = 0; if (s1[0] != s2[0]) c++; if (s1[1] != s2[1]) c++; if (s1[2] != s2[2]) c++; if (s1[3] != s2[3]) c++; // If the numbers differ only by a single // digit return true else false return (c == 1);} int shortestPath(int num1, int num2){ // Generate all 4 digit vector<int> pset; SieveOfEratosthenes(pset); // Create a graph where node numbers are indexes // in pset[] and there is an edge between two // nodes only if they differ by single digit. graph g(pset.size()); for (int i = 0; i < pset.size(); i++) for (int j = i + 1; j < pset.size(); j++) if (compare(pset[i], pset[j])) g.addedge(i, j); // Since graph nodes represent indexes of numbers // in pset[], we find indexes of num1 and num2. int in1, in2; for (int j = 0; j < pset.size(); j++) if (pset[j] == num1) in1 = j; for (int j = 0; j < pset.size(); j++) if (pset[j] == num2) in2 = j; return g.bfs(in1, in2);} // Driver codeint main(){ int num1 = 1033, num2 = 8179; cout << shortestPath(num1, num2); return 0;} # Python3 program to reach a prime number # from another by changing single digits # and using only prime numbers.import queue class Graph: def __init__(self, V): self.V = V; self.l = [[] for i in range(V)] def addedge(self, V1, V2): self.l[V1].append(V2); self.l[V2].append(V1); # in1 and in2 are two vertices of graph # which are actually indexes in pset[] def bfs(self, in1, in2): visited = [0] * self.V que = queue.Queue() visited[in1] = 1 que.put(in1) while (not que.empty()): p = que.queue[0] que.get() i = 0 while i < len(self.l[p]): if (not visited[self.l[p][i]]): visited[self.l[p][i]] = visited[p] + 1 que.put(self.l[p][i]) if (self.l[p][i] == in2): return visited[self.l[p][i]] - 1 i += 1 # Returns true if num1 and num2 # differ by single digit. # Finding all 4 digit prime numbers def SieveOfEratosthenes(v): # Create a boolean array "prime[0..n]" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. n = 9999 prime = [True] * (n + 1) p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Forming a vector of prime numbers for p in range(1000, n + 1): if (prime[p]): v.append(p) def compare(num1, num2): # To compare the digits s1 = str(num1) s2 = str(num2) c = 0 if (s1[0] != s2[0]): c += 1 if (s1[1] != s2[1]): c += 1 if (s1[2] != s2[2]): c += 1 if (s1[3] != s2[3]): c += 1 # If the numbers differ only by a single # digit return true else false return (c == 1) def shortestPath(num1, num2): # Generate all 4 digit pset = [] SieveOfEratosthenes(pset) # Create a graph where node numbers # are indexes in pset[] and there is # an edge between two nodes only if # they differ by single digit. g = Graph(len(pset)) for i in range(len(pset)): for j in range(i + 1, len(pset)): if (compare(pset[i], pset[j])): g.addedge(i, j) # Since graph nodes represent indexes # of numbers in pset[], we find indexes # of num1 and num2. in1, in2 = None, None for j in range(len(pset)): if (pset[j] == num1): in1 = j for j in range(len(pset)): if (pset[j] == num2): in2 = j return g.bfs(in1, in2) # Driver code if __name__ == '__main__': num1 = 1033 num2 = 8179 print(shortestPath(num1, num2)) # This code is contributed by PranchalK 6 goelankita2012 iniesta PranchalKatiyar Amazon BFS Prime Number Shortest Path Graph Amazon Prime Number Graph Shortest Path BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Ford-Fulkerson Algorithm for Maximum Flow Problem Tree, Back, Edge and Cross Edges in DFS of Graph Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
[ { "code": null, "e": 24839, "s": 24811, "text": "\n16 Sep, 2019" }, { "code": null, "e": 25125, "s": 24839, "text": "Given two four digit prime numbers, suppose 1033 and 8179, we need to find the shortest path from 1033 to 8179 by altering only single digit at a time such that every number that we get after changing a digit is prime. For example a solution is 1033, 1733, 3733, 3739, 3779, 8779, 8179" }, { "code": null, "e": 25135, "s": 25125, "text": "Examples:" }, { "code": null, "e": 25226, "s": 25135, "text": "Input : 1033 8179\nOutput :6\n\nInput : 1373 8017\nOutput : 7\n\nInput : 1033 1033\nOutput : 0\n" }, { "code": null, "e": 25576, "s": 25226, "text": "The question can be solved by BFS and it is a pretty interesting to solve as a starting problem for beginners. We first find out all 4 digit prime numbers till 9999 using technique of Sieve of Eratosthenes. And then using those numbers formed the graph using adjacency list. After forming the adjacency list, we used simple BFS to solve the problem." }, { "code": null, "e": 25580, "s": 25576, "text": "C++" }, { "code": null, "e": 25588, "s": 25580, "text": "Python3" }, { "code": "// CPP program to reach a prime number from // another by changing single digits and // using only prime numbers.#include <bits/stdc++.h> using namespace std; class graph { int V; list<int>* l; public: graph(int V) { this->V = V; l = new list<int>[V]; } void addedge(int V1, int V2) { l[V1].push_back(V2); l[V2].push_back(V1); } int bfs(int in1, int in2);}; // Finding all 4 digit prime numbersvoid SieveOfEratosthenes(vector<int>& v) { // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. int n = 9999; bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Forming a vector of prime numbers for (int p = 1000; p <= n; p++) if (prime[p]) v.push_back(p); } // in1 and in2 are two vertices of graph which are // actually indexes in pset[]int graph::bfs(int in1, int in2) { int visited[V]; memset(visited, 0, sizeof(visited)); queue<int> que; visited[in1] = 1; que.push(in1); list<int>::iterator i; while (!que.empty()) { int p = que.front(); que.pop(); for (i = l[p].begin(); i != l[p].end(); i++) { if (!visited[*i]) { visited[*i] = visited[p] + 1; que.push(*i); } if (*i == in2) { return visited[*i] - 1; } } }} // Returns true if num1 and num2 differ // by single digit.bool compare(int num1, int num2){ // To compare the digits string s1 = to_string(num1); string s2 = to_string(num2); int c = 0; if (s1[0] != s2[0]) c++; if (s1[1] != s2[1]) c++; if (s1[2] != s2[2]) c++; if (s1[3] != s2[3]) c++; // If the numbers differ only by a single // digit return true else false return (c == 1);} int shortestPath(int num1, int num2){ // Generate all 4 digit vector<int> pset; SieveOfEratosthenes(pset); // Create a graph where node numbers are indexes // in pset[] and there is an edge between two // nodes only if they differ by single digit. graph g(pset.size()); for (int i = 0; i < pset.size(); i++) for (int j = i + 1; j < pset.size(); j++) if (compare(pset[i], pset[j])) g.addedge(i, j); // Since graph nodes represent indexes of numbers // in pset[], we find indexes of num1 and num2. int in1, in2; for (int j = 0; j < pset.size(); j++) if (pset[j] == num1) in1 = j; for (int j = 0; j < pset.size(); j++) if (pset[j] == num2) in2 = j; return g.bfs(in1, in2);} // Driver codeint main(){ int num1 = 1033, num2 = 8179; cout << shortestPath(num1, num2); return 0;}", "e": 28687, "s": 25588, "text": null }, { "code": "# Python3 program to reach a prime number # from another by changing single digits # and using only prime numbers.import queue class Graph: def __init__(self, V): self.V = V; self.l = [[] for i in range(V)] def addedge(self, V1, V2): self.l[V1].append(V2); self.l[V2].append(V1); # in1 and in2 are two vertices of graph # which are actually indexes in pset[] def bfs(self, in1, in2): visited = [0] * self.V que = queue.Queue() visited[in1] = 1 que.put(in1) while (not que.empty()): p = que.queue[0] que.get() i = 0 while i < len(self.l[p]): if (not visited[self.l[p][i]]): visited[self.l[p][i]] = visited[p] + 1 que.put(self.l[p][i]) if (self.l[p][i] == in2): return visited[self.l[p][i]] - 1 i += 1 # Returns true if num1 and num2 # differ by single digit. # Finding all 4 digit prime numbers def SieveOfEratosthenes(v): # Create a boolean array \"prime[0..n]\" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. n = 9999 prime = [True] * (n + 1) p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Forming a vector of prime numbers for p in range(1000, n + 1): if (prime[p]): v.append(p) def compare(num1, num2): # To compare the digits s1 = str(num1) s2 = str(num2) c = 0 if (s1[0] != s2[0]): c += 1 if (s1[1] != s2[1]): c += 1 if (s1[2] != s2[2]): c += 1 if (s1[3] != s2[3]): c += 1 # If the numbers differ only by a single # digit return true else false return (c == 1) def shortestPath(num1, num2): # Generate all 4 digit pset = [] SieveOfEratosthenes(pset) # Create a graph where node numbers # are indexes in pset[] and there is # an edge between two nodes only if # they differ by single digit. g = Graph(len(pset)) for i in range(len(pset)): for j in range(i + 1, len(pset)): if (compare(pset[i], pset[j])): g.addedge(i, j) # Since graph nodes represent indexes # of numbers in pset[], we find indexes # of num1 and num2. in1, in2 = None, None for j in range(len(pset)): if (pset[j] == num1): in1 = j for j in range(len(pset)): if (pset[j] == num2): in2 = j return g.bfs(in1, in2) # Driver code if __name__ == '__main__': num1 = 1033 num2 = 8179 print(shortestPath(num1, num2)) # This code is contributed by PranchalK", "e": 31662, "s": 28687, "text": null }, { "code": null, "e": 31664, "s": 31662, "text": "6" }, { "code": null, "e": 31679, "s": 31664, "text": "goelankita2012" }, { "code": null, "e": 31687, "s": 31679, "text": "iniesta" }, { "code": null, "e": 31703, "s": 31687, "text": "PranchalKatiyar" }, { "code": null, "e": 31710, "s": 31703, "text": "Amazon" }, { "code": null, "e": 31714, "s": 31710, "text": "BFS" }, { "code": null, "e": 31727, "s": 31714, "text": "Prime Number" }, { "code": null, "e": 31741, "s": 31727, "text": "Shortest Path" }, { "code": null, "e": 31747, "s": 31741, "text": "Graph" }, { "code": null, "e": 31754, "s": 31747, "text": "Amazon" }, { "code": null, "e": 31767, "s": 31754, "text": "Prime Number" }, { "code": null, "e": 31773, "s": 31767, "text": "Graph" }, { "code": null, "e": 31787, "s": 31773, "text": "Shortest Path" }, { "code": null, "e": 31791, "s": 31787, "text": "BFS" }, { "code": null, "e": 31889, "s": 31791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31898, "s": 31889, "text": "Comments" }, { "code": null, "e": 31911, "s": 31898, "text": "Old Comments" }, { "code": null, "e": 31931, "s": 31911, "text": "Topological Sorting" }, { "code": null, "e": 31989, "s": 31931, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32020, "s": 31989, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32053, "s": 32020, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 32086, "s": 32053, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32136, "s": 32086, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 32185, "s": 32136, "text": "Tree, Back, Edge and Cross Edges in DFS of Graph" }, { "code": null, "e": 32260, "s": 32185, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 32331, "s": 32260, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" } ]
Java Program to subtract integers and check for overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE with the subtracted integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java. Let us see an example wherein integers are subtracted and if the result is more than Integer.MAX_VALUE, then an exception is thrown. The following is an example showing how to check for Integer overflow. Live Demo public class Demo { public static void main(String[] args) { int val1 = 9898999; int val2 = 8784556; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long sub = (long)val1 - (long)val2; if (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying subtraction result System.out.println("Subtraction Result: "+(int)sub); } } Value1: 9898999 Value2: 8784556 Subtraction Result: 1114443 In the above example, we have taken the following two integers − int val1 = 9898999; int val2 = 8784556; Now we will cast and subtract them to a long. long sub = (long)val1 - (long)val2; If the result is more than the maximum value, then an exception is thrown. If (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
[ { "code": null, "e": 1237, "s": 1062, "text": "To check for Integer overflow, we need to check the Integer.MAX_VALUE with the subtracted integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java." }, { "code": null, "e": 1370, "s": 1237, "text": "Let us see an example wherein integers are subtracted and if the result is more than Integer.MAX_VALUE, then an exception is thrown." }, { "code": null, "e": 1441, "s": 1370, "text": "The following is an example showing how to check for Integer overflow." }, { "code": null, "e": 1452, "s": 1441, "text": " Live Demo" }, { "code": null, "e": 1899, "s": 1452, "text": "public class Demo {\n public static void main(String[] args) {\n int val1 = 9898999;\n int val2 = 8784556;\n System.out.println(\"Value1: \"+val1);\n System.out.println(\"Value2: \"+val2);\n long sub = (long)val1 - (long)val2;\n if (sub > Integer.MAX_VALUE) {\n throw new ArithmeticException(\"Overflow!\");\n }\n // displaying subtraction result\n System.out.println(\"Subtraction Result: \"+(int)sub);\n }\n}" }, { "code": null, "e": 1959, "s": 1899, "text": "Value1: 9898999\nValue2: 8784556\nSubtraction Result: 1114443" }, { "code": null, "e": 2024, "s": 1959, "text": "In the above example, we have taken the following two integers −" }, { "code": null, "e": 2064, "s": 2024, "text": "int val1 = 9898999;\nint val2 = 8784556;" }, { "code": null, "e": 2110, "s": 2064, "text": "Now we will cast and subtract them to a long." }, { "code": null, "e": 2146, "s": 2110, "text": "long sub = (long)val1 - (long)val2;" }, { "code": null, "e": 2221, "s": 2146, "text": "If the result is more than the maximum value, then an exception is thrown." }, { "code": null, "e": 2301, "s": 2221, "text": "If (sub > Integer.MAX_VALUE) {\n throw new ArithmeticException(\"Overflow!\");\n}" } ]
How to change the row index after sampling an R data frame?
When we take a random sample from an R data frame the sample rows have row numbers as in the original data frame, obviously it happens due to randomization. But it might create confusion while doing analysis, especially in cases when we need to use rows, therefore, we can convert the index number of rows to numbers from 1 to the number of rows in the selected sample. Consider the below data frame − Live Demo > set.seed(111) > x1<-rnorm(20,1.5) > x2<-rnorm(20,2.5) > x3<-rnorm(20,3) > df1<-data.frame(x1,x2,x3) > df1 x1 x2 x3 1 1.735220712 2.8616625 1.824274 2 1.169264128 2.8469644 1.878784 3 1.188376176 2.6897365 1.638096 4 -0.802345658 2.3404232 3.481125 5 1.329123955 2.8265492 3.741972 6 1.640278225 3.0982542 3.027825 7 0.002573344 0.6584657 3.331380 8 0.489811581 5.2180556 3.644114 9 0.551524395 2.6912444 5.485662 10 1.006037783 1.1987039 4.959982 11 1.326325872 -0.6132173 3.191663 12 1.093401220 1.5586426 4.552544 13 3.345636264 3.9002588 3.914242 14 1.894054110 0.8795300 3.358625 15 2.297528501 0.2340040 3.175096 16 -0.066665360 3.6629936 2.152732 17 1.414148991 2.3838450 3.978232 18 1.140860519 2.8342560 4.805868 19 0.306391033 1.8791419 3.122915 20 1.864186737 1.1901551 2.870228 Creating a sample of size 5 from df1 − > df1_sample<-df1[sample(nrow(df1),5),] > df1_sample x1 x2 x3 18 1.140861 2.834256 4.805868 6 1.640278 3.098254 3.027825 13 3.345636 3.900259 3.914242 5 1.329124 2.826549 3.741972 15 2.297529 0.234004 3.175096 Renaming the index number of rows in the sample − > rownames(df1_sample)<-1:nrow(df1_sample) > df1_sample x1 x2 x3 1 1.140861 2.834256 4.805868 2 1.640278 3.098254 3.027825 3 3.345636 3.900259 3.914242 4 1.329124 2.826549 3.741972 5 2.297529 0.234004 3.175096 Let’s have a look at another example − Live Demo > y1<-runif(20,2,5) > y2<-runif(20,3,5) > y3<-runif(20,5,10) > y4<-runif(20,5,12) > df2<-data.frame(y1,y2,y3,y4) > df2 y1 y2 y3 y4 1 2.881213 4.894022 7.797367 6.487594 2 3.052896 3.223898 7.527572 6.695535 3 2.237543 4.127740 9.864026 8.754048 4 4.475907 4.696651 5.403004 6.239423 5 2.792642 4.023536 7.786222 8.992823 6 2.791539 4.333093 9.480036 6.087904 7 2.271143 3.053019 5.539486 8.320935 8 3.382534 3.212921 7.246406 10.091843 9 4.074728 4.390884 6.544056 10.924127 10 4.546881 3.546689 6.164413 11.710035 11 2.738344 4.489939 9.140333 8.211822 12 3.952763 4.490791 5.564392 7.542578 13 4.040586 3.333465 9.420011 11.554599 14 2.313604 4.959709 8.628101 11.193405 15 2.335957 4.189517 9.601667 9.694433 16 2.646964 4.376438 5.614787 10.929413 17 2.390349 3.343716 9.755718 11.017555 18 3.999001 3.083366 8.348515 8.370818 19 3.463324 3.379700 5.425484 7.219430 20 3.059911 4.522844 7.905784 11.420429 > df2_sample<-df2[sample(nrow(df2),7),] > df2_sample y1 y2 y3 y4 20 3.059911 4.522844 7.905784 11.420429 3 2.237543 4.127740 9.864026 8.754048 10 4.546881 3.546689 6.164413 11.710035 12 3.952763 4.490791 5.564392 7.542578 15 2.335957 4.189517 9.601667 9.694433 18 3.999001 3.083366 8.348515 8.370818 5 2.792642 4.023536 7.786222 8.992823 > rownames(df2_sample)<-1:nrow(df2_sample) > df2_sample y1 y2 y3 y4 1 3.059911 4.522844 7.905784 11.420429 2 2.237543 4.127740 9.864026 8.754048 3 4.546881 3.546689 6.164413 11.710035 4 3.952763 4.490791 5.564392 7.542578 5 2.335957 4.189517 9.601667 9.694433 6 3.999001 3.083366 8.348515 8.370818 7 2.792642 4.023536 7.786222 8.992823
[ { "code": null, "e": 1432, "s": 1062, "text": "When we take a random sample from an R data frame the sample rows have row numbers as in the original data frame, obviously it happens due to randomization. But it might create confusion while doing analysis, especially in cases when we need to use rows, therefore, we can convert the index number of rows to numbers from 1 to the number of rows in the selected sample." }, { "code": null, "e": 1464, "s": 1432, "text": "Consider the below data frame −" }, { "code": null, "e": 1475, "s": 1464, "text": " Live Demo" }, { "code": null, "e": 1583, "s": 1475, "text": "> set.seed(111)\n> x1<-rnorm(20,1.5)\n> x2<-rnorm(20,2.5)\n> x3<-rnorm(20,3)\n> df1<-data.frame(x1,x2,x3)\n> df1" }, { "code": null, "e": 2287, "s": 1583, "text": " x1 x2 x3\n1 1.735220712 2.8616625 1.824274\n2 1.169264128 2.8469644 1.878784\n3 1.188376176 2.6897365 1.638096\n4 -0.802345658 2.3404232 3.481125\n5 1.329123955 2.8265492 3.741972\n6 1.640278225 3.0982542 3.027825\n7 0.002573344 0.6584657 3.331380\n8 0.489811581 5.2180556 3.644114\n9 0.551524395 2.6912444 5.485662\n10 1.006037783 1.1987039 4.959982\n11 1.326325872 -0.6132173 3.191663\n12 1.093401220 1.5586426 4.552544\n13 3.345636264 3.9002588 3.914242\n14 1.894054110 0.8795300 3.358625\n15 2.297528501 0.2340040 3.175096\n16 -0.066665360 3.6629936 2.152732\n17 1.414148991 2.3838450 3.978232\n18 1.140860519 2.8342560 4.805868\n19 0.306391033 1.8791419 3.122915\n20 1.864186737 1.1901551 2.870228" }, { "code": null, "e": 2326, "s": 2287, "text": "Creating a sample of size 5 from df1 −" }, { "code": null, "e": 2379, "s": 2326, "text": "> df1_sample<-df1[sample(nrow(df1),5),]\n> df1_sample" }, { "code": null, "e": 2554, "s": 2379, "text": " x1 x2 x3\n18 1.140861 2.834256 4.805868\n6 1.640278 3.098254 3.027825\n13 3.345636 3.900259 3.914242\n5 1.329124 2.826549 3.741972\n15 2.297529 0.234004 3.175096" }, { "code": null, "e": 2604, "s": 2554, "text": "Renaming the index number of rows in the sample −" }, { "code": null, "e": 2660, "s": 2604, "text": "> rownames(df1_sample)<-1:nrow(df1_sample)\n> df1_sample" }, { "code": null, "e": 2832, "s": 2660, "text": " x1 x2 x3\n1 1.140861 2.834256 4.805868\n2 1.640278 3.098254 3.027825\n3 3.345636 3.900259 3.914242\n4 1.329124 2.826549 3.741972\n5 2.297529 0.234004 3.175096" }, { "code": null, "e": 2871, "s": 2832, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2882, "s": 2871, "text": " Live Demo" }, { "code": null, "e": 3001, "s": 2882, "text": "> y1<-runif(20,2,5)\n> y2<-runif(20,3,5)\n> y3<-runif(20,5,10)\n> y4<-runif(20,5,12)\n> df2<-data.frame(y1,y2,y3,y4)\n> df2" }, { "code": null, "e": 3816, "s": 3001, "text": " y1 y2 y3 y4\n1 2.881213 4.894022 7.797367 6.487594\n2 3.052896 3.223898 7.527572 6.695535\n3 2.237543 4.127740 9.864026 8.754048\n4 4.475907 4.696651 5.403004 6.239423\n5 2.792642 4.023536 7.786222 8.992823\n6 2.791539 4.333093 9.480036 6.087904\n7 2.271143 3.053019 5.539486 8.320935\n8 3.382534 3.212921 7.246406 10.091843\n9 4.074728 4.390884 6.544056 10.924127\n10 4.546881 3.546689 6.164413 11.710035\n11 2.738344 4.489939 9.140333 8.211822\n12 3.952763 4.490791 5.564392 7.542578\n13 4.040586 3.333465 9.420011 11.554599\n14 2.313604 4.959709 8.628101 11.193405\n15 2.335957 4.189517 9.601667 9.694433\n16 2.646964 4.376438 5.614787 10.929413\n17 2.390349 3.343716 9.755718 11.017555\n18 3.999001 3.083366 8.348515 8.370818\n19 3.463324 3.379700 5.425484 7.219430\n20 3.059911 4.522844 7.905784 11.420429" }, { "code": null, "e": 3869, "s": 3816, "text": "> df2_sample<-df2[sample(nrow(df2),7),]\n> df2_sample" }, { "code": null, "e": 4178, "s": 3869, "text": " y1 y2 y3 y4\n20 3.059911 4.522844 7.905784 11.420429\n3 2.237543 4.127740 9.864026 8.754048\n10 4.546881 3.546689 6.164413 11.710035\n12 3.952763 4.490791 5.564392 7.542578\n15 2.335957 4.189517 9.601667 9.694433\n18 3.999001 3.083366 8.348515 8.370818\n5 2.792642 4.023536 7.786222 8.992823" }, { "code": null, "e": 4234, "s": 4178, "text": "> rownames(df2_sample)<-1:nrow(df2_sample)\n> df2_sample" }, { "code": null, "e": 4538, "s": 4234, "text": " y1 y2 y3 y4\n1 3.059911 4.522844 7.905784 11.420429\n2 2.237543 4.127740 9.864026 8.754048\n3 4.546881 3.546689 6.164413 11.710035\n4 3.952763 4.490791 5.564392 7.542578\n5 2.335957 4.189517 9.601667 9.694433\n6 3.999001 3.083366 8.348515 8.370818\n7 2.792642 4.023536 7.786222 8.992823" } ]
What is Group Normalization?. An alternative to Batch Normalization | by Wanshun Wong | Towards Data Science
Batch Normalization (BN) has been an important component of many state-of-the-art deep learning models, especially in computer vision. It normalizes the layer inputs by the mean and variance computed within a batch, hence the name. For BN to work the batch size is required to be sufficiently large, usually at least 32. However, there are situations that we have to settle for a small batch size: when each data sample is highly memory-consuming, e.g. video or high resolution image when we train a very large neural network, which leaves little GPU memory for processing data Therefore we need alternatives to BN which work well with small batch size. Group Normalization (GN) is one of the latest normalization methods that avoids exploiting the batch dimension, thus is independent of batch size. To motivate the formulation of GN we will first look at some of the previous normalization methods. All of the following normalization methods perform the calculation xi ← (xi - μi) / √(σi2 + ε) for every coefficient xi of an input feature x. μi and σi2 are the mean and variance computed over a set Si of coefficients, and ε is a small constant added for numerical stability and to avoid division by zero. The only difference is how the set Si is chosen. To illustrate the computation of the normalization methods, we consider a batch of size N = 3, with input features a, b, and c. They have channels C = 4, height H = 1, width W = 2: a = [ [[2, 3]], [[5, 7]], [[11, 13]], [[17, 19]] ]b = [ [[0, 1]], [[1, 2]], [[3, 5]], [[8, 13]] ]c = [ [[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]] ] Hence the batch will have shape (N, C, H, W) = (3, 4, 1, 2). We take ε = 0.00001. BN normalizes the channels and computes μi and σi along the (N, H, W) axes. Si is defined as the set of coefficients in the batch that are in the same channel as xi. For the first coefficient ai = 2 of a, where i = (0, 0, 0), the corresponding μi and σi2 are computed over the coefficients of a, b, and c that are in the first channel: μi = mean(2, 3, 0, 1, 1, 2) = 1.5σi2 = var(2, 3, 0, 1, 1, 2) = 0.917 Plugging these into the normalization formula, ai ← (2 - 1.5) / √(0.917 + 0.00001) = 0.522 Computing all the coefficients of a gives a ← [ [[0.522, 1.567]], [[0.676, 1.690]], [[1.071, 1.630]], [[1.066, 1.492]] ] Layer Normalization (LN) is designed to overcome the drawbacks of BN, including its constraints on batch size. It computes μi and σi along the (C, H, W) axes, with Si defined as all the coefficients that belong to the same input feature as xi. As a result, the computation for an input feature is entirely independent of other input features in a batch. All the coefficients of a are normalized by the same μi and σi2 μi = mean(2, 3, 5, 7, 11, 13, 17, 19) = 9.625σi2 = var(2, 3, 5, 7, 11, 13, 17, 19) = 35.734 Therefore applying LN to a gives a ← [ [[-1.276, -1.108]], [[-0.773, -0.439]], [[0.230, 0.565]], [[1.234, 1.568]] ] Instance Normalization (IN) can be viewed as applying the formula of BN to each input feature (a.k.a. instance) individually as if it is the only member in a batch. More precisely, IN computes μi and σi along the (H, W) axes, and Si is defined as the set of coefficients that are in the same input feature and also in the same channel as xi. Since the computation of IN is the same as that of BN with batch size = 1, IN actually makes the situation even worse in most cases. However, for style transfer tasks, IN is better at discarding contrast information of an image, and has superior performances than BN. For the first coefficient ai = 2 of a, where i = (0, 0, 0), the corresponding μi and σi2 are simply μi = mean(2, 3) = 2.5σi2 = var(2, 3) = 0.25 which gives ai ← (2 - 2.5) / √(0.25 + 0.00001) = -1.000 When we apply IN to a, we get a ← [ [[-1.000, 1.000]], [[-1.000, 1.000]], [[-1.000, 1.000]], [[-1.000, 1.000]] ] Previously we introduced IN as applying BN to each input feature individually as if batch size = 1. Notice that IN can also be viewed as applying LN to each channel individually as if the number of channels = 1. Group Normalization (GN) is a middle ground between IN and LN. It organizes the channels into different groups, and computes μi and σi along the (H, W) axes and along a group of channels. Si is then the set of coefficients that are in the same input feature and also in the same group of channels as xi. The number of groups G is a pre-defined hyperparameter, which is usually required to divide C. For simplicity we group the channels in a sequential order. So channels 1, ..., C / G belong to the 1st group, channels C / G + 1, ..., 2C / G belong to the 2nd group, and so on. When G = C, which means each group has only 1 channel, GN becomes IN. On the other hand, when G = 1, GN becomes LN. Therefore G controls the interpolation between IN and LN. For our example consider G = 2. To normalize the first coefficient ai = 2 of a where i = (0, 0, 0), we use the coefficients of a in the first 4 / 2 = 2 channels μi = mean(2, 3, 5, 7) = 4.25σi2 = var(2, 3, 5, 7) = 3.687 Plugging these into the normalization formula, ai ← (2 - 4.25) / √(3.687 + 0.00001) = -1.172 For other coefficients of a, the computations are similar: a ← [ [[-1.172, -0.651]], [[0.391, 1.432]], [[-1.265, -0.633]], [[0.633, 1.265]] ] The following figure visualizes the relations among BN, LN, IN, and GN. The blue regions correspond to the sets Si for the computation μi and σi, which are then used to normalize any coefficients in the blue regions. From this figure we can see how GN interpolates between IN and LN. GN is better than IN as GN can exploit the dependence across the channels. It is also better than LN because it allows different distribution to be learned for each group of channels. When the batch size is small, GN consistently outperforms BN. However, when the batch size is significantly large, GN does not scale as well as BN and might not be able to match the performance of BN. TensorFlow: It is available via TensorFlow Addons tfa.layers.GroupNormalization PyTorch: torch.nn.GroupNorm Note that both implementations of GN have a learnable, per-channel linear transformation following the normalization by fault. This is similar to the implementations of BN, LN, and IN. The original paper of GN [4] is an excellent reference on the technical details of GN and also on the comparison of different normalization methods.Even though GN does not match BN when the batch size is large, GN + Weight Standardization [2] is able to match and even outperforms BN. We refer to [1] and [2] for some experiment results.[3] shows BN works by making the optimization landscape much smoother. This motivates the formulation of Weight Standardization. The original paper of GN [4] is an excellent reference on the technical details of GN and also on the comparison of different normalization methods. Even though GN does not match BN when the batch size is large, GN + Weight Standardization [2] is able to match and even outperforms BN. We refer to [1] and [2] for some experiment results. [3] shows BN works by making the optimization landscape much smoother. This motivates the formulation of Weight Standardization. A. Kolesnikov, L. Beyer, X. Zhai, J. Puigcerver, J. Yung, S. Gelly, and N. Houlsby. Big Transfer (BiT): General Visual Representation Learning (2019), arXiv preprint.S. Qiao, H. Wang, C. Liu, W. Shen, and A. Yuille. Weight Standardization (2019), arXiv preprint.S. Santurkar, D. Tsipras, A. Ilyas, and A. Madry. How Does Batch Normalization Help Optimization? (2018), NIPS 2018.Y. Wu, and K. He. Group Normalization (2018), ECCV 2018. A. Kolesnikov, L. Beyer, X. Zhai, J. Puigcerver, J. Yung, S. Gelly, and N. Houlsby. Big Transfer (BiT): General Visual Representation Learning (2019), arXiv preprint. S. Qiao, H. Wang, C. Liu, W. Shen, and A. Yuille. Weight Standardization (2019), arXiv preprint. S. Santurkar, D. Tsipras, A. Ilyas, and A. Madry. How Does Batch Normalization Help Optimization? (2018), NIPS 2018. Y. Wu, and K. He. Group Normalization (2018), ECCV 2018.
[ { "code": null, "e": 445, "s": 47, "text": "Batch Normalization (BN) has been an important component of many state-of-the-art deep learning models, especially in computer vision. It normalizes the layer inputs by the mean and variance computed within a batch, hence the name. For BN to work the batch size is required to be sufficiently large, usually at least 32. However, there are situations that we have to settle for a small batch size:" }, { "code": null, "e": 531, "s": 445, "text": "when each data sample is highly memory-consuming, e.g. video or high resolution image" }, { "code": null, "e": 625, "s": 531, "text": "when we train a very large neural network, which leaves little GPU memory for processing data" }, { "code": null, "e": 848, "s": 625, "text": "Therefore we need alternatives to BN which work well with small batch size. Group Normalization (GN) is one of the latest normalization methods that avoids exploiting the batch dimension, thus is independent of batch size." }, { "code": null, "e": 948, "s": 848, "text": "To motivate the formulation of GN we will first look at some of the previous normalization methods." }, { "code": null, "e": 1015, "s": 948, "text": "All of the following normalization methods perform the calculation" }, { "code": null, "e": 1043, "s": 1015, "text": "xi ← (xi - μi) / √(σi2 + ε)" }, { "code": null, "e": 1304, "s": 1043, "text": "for every coefficient xi of an input feature x. μi and σi2 are the mean and variance computed over a set Si of coefficients, and ε is a small constant added for numerical stability and to avoid division by zero. The only difference is how the set Si is chosen." }, { "code": null, "e": 1485, "s": 1304, "text": "To illustrate the computation of the normalization methods, we consider a batch of size N = 3, with input features a, b, and c. They have channels C = 4, height H = 1, width W = 2:" }, { "code": null, "e": 1629, "s": 1485, "text": "a = [ [[2, 3]], [[5, 7]], [[11, 13]], [[17, 19]] ]b = [ [[0, 1]], [[1, 2]], [[3, 5]], [[8, 13]] ]c = [ [[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]] ]" }, { "code": null, "e": 1711, "s": 1629, "text": "Hence the batch will have shape (N, C, H, W) = (3, 4, 1, 2). We take ε = 0.00001." }, { "code": null, "e": 1877, "s": 1711, "text": "BN normalizes the channels and computes μi and σi along the (N, H, W) axes. Si is defined as the set of coefficients in the batch that are in the same channel as xi." }, { "code": null, "e": 2047, "s": 1877, "text": "For the first coefficient ai = 2 of a, where i = (0, 0, 0), the corresponding μi and σi2 are computed over the coefficients of a, b, and c that are in the first channel:" }, { "code": null, "e": 2116, "s": 2047, "text": "μi = mean(2, 3, 0, 1, 1, 2) = 1.5σi2 = var(2, 3, 0, 1, 1, 2) = 0.917" }, { "code": null, "e": 2163, "s": 2116, "text": "Plugging these into the normalization formula," }, { "code": null, "e": 2207, "s": 2163, "text": "ai ← (2 - 1.5) / √(0.917 + 0.00001) = 0.522" }, { "code": null, "e": 2249, "s": 2207, "text": "Computing all the coefficients of a gives" }, { "code": null, "e": 2328, "s": 2249, "text": "a ← [ [[0.522, 1.567]], [[0.676, 1.690]], [[1.071, 1.630]], [[1.066, 1.492]] ]" }, { "code": null, "e": 2682, "s": 2328, "text": "Layer Normalization (LN) is designed to overcome the drawbacks of BN, including its constraints on batch size. It computes μi and σi along the (C, H, W) axes, with Si defined as all the coefficients that belong to the same input feature as xi. As a result, the computation for an input feature is entirely independent of other input features in a batch." }, { "code": null, "e": 2746, "s": 2682, "text": "All the coefficients of a are normalized by the same μi and σi2" }, { "code": null, "e": 2838, "s": 2746, "text": "μi = mean(2, 3, 5, 7, 11, 13, 17, 19) = 9.625σi2 = var(2, 3, 5, 7, 11, 13, 17, 19) = 35.734" }, { "code": null, "e": 2871, "s": 2838, "text": "Therefore applying LN to a gives" }, { "code": null, "e": 2954, "s": 2871, "text": "a ← [ [[-1.276, -1.108]], [[-0.773, -0.439]], [[0.230, 0.565]], [[1.234, 1.568]] ]" }, { "code": null, "e": 3296, "s": 2954, "text": "Instance Normalization (IN) can be viewed as applying the formula of BN to each input feature (a.k.a. instance) individually as if it is the only member in a batch. More precisely, IN computes μi and σi along the (H, W) axes, and Si is defined as the set of coefficients that are in the same input feature and also in the same channel as xi." }, { "code": null, "e": 3564, "s": 3296, "text": "Since the computation of IN is the same as that of BN with batch size = 1, IN actually makes the situation even worse in most cases. However, for style transfer tasks, IN is better at discarding contrast information of an image, and has superior performances than BN." }, { "code": null, "e": 3664, "s": 3564, "text": "For the first coefficient ai = 2 of a, where i = (0, 0, 0), the corresponding μi and σi2 are simply" }, { "code": null, "e": 3708, "s": 3664, "text": "μi = mean(2, 3) = 2.5σi2 = var(2, 3) = 0.25" }, { "code": null, "e": 3720, "s": 3708, "text": "which gives" }, { "code": null, "e": 3764, "s": 3720, "text": "ai ← (2 - 2.5) / √(0.25 + 0.00001) = -1.000" }, { "code": null, "e": 3794, "s": 3764, "text": "When we apply IN to a, we get" }, { "code": null, "e": 3877, "s": 3794, "text": "a ← [ [[-1.000, 1.000]], [[-1.000, 1.000]], [[-1.000, 1.000]], [[-1.000, 1.000]] ]" }, { "code": null, "e": 4089, "s": 3877, "text": "Previously we introduced IN as applying BN to each input feature individually as if batch size = 1. Notice that IN can also be viewed as applying LN to each channel individually as if the number of channels = 1." }, { "code": null, "e": 4393, "s": 4089, "text": "Group Normalization (GN) is a middle ground between IN and LN. It organizes the channels into different groups, and computes μi and σi along the (H, W) axes and along a group of channels. Si is then the set of coefficients that are in the same input feature and also in the same group of channels as xi." }, { "code": null, "e": 4841, "s": 4393, "text": "The number of groups G is a pre-defined hyperparameter, which is usually required to divide C. For simplicity we group the channels in a sequential order. So channels 1, ..., C / G belong to the 1st group, channels C / G + 1, ..., 2C / G belong to the 2nd group, and so on. When G = C, which means each group has only 1 channel, GN becomes IN. On the other hand, when G = 1, GN becomes LN. Therefore G controls the interpolation between IN and LN." }, { "code": null, "e": 5002, "s": 4841, "text": "For our example consider G = 2. To normalize the first coefficient ai = 2 of a where i = (0, 0, 0), we use the coefficients of a in the first 4 / 2 = 2 channels" }, { "code": null, "e": 5060, "s": 5002, "text": "μi = mean(2, 3, 5, 7) = 4.25σi2 = var(2, 3, 5, 7) = 3.687" }, { "code": null, "e": 5107, "s": 5060, "text": "Plugging these into the normalization formula," }, { "code": null, "e": 5153, "s": 5107, "text": "ai ← (2 - 4.25) / √(3.687 + 0.00001) = -1.172" }, { "code": null, "e": 5212, "s": 5153, "text": "For other coefficients of a, the computations are similar:" }, { "code": null, "e": 5295, "s": 5212, "text": "a ← [ [[-1.172, -0.651]], [[0.391, 1.432]], [[-1.265, -0.633]], [[0.633, 1.265]] ]" }, { "code": null, "e": 5367, "s": 5295, "text": "The following figure visualizes the relations among BN, LN, IN, and GN." }, { "code": null, "e": 5512, "s": 5367, "text": "The blue regions correspond to the sets Si for the computation μi and σi, which are then used to normalize any coefficients in the blue regions." }, { "code": null, "e": 5763, "s": 5512, "text": "From this figure we can see how GN interpolates between IN and LN. GN is better than IN as GN can exploit the dependence across the channels. It is also better than LN because it allows different distribution to be learned for each group of channels." }, { "code": null, "e": 5964, "s": 5763, "text": "When the batch size is small, GN consistently outperforms BN. However, when the batch size is significantly large, GN does not scale as well as BN and might not be able to match the performance of BN." }, { "code": null, "e": 6044, "s": 5964, "text": "TensorFlow: It is available via TensorFlow Addons tfa.layers.GroupNormalization" }, { "code": null, "e": 6072, "s": 6044, "text": "PyTorch: torch.nn.GroupNorm" }, { "code": null, "e": 6257, "s": 6072, "text": "Note that both implementations of GN have a learnable, per-channel linear transformation following the normalization by fault. This is similar to the implementations of BN, LN, and IN." }, { "code": null, "e": 6723, "s": 6257, "text": "The original paper of GN [4] is an excellent reference on the technical details of GN and also on the comparison of different normalization methods.Even though GN does not match BN when the batch size is large, GN + Weight Standardization [2] is able to match and even outperforms BN. We refer to [1] and [2] for some experiment results.[3] shows BN works by making the optimization landscape much smoother. This motivates the formulation of Weight Standardization." }, { "code": null, "e": 6872, "s": 6723, "text": "The original paper of GN [4] is an excellent reference on the technical details of GN and also on the comparison of different normalization methods." }, { "code": null, "e": 7062, "s": 6872, "text": "Even though GN does not match BN when the batch size is large, GN + Weight Standardization [2] is able to match and even outperforms BN. We refer to [1] and [2] for some experiment results." }, { "code": null, "e": 7191, "s": 7062, "text": "[3] shows BN works by making the optimization landscape much smoother. This motivates the formulation of Weight Standardization." }, { "code": null, "e": 7626, "s": 7191, "text": "A. Kolesnikov, L. Beyer, X. Zhai, J. Puigcerver, J. Yung, S. Gelly, and N. Houlsby. Big Transfer (BiT): General Visual Representation Learning (2019), arXiv preprint.S. Qiao, H. Wang, C. Liu, W. Shen, and A. Yuille. Weight Standardization (2019), arXiv preprint.S. Santurkar, D. Tsipras, A. Ilyas, and A. Madry. How Does Batch Normalization Help Optimization? (2018), NIPS 2018.Y. Wu, and K. He. Group Normalization (2018), ECCV 2018." }, { "code": null, "e": 7793, "s": 7626, "text": "A. Kolesnikov, L. Beyer, X. Zhai, J. Puigcerver, J. Yung, S. Gelly, and N. Houlsby. Big Transfer (BiT): General Visual Representation Learning (2019), arXiv preprint." }, { "code": null, "e": 7890, "s": 7793, "text": "S. Qiao, H. Wang, C. Liu, W. Shen, and A. Yuille. Weight Standardization (2019), arXiv preprint." }, { "code": null, "e": 8007, "s": 7890, "text": "S. Santurkar, D. Tsipras, A. Ilyas, and A. Madry. How Does Batch Normalization Help Optimization? (2018), NIPS 2018." } ]
ArrayList in Java - GeeksforGeeks
08 Mar, 2022 ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. Illustration: Example: The following implementation demonstrates how to create and use an ArrayList. Java // Java program to demonstrate the// working of ArrayList in Java import java.io.*;import java.util.*; class ArrayListExample { public static void main(String[] args) { // Size of the // ArrayList int n = 5; // Declaring the ArrayList with // initial size n ArrayList<Integer> arrli = new ArrayList<Integer>(n); // Appending new elements at // the end of the list for (int i = 1; i <= n; i++) arrli.add(i); // Printing elements System.out.println(arrli); // Remove element at index 3 arrli.remove(3); // Displaying the ArrayList // after deletion System.out.println(arrli); // Printing elements one by one for (int i = 0; i < arrli.size(); i++) System.out.print(arrli.get(i) + " "); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5 Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item: Creates a bigger-sized memory on heap memory (for example memory of double size). Copies the current memory elements to the new memory. New item is added now as there is bigger memory available now. Delete the old memory. Important Features: ArrayList inherits AbstractList class and implements the List interface. ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases. ArrayList in Java can be seen as a vector in C++. ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector. Let’s understand the Java ArrayList in depth. Look at the below image: In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are: AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class: 1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as: ArrayList arr = new ArrayList(); 2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as: ArrayList arr = new ArrayList(c); 3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as: ArrayList arr = new ArrayList(N); Note: You can also create a generic ArrayList: // Creating generic integer ArrayList ArrayList<Integer> arrli = new ArrayList<Integer>(); Let’s see how to perform some basics operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation. Adding element to List Changing elements Removing elements Iterating elements Operation 1: Adding Elements In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows: add(Object): This method is used to add an element at the end of the ArrayList. add(int index, Object): This method is used to add an element at a specific index in the ArrayList. Example: Java // Java Program to Add elements to An ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Array of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // Custom inputs al.add("Geeks"); al.add("Geeks"); // Here we are mentioning the index // at which it is to be added al.add(1, "For"); // Printing all the elements in an ArrayList System.out.println(al); }} [Geeks, For, Geeks] Operation 2: Changing Elements After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. Example Java // Java Program to Change elements in ArrayList // Importing all utility classesimport java.util.*; // main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist object of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to Arraylist // Custom input elements al.add("Geeks"); al.add("Geeks"); // Adding specifying the index to be added al.add(1, "Geeks"); // Printing the Arraylist elements System.out.println("Initial ArrayList " + al); // Setting element at 1st index al.set(1, "For"); // Printing the updated Arraylist System.out.println("Updated ArrayList " + al); }} Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks] Operation 3: Removing Elements In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows: remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed. remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated. Example Java // Java program to Remove Elements in ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an object of arraylist class ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // Custom addition al.add("Geeks"); al.add("Geeks"); // Adding element at specific index al.add(1, "For"); // Printing all elements of ArrayList System.out.println("Initial ArrayList " + al); // Removing element from above ArrayList al.remove(1); // Printing the updated Arraylist elements System.out.println("After the Index Removal " + al); // Removing this word element in ArrayList al.remove("Geeks"); // Now printing updated ArrayList System.out.println("After the Object Removal " + al); }} Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks] Operation 4: Iterating the ArrayList There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop. Example Java // Java program to Iterate the elements// in an ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // using standard add() method al.add("Geeks"); al.add("Geeks"); al.add(1, "For"); // Using the Get method and the // for loop for (int i = 0; i < al.size(); i++) { System.out.print(al.get(i) + " "); } System.out.println(); // Using the for each loop for (String str : al) System.out.print(str + " "); }} Geeks For Geeks Geeks For Geeks Must Read: Array vs ArrayList in Java KaashyapMSK solankimayank sagartomar9927 abhisheksonu1001 simmytarika5 Java - util package Java-ArrayList Java-Collections java-list Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java How to add an element to an Array in Java? Stream In Java
[ { "code": null, "e": 28870, "s": 28842, "text": "\n08 Mar, 2022" }, { "code": null, "e": 29166, "s": 28870, "text": "ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. " }, { "code": null, "e": 29181, "s": 29166, "text": "Illustration: " }, { "code": null, "e": 29268, "s": 29181, "text": "Example: The following implementation demonstrates how to create and use an ArrayList." }, { "code": null, "e": 29273, "s": 29268, "text": "Java" }, { "code": "// Java program to demonstrate the// working of ArrayList in Java import java.io.*;import java.util.*; class ArrayListExample { public static void main(String[] args) { // Size of the // ArrayList int n = 5; // Declaring the ArrayList with // initial size n ArrayList<Integer> arrli = new ArrayList<Integer>(n); // Appending new elements at // the end of the list for (int i = 1; i <= n; i++) arrli.add(i); // Printing elements System.out.println(arrli); // Remove element at index 3 arrli.remove(3); // Displaying the ArrayList // after deletion System.out.println(arrli); // Printing elements one by one for (int i = 0; i < arrli.size(); i++) System.out.print(arrli.get(i) + \" \"); }}", "e": 30133, "s": 29273, "text": null }, { "code": null, "e": 30171, "s": 30133, "text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]\n1 2 3 5 " }, { "code": null, "e": 30543, "s": 30171, "text": "Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:" }, { "code": null, "e": 30625, "s": 30543, "text": "Creates a bigger-sized memory on heap memory (for example memory of double size)." }, { "code": null, "e": 30679, "s": 30625, "text": "Copies the current memory elements to the new memory." }, { "code": null, "e": 30742, "s": 30679, "text": "New item is added now as there is bigger memory available now." }, { "code": null, "e": 30765, "s": 30742, "text": "Delete the old memory." }, { "code": null, "e": 30785, "s": 30765, "text": "Important Features:" }, { "code": null, "e": 30858, "s": 30785, "text": "ArrayList inherits AbstractList class and implements the List interface." }, { "code": null, "e": 31024, "s": 30858, "text": "ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection." }, { "code": null, "e": 31078, "s": 31024, "text": "Java ArrayList allows us to randomly access the list." }, { "code": null, "e": 31186, "s": 31078, "text": "ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases." }, { "code": null, "e": 31236, "s": 31186, "text": "ArrayList in Java can be seen as a vector in C++." }, { "code": null, "e": 31320, "s": 31236, "text": "ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector." }, { "code": null, "e": 31391, "s": 31320, "text": "Let’s understand the Java ArrayList in depth. Look at the below image:" }, { "code": null, "e": 31620, "s": 31391, "text": "In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:" }, { "code": null, "e": 32279, "s": 31620, "text": "AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods." }, { "code": null, "e": 32459, "s": 32279, "text": "AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods." }, { "code": null, "e": 32669, "s": 32459, "text": "CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list." }, { "code": null, "e": 32940, "s": 32669, "text": "AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods." }, { "code": null, "e": 33192, "s": 32940, "text": "In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class: " }, { "code": null, "e": 33350, "s": 33192, "text": "1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:" }, { "code": null, "e": 33385, "s": 33350, "text": "ArrayList arr = new ArrayList(); " }, { "code": null, "e": 33645, "s": 33385, "text": "2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as: " }, { "code": null, "e": 33681, "s": 33645, "text": "ArrayList arr = new ArrayList(c); " }, { "code": null, "e": 33894, "s": 33681, "text": "3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:" }, { "code": null, "e": 33930, "s": 33894, "text": "ArrayList arr = new ArrayList(N); " }, { "code": null, "e": 33977, "s": 33930, "text": "Note: You can also create a generic ArrayList:" }, { "code": null, "e": 34068, "s": 33977, "text": "// Creating generic integer ArrayList\nArrayList<Integer> arrli = new ArrayList<Integer>();" }, { "code": null, "e": 34221, "s": 34068, "text": "Let’s see how to perform some basics operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation." }, { "code": null, "e": 34244, "s": 34221, "text": "Adding element to List" }, { "code": null, "e": 34262, "s": 34244, "text": "Changing elements" }, { "code": null, "e": 34280, "s": 34262, "text": "Removing elements" }, { "code": null, "e": 34302, "s": 34280, "text": "Iterating elements " }, { "code": null, "e": 34331, "s": 34302, "text": "Operation 1: Adding Elements" }, { "code": null, "e": 34515, "s": 34331, "text": "In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows: " }, { "code": null, "e": 34595, "s": 34515, "text": "add(Object): This method is used to add an element at the end of the ArrayList." }, { "code": null, "e": 34695, "s": 34595, "text": "add(int index, Object): This method is used to add an element at a specific index in the ArrayList." }, { "code": null, "e": 34704, "s": 34695, "text": "Example:" }, { "code": null, "e": 34709, "s": 34704, "text": "Java" }, { "code": "// Java Program to Add elements to An ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Array of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // Custom inputs al.add(\"Geeks\"); al.add(\"Geeks\"); // Here we are mentioning the index // at which it is to be added al.add(1, \"For\"); // Printing all the elements in an ArrayList System.out.println(al); }}", "e": 35307, "s": 34709, "text": null }, { "code": null, "e": 35327, "s": 35307, "text": "[Geeks, For, Geeks]" }, { "code": null, "e": 35360, "s": 35329, "text": "Operation 2: Changing Elements" }, { "code": null, "e": 35675, "s": 35360, "text": "After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. " }, { "code": null, "e": 35683, "s": 35675, "text": "Example" }, { "code": null, "e": 35688, "s": 35683, "text": "Java" }, { "code": "// Java Program to Change elements in ArrayList // Importing all utility classesimport java.util.*; // main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist object of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to Arraylist // Custom input elements al.add(\"Geeks\"); al.add(\"Geeks\"); // Adding specifying the index to be added al.add(1, \"Geeks\"); // Printing the Arraylist elements System.out.println(\"Initial ArrayList \" + al); // Setting element at 1st index al.set(1, \"For\"); // Printing the updated Arraylist System.out.println(\"Updated ArrayList \" + al); }}", "e": 36452, "s": 35688, "text": null }, { "code": null, "e": 36530, "s": 36452, "text": "Initial ArrayList [Geeks, Geeks, Geeks]\nUpdated ArrayList [Geeks, For, Geeks]" }, { "code": null, "e": 36563, "s": 36532, "text": "Operation 3: Removing Elements" }, { "code": null, "e": 36754, "s": 36563, "text": "In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows: " }, { "code": null, "e": 36925, "s": 36754, "text": "remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed." }, { "code": null, "e": 37221, "s": 36925, "text": "remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated." }, { "code": null, "e": 37229, "s": 37221, "text": "Example" }, { "code": null, "e": 37234, "s": 37229, "text": "Java" }, { "code": "// Java program to Remove Elements in ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an object of arraylist class ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // Custom addition al.add(\"Geeks\"); al.add(\"Geeks\"); // Adding element at specific index al.add(1, \"For\"); // Printing all elements of ArrayList System.out.println(\"Initial ArrayList \" + al); // Removing element from above ArrayList al.remove(1); // Printing the updated Arraylist elements System.out.println(\"After the Index Removal \" + al); // Removing this word element in ArrayList al.remove(\"Geeks\"); // Now printing updated ArrayList System.out.println(\"After the Object Removal \" + al); }}", "e": 38205, "s": 37234, "text": null }, { "code": null, "e": 38315, "s": 38205, "text": "Initial ArrayList [Geeks, For, Geeks]\nAfter the Index Removal [Geeks, Geeks]\nAfter the Object Removal [Geeks]" }, { "code": null, "e": 38354, "s": 38317, "text": "Operation 4: Iterating the ArrayList" }, { "code": null, "e": 38567, "s": 38354, "text": "There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop. " }, { "code": null, "e": 38575, "s": 38567, "text": "Example" }, { "code": null, "e": 38580, "s": 38575, "text": "Java" }, { "code": "// Java program to Iterate the elements// in an ArrayList // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to ArrayList // using standard add() method al.add(\"Geeks\"); al.add(\"Geeks\"); al.add(1, \"For\"); // Using the Get method and the // for loop for (int i = 0; i < al.size(); i++) { System.out.print(al.get(i) + \" \"); } System.out.println(); // Using the for each loop for (String str : al) System.out.print(str + \" \"); }}", "e": 39336, "s": 38580, "text": null }, { "code": null, "e": 39369, "s": 39336, "text": "Geeks For Geeks \nGeeks For Geeks" }, { "code": null, "e": 39409, "s": 39371, "text": "Must Read: Array vs ArrayList in Java" }, { "code": null, "e": 39421, "s": 39409, "text": "KaashyapMSK" }, { "code": null, "e": 39435, "s": 39421, "text": "solankimayank" }, { "code": null, "e": 39450, "s": 39435, "text": "sagartomar9927" }, { "code": null, "e": 39467, "s": 39450, "text": "abhisheksonu1001" }, { "code": null, "e": 39480, "s": 39467, "text": "simmytarika5" }, { "code": null, "e": 39500, "s": 39480, "text": "Java - util package" }, { "code": null, "e": 39515, "s": 39500, "text": "Java-ArrayList" }, { "code": null, "e": 39532, "s": 39515, "text": "Java-Collections" }, { "code": null, "e": 39542, "s": 39532, "text": "java-list" }, { "code": null, "e": 39547, "s": 39542, "text": "Java" }, { "code": null, "e": 39566, "s": 39547, "text": "Technical Scripter" }, { "code": null, "e": 39571, "s": 39566, "text": "Java" }, { "code": null, "e": 39588, "s": 39571, "text": "Java-Collections" }, { "code": null, "e": 39686, "s": 39588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39695, "s": 39686, "text": "Comments" }, { "code": null, "e": 39708, "s": 39695, "text": "Old Comments" }, { "code": null, "e": 39752, "s": 39708, "text": "Split() String method in Java with examples" }, { "code": null, "e": 39788, "s": 39752, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 39813, "s": 39788, "text": "Reverse a string in Java" }, { "code": null, "e": 39845, "s": 39813, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 39876, "s": 39845, "text": "How to iterate any Map in Java" }, { "code": null, "e": 39900, "s": 39876, "text": "Singleton Class in Java" }, { "code": null, "e": 39928, "s": 39900, "text": "Initializing a List in Java" }, { "code": null, "e": 39974, "s": 39928, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 40017, "s": 39974, "text": "How to add an element to an Array in Java?" } ]
C# | Type.GetTypeCode() Method - GeeksforGeeks
20 May, 2019 Type.GetTypeCode() Method is used to get the underlying type code of the specified Type. Syntax: public static TypeCode GetTypeCode (Type type);Here, it takes the type whose underlying type code to get. Return Value: This method returns the code of the underlying type, or Empty if type is null. Below programs illustrate the use of Type.GetTypeCode() Method: Example 1: // C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // creating and initializing object Type Type type = typeof(int); // Getting the TypeCode TypeCode code = Type.GetTypeCode(type); // Display the Result Console.WriteLine("TypeCode is {0}", code); }} TypeCode is Int32 Example 2: // C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Calling get() Method get(typeof(int)); get(typeof(decimal)); get(typeof(double)); get(typeof(short)); get(typeof(string)); } // defining get Method public static void get(Type type) { // Getting Typecode TypeCode code = Type.GetTypeCode(type); // Display the Result Console.WriteLine("TypeCode of {1} is {0}", code, type); }} TypeCode of System.Int32 is Int32 TypeCode of System.Decimal is Decimal TypeCode of System.Double is Double TypeCode of System.Int16 is Int16 TypeCode of System.String is String Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.gettypecode?view=netframework-4.8 CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n20 May, 2019" }, { "code": null, "e": 25636, "s": 25547, "text": "Type.GetTypeCode() Method is used to get the underlying type code of the specified Type." }, { "code": null, "e": 25750, "s": 25636, "text": "Syntax: public static TypeCode GetTypeCode (Type type);Here, it takes the type whose underlying type code to get." }, { "code": null, "e": 25843, "s": 25750, "text": "Return Value: This method returns the code of the underlying type, or Empty if type is null." }, { "code": null, "e": 25907, "s": 25843, "text": "Below programs illustrate the use of Type.GetTypeCode() Method:" }, { "code": null, "e": 25918, "s": 25907, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // creating and initializing object Type Type type = typeof(int); // Getting the TypeCode TypeCode code = Type.GetTypeCode(type); // Display the Result Console.WriteLine(\"TypeCode is {0}\", code); }}", "e": 26360, "s": 25918, "text": null }, { "code": null, "e": 26379, "s": 26360, "text": "TypeCode is Int32\n" }, { "code": null, "e": 26390, "s": 26379, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Calling get() Method get(typeof(int)); get(typeof(decimal)); get(typeof(double)); get(typeof(short)); get(typeof(string)); } // defining get Method public static void get(Type type) { // Getting Typecode TypeCode code = Type.GetTypeCode(type); // Display the Result Console.WriteLine(\"TypeCode of {1} is {0}\", code, type); }}", "e": 27002, "s": 26390, "text": null }, { "code": null, "e": 27181, "s": 27002, "text": "TypeCode of System.Int32 is Int32\nTypeCode of System.Decimal is Decimal\nTypeCode of System.Double is Double\nTypeCode of System.Int16 is Int16\nTypeCode of System.String is String\n" }, { "code": null, "e": 27192, "s": 27181, "text": "Reference:" }, { "code": null, "e": 27282, "s": 27192, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.gettypecode?view=netframework-4.8" }, { "code": null, "e": 27296, "s": 27282, "text": "CSharp-method" }, { "code": null, "e": 27314, "s": 27296, "text": "CSharp-Type-Class" }, { "code": null, "e": 27317, "s": 27314, "text": "C#" }, { "code": null, "e": 27415, "s": 27317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27438, "s": 27415, "text": "Extension Method in C#" }, { "code": null, "e": 27466, "s": 27438, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27488, "s": 27466, "text": "Partial Classes in C#" }, { "code": null, "e": 27505, "s": 27488, "text": "C# | Inheritance" }, { "code": null, "e": 27534, "s": 27505, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27574, "s": 27534, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27597, "s": 27574, "text": "Switch Statement in C#" }, { "code": null, "e": 27637, "s": 27597, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27680, "s": 27637, "text": "C# | How to insert an element in an Array?" } ]
Deploying Containers with Docker, GCP Cloud Run and Flask-RESTful | by Mark Garvey | Towards Data Science
These days, data science practitioners find themselves relying on cloud platforms more and more, either for data storage, cloud computing, or a mix of both. This article will demonstrate how to leverage Cloud Run in GCP to access a dataset stored on Google BigQuery, apply a quick transformation, and present the result back to users through a Flask-RESTful API. Cloud Run is a service that allows you to construct and deploy containers that can be accessed via HTTP requests. Cloud Run is scalable and abstracts away infrastructure management so you can get things up and running quickly. What is a container you ask? A simple way to think about containers is that they are similar to a Virtual Machine (VM), but much smaller in scale and scope. With a VM, you typically have a virtual version of an entire OS running (such as a Windows PC running a Linux VM through something like VirtualBox.) This Linux VM will typically have a GUI, a web browser, word processing software, IDEs and a whole host of software accompanying it. With containers however, you can have the minimal amount of software necessary to perform your desired task, making them compact and efficient, easy to create, destroy and deploy on the fly. For example, the container in this article will just have Python 3.8 installed and nothing else. Cloud Run is well-suited to deploying stateless containers. For a good insight into stateful vs stateless containers, take a look at this article. The public dataset on BigQuery we will be looking at is the bigquery-public-data.usa_names.usa_1910_2013 dataset: Before getting started, you will need to create: A Project on GCP,a service account and a service account key. A Project on GCP, a service account and a service account key. For a guide on how to quickly do so, check out the BigQuery API docs. Once you have created a service account, you can create and download a .json service account key, which is used to authenticate you when trying to access BigQuery data through the BQ API. Access Google Cloud Shell and click ‘Open Editor’. You should see something like this: Next click ‘Cloud Code’ in the bottom left corner: This will bring up a menu of options. Select ‘New Application’: Then from the following options select ‘Cloud Run Application’ → ‘Python (Flask) : Cloud Run’. This gives you the sample Flask-based ‘Hello World’ application for Cloud Run that we will build on to access our BigQuery dataset. You should now have something like this: The next steps will be changing the provided app.py and Dockerfile, as well as adding some code of our own to access BigQuery. The first step is to slightly edit the existing Dockerfile to specify how our container will be created. Replace the existing Dockerfile code with: # Python image to use.FROM python:3.8# Set the working directory to /appWORKDIR /app# copy the requirements file used for dependenciesCOPY requirements.txt .# Install any needed packages specified in requirements.txtRUN pip install --trusted-host pypi.python.org -r requirements.txtRUN pip install flask-restfulRUN pip install --upgrade google-cloud-bigqueryRUN pip install --upgrade gcloudRUN pip install pandas# Copy the rest of the working directory contents into the container at /appCOPY . .# Run app.py when the container launchesENTRYPOINT ["python", "app.py"] This Dockerfile will: Build a container from the official Python 3.8 imageSet the working directory of the containerInstall the packages in the existing requirements.txt fileInstall the extra packages necessary (these could instead be added to the existing requirements.txt file if one wished)Copy other existing files in the working directory to the container’s working directory (his includes our service account key)Run app.py when the container launches Build a container from the official Python 3.8 image Set the working directory of the container Install the packages in the existing requirements.txt file Install the extra packages necessary (these could instead be added to the existing requirements.txt file if one wished) Copy other existing files in the working directory to the container’s working directory (his includes our service account key) Run app.py when the container launches Replace the code in the existing app.py with: import osimport requestsimport bqfrom flask import Flaskfrom flask_restful import Resource, Apiapp = Flask(__name__)api = Api(app)class QueryData(Resource): def get(self): return bq.run_()api.add_resource(QueryData, '/')if __name__ == '__main__': server_port = os.environ.get('PORT', '8080') app.run(debug=True, port=server_port, host='0.0.0.0') Flask-RESTful uses Resource objects to easily define HTTP methods (see the docs for more info). Above we define a Resource to get the results of our bq.py Python script which queries, sorts and returns the data. (It’s possible to create a number of resources and add them to the API using the .add_resource() method.) Below is the code file that will access the bigquery-data.usa_names.usa_1910_2013 dataset: bq.py def run_(): import os import pandas as pd from google.cloud import bigquery from google.oauth2 import service_account key_path = "./your_key.json" credentials = service_account.Credentials.from_service_account_file( key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"], ) client = bigquery.Client(credentials=credentials) query = """ SELECT name, SUM(number) as total_people FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = 'TX' GROUP BY name, state ORDER BY total_people DESC LIMIT 20 """ query_job = client.query(query) counts = [] names = [] for row in query_job: names.append(row["name"]) counts.append(row["total_people"]) # put names and name counts in a dataframe and sort #alphabetically, to simulate operating on data with a model results = {'Names': names, 'Name Counts': counts} df = pd.DataFrame.from_dict(results) # convert to DataFrame df = df.sort_values(by=['Names']) # sort alphabetically df = df.to_dict(orient='list') # convert to dictionary format return df Add this code to a new file name bq.py in the same directory as app.py and the Dockerfile: Breakdown of bq.py: This section will allow us to authenticate and access BigQuery to fetch our data: from google.cloud import bigqueryfrom google.oauth2 import service_accountkey_path = "./your_key.json"credentials = service_account.Credentials.from_service_account_file( key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"], )client = bigquery.Client(credentials=credentials) Note that key_path = “./your_key.json” must be changed to the name of your downloaded json service account key from earlier. To import your downloaded key from your computer’s downloads folder into the Cloud Shell editor, simply drag and drop the file into your browser window: The next section contains the query for our desired data: query = """ SELECT name, SUM(number) as total_people FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = 'TX' GROUP BY name, state ORDER BY total_people DESC LIMIT 20 """query_job = client.query(query) The remaining code simply applies sorting to the two data columns, sorting the columns according to the alphabetical order of the ‘Name’ column: counts = []names = [] for row in query_job: names.append(row["name"]) counts.append(row["total_people"]) # put names and name counts in a dataframe and sort #alphabetically, to simulate operating on data with a model results = {'Names': names, 'Name Counts': counts}df = pd.DataFrame.from_dict(results) # convert to DataFramedf = df.sort_values(by=['Names']) # sort alphabeticallydf = df.to_dict(orient='list') # convert to dictionary format return df The data must be returned in a json compatible format for use with Flask-RESTful, which is why we return the data in dictionary format. Finally, we can deploy our service to the web. Deploying with Cloud Run will generate a link that will allow access to the result of our data transformation. Once again, select ‘Cloud Code’ in the bottom left corner of the Cloud Shell Editor. This time click ‘Deploy to Cloud Run’ : Follow the steps to create a service, choose a region, allow unauthenticated invocations, and a build environment (either local or with Cloud Build). When you are ready, click Deploy! You can click ‘Show Detailed Logs’ to view the steps of the build and deployment taking place. When the container has finished building, click the provided link: This link opens a new tab to our final result — the queried BQ data with sorting applied! The two data columns have been sorted, according to the alphabetical order of the ‘Name’ column! While this is a simple operation, the potential for more complex workflows exists. Instead of sorting data, you could apply a trained machine learning model to make predictions and return the results through the API instead. Adding a nicer design to the page as well would help readability. As a side note, it is not considered best practice to have service account keys sitting in storage, there are other alternative authentication methods available for GCP. Also, keep an eye on billing for GCP products, the public BQ datasets can be queried up to 1TB for free but it is worth deactivating projects if you are not using them long term. I hoped this article was of use to you. If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/ Find me on LinkedIn: https://www.linkedin.com/in/mark-garvey/
[ { "code": null, "e": 535, "s": 172, "text": "These days, data science practitioners find themselves relying on cloud platforms more and more, either for data storage, cloud computing, or a mix of both. This article will demonstrate how to leverage Cloud Run in GCP to access a dataset stored on Google BigQuery, apply a quick transformation, and present the result back to users through a Flask-RESTful API." }, { "code": null, "e": 762, "s": 535, "text": "Cloud Run is a service that allows you to construct and deploy containers that can be accessed via HTTP requests. Cloud Run is scalable and abstracts away infrastructure management so you can get things up and running quickly." }, { "code": null, "e": 919, "s": 762, "text": "What is a container you ask? A simple way to think about containers is that they are similar to a Virtual Machine (VM), but much smaller in scale and scope." }, { "code": null, "e": 1201, "s": 919, "text": "With a VM, you typically have a virtual version of an entire OS running (such as a Windows PC running a Linux VM through something like VirtualBox.) This Linux VM will typically have a GUI, a web browser, word processing software, IDEs and a whole host of software accompanying it." }, { "code": null, "e": 1489, "s": 1201, "text": "With containers however, you can have the minimal amount of software necessary to perform your desired task, making them compact and efficient, easy to create, destroy and deploy on the fly. For example, the container in this article will just have Python 3.8 installed and nothing else." }, { "code": null, "e": 1636, "s": 1489, "text": "Cloud Run is well-suited to deploying stateless containers. For a good insight into stateful vs stateless containers, take a look at this article." }, { "code": null, "e": 1750, "s": 1636, "text": "The public dataset on BigQuery we will be looking at is the bigquery-public-data.usa_names.usa_1910_2013 dataset:" }, { "code": null, "e": 1799, "s": 1750, "text": "Before getting started, you will need to create:" }, { "code": null, "e": 1861, "s": 1799, "text": "A Project on GCP,a service account and a service account key." }, { "code": null, "e": 1879, "s": 1861, "text": "A Project on GCP," }, { "code": null, "e": 1924, "s": 1879, "text": "a service account and a service account key." }, { "code": null, "e": 2182, "s": 1924, "text": "For a guide on how to quickly do so, check out the BigQuery API docs. Once you have created a service account, you can create and download a .json service account key, which is used to authenticate you when trying to access BigQuery data through the BQ API." }, { "code": null, "e": 2269, "s": 2182, "text": "Access Google Cloud Shell and click ‘Open Editor’. You should see something like this:" }, { "code": null, "e": 2320, "s": 2269, "text": "Next click ‘Cloud Code’ in the bottom left corner:" }, { "code": null, "e": 2384, "s": 2320, "text": "This will bring up a menu of options. Select ‘New Application’:" }, { "code": null, "e": 2652, "s": 2384, "text": "Then from the following options select ‘Cloud Run Application’ → ‘Python (Flask) : Cloud Run’. This gives you the sample Flask-based ‘Hello World’ application for Cloud Run that we will build on to access our BigQuery dataset. You should now have something like this:" }, { "code": null, "e": 2779, "s": 2652, "text": "The next steps will be changing the provided app.py and Dockerfile, as well as adding some code of our own to access BigQuery." }, { "code": null, "e": 2927, "s": 2779, "text": "The first step is to slightly edit the existing Dockerfile to specify how our container will be created. Replace the existing Dockerfile code with:" }, { "code": null, "e": 3495, "s": 2927, "text": "# Python image to use.FROM python:3.8# Set the working directory to /appWORKDIR /app# copy the requirements file used for dependenciesCOPY requirements.txt .# Install any needed packages specified in requirements.txtRUN pip install --trusted-host pypi.python.org -r requirements.txtRUN pip install flask-restfulRUN pip install --upgrade google-cloud-bigqueryRUN pip install --upgrade gcloudRUN pip install pandas# Copy the rest of the working directory contents into the container at /appCOPY . .# Run app.py when the container launchesENTRYPOINT [\"python\", \"app.py\"]" }, { "code": null, "e": 3517, "s": 3495, "text": "This Dockerfile will:" }, { "code": null, "e": 3953, "s": 3517, "text": "Build a container from the official Python 3.8 imageSet the working directory of the containerInstall the packages in the existing requirements.txt fileInstall the extra packages necessary (these could instead be added to the existing requirements.txt file if one wished)Copy other existing files in the working directory to the container’s working directory (his includes our service account key)Run app.py when the container launches" }, { "code": null, "e": 4006, "s": 3953, "text": "Build a container from the official Python 3.8 image" }, { "code": null, "e": 4049, "s": 4006, "text": "Set the working directory of the container" }, { "code": null, "e": 4108, "s": 4049, "text": "Install the packages in the existing requirements.txt file" }, { "code": null, "e": 4228, "s": 4108, "text": "Install the extra packages necessary (these could instead be added to the existing requirements.txt file if one wished)" }, { "code": null, "e": 4355, "s": 4228, "text": "Copy other existing files in the working directory to the container’s working directory (his includes our service account key)" }, { "code": null, "e": 4394, "s": 4355, "text": "Run app.py when the container launches" }, { "code": null, "e": 4440, "s": 4394, "text": "Replace the code in the existing app.py with:" }, { "code": null, "e": 4802, "s": 4440, "text": "import osimport requestsimport bqfrom flask import Flaskfrom flask_restful import Resource, Apiapp = Flask(__name__)api = Api(app)class QueryData(Resource): def get(self): return bq.run_()api.add_resource(QueryData, '/')if __name__ == '__main__': server_port = os.environ.get('PORT', '8080') app.run(debug=True, port=server_port, host='0.0.0.0')" }, { "code": null, "e": 5120, "s": 4802, "text": "Flask-RESTful uses Resource objects to easily define HTTP methods (see the docs for more info). Above we define a Resource to get the results of our bq.py Python script which queries, sorts and returns the data. (It’s possible to create a number of resources and add them to the API using the .add_resource() method.)" }, { "code": null, "e": 5211, "s": 5120, "text": "Below is the code file that will access the bigquery-data.usa_names.usa_1910_2013 dataset:" }, { "code": null, "e": 5217, "s": 5211, "text": "bq.py" }, { "code": null, "e": 6348, "s": 5217, "text": "def run_(): import os import pandas as pd from google.cloud import bigquery from google.oauth2 import service_account key_path = \"./your_key.json\" credentials = service_account.Credentials.from_service_account_file( key_path, scopes=[\"https://www.googleapis.com/auth/cloud-platform\"], ) client = bigquery.Client(credentials=credentials) query = \"\"\" SELECT name, SUM(number) as total_people FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = 'TX' GROUP BY name, state ORDER BY total_people DESC LIMIT 20 \"\"\" query_job = client.query(query) counts = [] names = [] for row in query_job: names.append(row[\"name\"]) counts.append(row[\"total_people\"]) # put names and name counts in a dataframe and sort #alphabetically, to simulate operating on data with a model results = {'Names': names, 'Name Counts': counts} df = pd.DataFrame.from_dict(results) # convert to DataFrame df = df.sort_values(by=['Names']) # sort alphabetically df = df.to_dict(orient='list') # convert to dictionary format return df" }, { "code": null, "e": 6439, "s": 6348, "text": "Add this code to a new file name bq.py in the same directory as app.py and the Dockerfile:" }, { "code": null, "e": 6459, "s": 6439, "text": "Breakdown of bq.py:" }, { "code": null, "e": 6541, "s": 6459, "text": "This section will allow us to authenticate and access BigQuery to fetch our data:" }, { "code": null, "e": 6840, "s": 6541, "text": "from google.cloud import bigqueryfrom google.oauth2 import service_accountkey_path = \"./your_key.json\"credentials = service_account.Credentials.from_service_account_file( key_path, scopes=[\"https://www.googleapis.com/auth/cloud-platform\"], )client = bigquery.Client(credentials=credentials)" }, { "code": null, "e": 7118, "s": 6840, "text": "Note that key_path = “./your_key.json” must be changed to the name of your downloaded json service account key from earlier. To import your downloaded key from your computer’s downloads folder into the Cloud Shell editor, simply drag and drop the file into your browser window:" }, { "code": null, "e": 7176, "s": 7118, "text": "The next section contains the query for our desired data:" }, { "code": null, "e": 7413, "s": 7176, "text": "query = \"\"\" SELECT name, SUM(number) as total_people FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = 'TX' GROUP BY name, state ORDER BY total_people DESC LIMIT 20 \"\"\"query_job = client.query(query)" }, { "code": null, "e": 7558, "s": 7413, "text": "The remaining code simply applies sorting to the two data columns, sorting the columns according to the alphabetical order of the ‘Name’ column:" }, { "code": null, "e": 8028, "s": 7558, "text": "counts = []names = [] for row in query_job: names.append(row[\"name\"]) counts.append(row[\"total_people\"]) # put names and name counts in a dataframe and sort #alphabetically, to simulate operating on data with a model results = {'Names': names, 'Name Counts': counts}df = pd.DataFrame.from_dict(results) # convert to DataFramedf = df.sort_values(by=['Names']) # sort alphabeticallydf = df.to_dict(orient='list') # convert to dictionary format return df" }, { "code": null, "e": 8164, "s": 8028, "text": "The data must be returned in a json compatible format for use with Flask-RESTful, which is why we return the data in dictionary format." }, { "code": null, "e": 8322, "s": 8164, "text": "Finally, we can deploy our service to the web. Deploying with Cloud Run will generate a link that will allow access to the result of our data transformation." }, { "code": null, "e": 8447, "s": 8322, "text": "Once again, select ‘Cloud Code’ in the bottom left corner of the Cloud Shell Editor. This time click ‘Deploy to Cloud Run’ :" }, { "code": null, "e": 8726, "s": 8447, "text": "Follow the steps to create a service, choose a region, allow unauthenticated invocations, and a build environment (either local or with Cloud Build). When you are ready, click Deploy! You can click ‘Show Detailed Logs’ to view the steps of the build and deployment taking place." }, { "code": null, "e": 8793, "s": 8726, "text": "When the container has finished building, click the provided link:" }, { "code": null, "e": 8883, "s": 8793, "text": "This link opens a new tab to our final result — the queried BQ data with sorting applied!" }, { "code": null, "e": 9271, "s": 8883, "text": "The two data columns have been sorted, according to the alphabetical order of the ‘Name’ column! While this is a simple operation, the potential for more complex workflows exists. Instead of sorting data, you could apply a trained machine learning model to make predictions and return the results through the API instead. Adding a nicer design to the page as well would help readability." }, { "code": null, "e": 9620, "s": 9271, "text": "As a side note, it is not considered best practice to have service account keys sitting in storage, there are other alternative authentication methods available for GCP. Also, keep an eye on billing for GCP products, the public BQ datasets can be queried up to 1TB for free but it is worth deactivating projects if you are not using them long term." }, { "code": null, "e": 9771, "s": 9620, "text": "I hoped this article was of use to you. If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/" } ]
HTML | DOM Input Hidden value Property - GeeksforGeeks
20 Jan, 2022 The Input Hidden value property in HTML DOM is used to set or return the value of the value attribute of the hidden input field. The value attribute defines the default value of the input hidden field. Syntax: It returns the value property.hiddenObject.value hiddenObject.value It is used to set the value property.hiddenObject.value = text hiddenObject.value = text Property Values: This property contains single value text which is used to specify the initial value of the input hidden field. Return Value: It returns a string value which represent the value of the value attribute of the hidden input field. Example 1: This example illustrates how to return the hidden value property. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Hidden value Property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Hidden value Property</h2> <input type="hidden" id="GFG" value="GeeksForGeeks"> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:35px;"></p> <!-- Script to return the hidden value --> <script> function myGeeks() { var x = document.getElementById("GFG").value; document.getElementById("sudo").innerHTML = x; } </script></body> </html> Example 2: This example illustrate how to set the hidden property. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Hidden value Property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Hidden value Property</h2> <input type="hidden" id="GFG" value="GeeksForGeeks"> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:20px;"></p> <!-- Script to set hidden property value --> <script> function myGeeks() { var x = document.getElementById("GFG").value = "Sudo Placement"; document.getElementById("sudo").innerHTML = "The value of the value attribute" + " have changed to " + x; } </script></body> </html> Supported Browsers: The browser supported by DOM input Hidden value Property are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 chhabradhanvi HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24660, "s": 24632, "text": "\n20 Jan, 2022" }, { "code": null, "e": 24862, "s": 24660, "text": "The Input Hidden value property in HTML DOM is used to set or return the value of the value attribute of the hidden input field. The value attribute defines the default value of the input hidden field." }, { "code": null, "e": 24870, "s": 24862, "text": "Syntax:" }, { "code": null, "e": 24919, "s": 24870, "text": "It returns the value property.hiddenObject.value" }, { "code": null, "e": 24938, "s": 24919, "text": "hiddenObject.value" }, { "code": null, "e": 25001, "s": 24938, "text": "It is used to set the value property.hiddenObject.value = text" }, { "code": null, "e": 25027, "s": 25001, "text": "hiddenObject.value = text" }, { "code": null, "e": 25155, "s": 25027, "text": "Property Values: This property contains single value text which is used to specify the initial value of the input hidden field." }, { "code": null, "e": 25271, "s": 25155, "text": "Return Value: It returns a string value which represent the value of the value attribute of the hidden input field." }, { "code": null, "e": 25348, "s": 25271, "text": "Example 1: This example illustrates how to return the hidden value property." }, { "code": null, "e": 25353, "s": 25348, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Hidden value Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Hidden value Property</h2> <input type=\"hidden\" id=\"GFG\" value=\"GeeksForGeeks\"> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:35px;\"></p> <!-- Script to return the hidden value --> <script> function myGeeks() { var x = document.getElementById(\"GFG\").value; document.getElementById(\"sudo\").innerHTML = x; } </script></body> </html> ", "e": 26086, "s": 25353, "text": null }, { "code": null, "e": 26153, "s": 26086, "text": "Example 2: This example illustrate how to set the hidden property." }, { "code": null, "e": 26158, "s": 26153, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Hidden value Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Hidden value Property</h2> <input type=\"hidden\" id=\"GFG\" value=\"GeeksForGeeks\"> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:20px;\"></p> <!-- Script to set hidden property value --> <script> function myGeeks() { var x = document.getElementById(\"GFG\").value = \"Sudo Placement\"; document.getElementById(\"sudo\").innerHTML = \"The value of the value attribute\" + \" have changed to \" + x; } </script></body> </html> ", "e": 27003, "s": 26158, "text": null }, { "code": null, "e": 27098, "s": 27003, "text": "Supported Browsers: The browser supported by DOM input Hidden value Property are listed below:" }, { "code": null, "e": 27112, "s": 27098, "text": "Google Chrome" }, { "code": null, "e": 27130, "s": 27112, "text": "Internet Explorer" }, { "code": null, "e": 27138, "s": 27130, "text": "Firefox" }, { "code": null, "e": 27144, "s": 27138, "text": "Opera" }, { "code": null, "e": 27151, "s": 27144, "text": "Safari" }, { "code": null, "e": 27288, "s": 27151, "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": 27308, "s": 27288, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27322, "s": 27308, "text": "chhabradhanvi" }, { "code": null, "e": 27331, "s": 27322, "text": "HTML-DOM" }, { "code": null, "e": 27336, "s": 27331, "text": "HTML" }, { "code": null, "e": 27353, "s": 27336, "text": "Web Technologies" }, { "code": null, "e": 27358, "s": 27353, "text": "HTML" }, { "code": null, "e": 27456, "s": 27358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27465, "s": 27456, "text": "Comments" }, { "code": null, "e": 27478, "s": 27465, "text": "Old Comments" }, { "code": null, "e": 27526, "s": 27478, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27563, "s": 27526, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27613, "s": 27563, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27663, "s": 27613, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27687, "s": 27663, "text": "REST API (Introduction)" }, { "code": null, "e": 27743, "s": 27687, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27776, "s": 27743, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27819, "s": 27776, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27880, "s": 27819, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to Configure Spring Profile in Tomcat ? - 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 There are multiple ways to configure Spring profile in tomcat. Let’s see here. If you are running the application in your local, you can set the active profile using -Dspring-boot.run.profiles=test/dev/prod property as a parameter to your maven or Gradle run command. Example: #maven mvnw spring-boot:run -Dspring-boot.run.profiles=dev #Gradle gradlew bootRun -Dspring-boot.run.profiles=dev To configure the same in Eclipse tomcat, select Run -> Run Configurations and choose your Tomcat run configuration. Click the Arguments tab and add -Dspring.profiles.active=dev at the end of VM arguments. Again you can have multiple options here to configure Spring profile in tomcat in the external config, the most prominent way is to set the profile in catalina.properties. Add profile in catalina.properties file by omitting -D spring.profiles.active=dev ./startup.sh ed JARs during scanning can improve startup time and JSP compilation time. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.4.RELEASE) 2020-05-05 08:02:13.992 INFO 192322 --- [ main] c.s.SampleApplication : Starting SampleApplication v0.0.1-SNAPSHOT on localhost.localdomain with PID 192322 (/opt/cgoka/tomcat/webapps/sample_application/WEB-INF/classes started by root in /root) 2020-05-05 08:02:13.996 INFO 192322 --- [ main] c.s.SampleApplication : The following profiles are active: dev Now you can see the log message “The following profiles are active: dev” like above. How to implement Spring Boot Profiles Happy Learning 🙂 Spring Boot Environment Properties reading based on activeprofile How to enable Swagger in Spring Boot Application How to set Spring Boot SetTimeZone External Apache ActiveMQ Spring Boot Example How to use Spring Boot Random Port Spring Boot MongoDB + Spring Data Example Spring Boot Basic Authentication Example How to Create own Spring Boot Error Page How To Change Spring Boot Context Path Step By Step Spring Boot Docker Deployment Example SSL Spring Boot HTTPs Enabling Example How to set Spring Boot Tomcat session timeout How to change Spring Boot Tomcat Port Number Spring Boot How to change the Tomcat to Jetty Server Spring Boot JNDI Configuration – External Tomcat Spring Boot Environment Properties reading based on activeprofile How to enable Swagger in Spring Boot Application How to set Spring Boot SetTimeZone External Apache ActiveMQ Spring Boot Example How to use Spring Boot Random Port Spring Boot MongoDB + Spring Data Example Spring Boot Basic Authentication Example How to Create own Spring Boot Error Page How To Change Spring Boot Context Path Step By Step Spring Boot Docker Deployment Example SSL Spring Boot HTTPs Enabling Example How to set Spring Boot Tomcat session timeout How to change Spring Boot Tomcat Port Number Spring Boot How to change the Tomcat to Jetty Server Spring Boot JNDI Configuration – External Tomcat Adam January 22, 2021 at 10:04 pm - Reply how to set profile only for specific .war when using external tomcat? for example i have two apps and one of them is using profile “dev” and second app is using profile “prod” Adam January 22, 2021 at 10:04 pm - Reply how to set profile only for specific .war when using external tomcat? for example i have two apps and one of them is using profile “dev” and second app is using profile “prod” how to set profile only for specific .war when using external tomcat? for example i have two apps and one of them is using profile “dev” and second app is using profile “prod” Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 477, "s": 398, "text": "There are multiple ways to configure Spring profile in tomcat. Let’s see here." }, { "code": null, "e": 675, "s": 477, "text": "If you are running the application in your local, you can set the active profile using -Dspring-boot.run.profiles=test/dev/prod property as a parameter to your maven or Gradle run command.\nExample:" }, { "code": null, "e": 791, "s": 675, "text": "#maven \nmvnw spring-boot:run -Dspring-boot.run.profiles=dev\n#Gradle\ngradlew bootRun -Dspring-boot.run.profiles=dev\n" }, { "code": null, "e": 996, "s": 791, "text": "To configure the same in Eclipse tomcat, select Run -> Run Configurations and choose your Tomcat run configuration. Click the Arguments tab and add -Dspring.profiles.active=dev at the end of VM arguments." }, { "code": null, "e": 1168, "s": 996, "text": "Again you can have multiple options here to configure Spring profile in tomcat in the external config, the most prominent way is to set the profile in catalina.properties." }, { "code": null, "e": 1223, "s": 1168, "text": "Add profile in catalina.properties file by omitting -D" }, { "code": null, "e": 1250, "s": 1223, "text": "spring.profiles.active=dev" }, { "code": null, "e": 2035, "s": 1250, "text": "./startup.sh\n\ned JARs during scanning can improve startup time and JSP compilation time.\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.2.4.RELEASE)\n\n2020-05-05 08:02:13.992 INFO 192322 --- [ main] c.s.SampleApplication : Starting SampleApplication v0.0.1-SNAPSHOT on localhost.localdomain with PID 192322 (/opt/cgoka/tomcat/webapps/sample_application/WEB-INF/classes started by root in /root)\n2020-05-05 08:02:13.996 INFO 192322 --- [ main] c.s.SampleApplication : The following profiles are active: dev\n" }, { "code": null, "e": 2120, "s": 2035, "text": "Now you can see the log message “The following profiles are active: dev” like above." }, { "code": null, "e": 2158, "s": 2120, "text": "How to implement Spring Boot Profiles" }, { "code": null, "e": 2175, "s": 2158, "text": "Happy Learning 🙂" }, { "code": null, "e": 2853, "s": 2175, "text": "\nSpring Boot Environment Properties reading based on activeprofile\nHow to enable Swagger in Spring Boot Application\nHow to set Spring Boot SetTimeZone\nExternal Apache ActiveMQ Spring Boot Example\nHow to use Spring Boot Random Port\nSpring Boot MongoDB + Spring Data Example\nSpring Boot Basic Authentication Example\nHow to Create own Spring Boot Error Page\nHow To Change Spring Boot Context Path\nStep By Step Spring Boot Docker Deployment Example\nSSL Spring Boot HTTPs Enabling Example\nHow to set Spring Boot Tomcat session timeout\nHow to change Spring Boot Tomcat Port Number\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot JNDI Configuration – External Tomcat\n" }, { "code": null, "e": 2919, "s": 2853, "text": "Spring Boot Environment Properties reading based on activeprofile" }, { "code": null, "e": 2968, "s": 2919, "text": "How to enable Swagger in Spring Boot Application" }, { "code": null, "e": 3003, "s": 2968, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 3048, "s": 3003, "text": "External Apache ActiveMQ Spring Boot Example" }, { "code": null, "e": 3083, "s": 3048, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 3125, "s": 3083, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 3166, "s": 3125, "text": "Spring Boot Basic Authentication Example" }, { "code": null, "e": 3207, "s": 3166, "text": "How to Create own Spring Boot Error Page" }, { "code": null, "e": 3246, "s": 3207, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 3297, "s": 3246, "text": "Step By Step Spring Boot Docker Deployment Example" }, { "code": null, "e": 3336, "s": 3297, "text": "SSL Spring Boot HTTPs Enabling Example" }, { "code": null, "e": 3382, "s": 3336, "text": "How to set Spring Boot Tomcat session timeout" }, { "code": null, "e": 3427, "s": 3382, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 3480, "s": 3427, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 3529, "s": 3480, "text": "Spring Boot JNDI Configuration – External Tomcat" }, { "code": null, "e": 3760, "s": 3529, "text": "\n\n\n\n\n\nAdam\nJanuary 22, 2021 at 10:04 pm - Reply \n\nhow to set profile only for specific .war when using external tomcat?\nfor example i have two apps and one of them is using profile “dev” and second app is using profile “prod”\n\n\n\n\n" }, { "code": null, "e": 3989, "s": 3760, "text": "\n\n\n\n\nAdam\nJanuary 22, 2021 at 10:04 pm - Reply \n\nhow to set profile only for specific .war when using external tomcat?\nfor example i have two apps and one of them is using profile “dev” and second app is using profile “prod”\n\n\n\n" }, { "code": null, "e": 4165, "s": 3989, "text": "how to set profile only for specific .war when using external tomcat?\nfor example i have two apps and one of them is using profile “dev” and second app is using profile “prod”" }, { "code": null, "e": 4171, "s": 4169, "text": "Δ" }, { "code": null, "e": 4198, "s": 4171, "text": " Spring Boot – Hello World" }, { "code": null, "e": 4225, "s": 4198, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 4259, "s": 4225, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 4300, "s": 4259, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 4345, "s": 4300, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 4383, "s": 4345, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 4417, "s": 4383, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 4448, "s": 4417, "text": " Spring Boot – Properties File" }, { "code": null, "e": 4482, "s": 4448, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 4515, "s": 4482, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 4548, "s": 4515, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 4588, "s": 4548, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 4613, "s": 4588, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 4644, "s": 4613, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 4668, "s": 4644, "text": " Spring Boot – Actuator" }, { "code": null, "e": 4714, "s": 4668, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 4737, "s": 4714, "text": " Spring Boot – Swagger" }, { "code": null, "e": 4764, "s": 4737, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 4810, "s": 4764, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 4850, "s": 4810, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 4879, "s": 4850, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 4913, "s": 4879, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 4943, "s": 4913, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 4979, "s": 4943, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 5012, "s": 4979, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 5045, "s": 5012, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 5089, "s": 5045, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 5123, "s": 5089, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 5155, "s": 5123, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 5183, "s": 5155, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 5214, "s": 5183, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 5255, "s": 5214, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 5289, "s": 5255, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 5314, "s": 5289, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 5348, "s": 5314, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 5384, "s": 5348, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 5430, "s": 5384, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 5481, "s": 5430, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 5523, "s": 5481, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 5554, "s": 5523, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 5577, "s": 5554, "text": " Spring Boot – EhCache" }, { "code": null, "e": 5607, "s": 5577, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 5637, "s": 5607, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 5686, "s": 5637, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 5720, "s": 5686, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 5753, "s": 5720, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 5782, "s": 5753, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 5814, "s": 5782, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 5851, "s": 5814, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 5880, "s": 5851, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 5909, "s": 5880, "text": " Spring Boot – MockMvc JUnit" } ]
What are objects in C#?
Like any other object-oriented language, C# also has object and classes. Objects are real-world entities and instance of a class. Access the members of the class using an object. To access the class members, you need to use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a member, for example, Box b1 = new Box(); Above you can see Box1 is our object. We will use it to access the members − b1.height = 7.0; You can also use it to call member functions − b1.getVolume(); The following is an example showing how objects and class work in C# − Live Demo using System; namespace BoxApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } public double getVolume() { return length * breadth * height; } } class Boxtester { static void Main(string[] args) { // Creating two objects Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); double volume; // using objects to call the member functions Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine("Volume of Box1 : {0}" ,volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine("Volume of Box2 : {0}", volume); Console.ReadKey(); } } } Volume of Box1 : 210 Volume of Box2 : 1560
[ { "code": null, "e": 1241, "s": 1062, "text": "Like any other object-oriented language, C# also has object and classes. Objects are real-world entities and instance of a class. Access the members of the class using an object." }, { "code": null, "e": 1415, "s": 1241, "text": "To access the class members, you need to use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a member, for example," }, { "code": null, "e": 1435, "s": 1415, "text": "Box b1 = new Box();" }, { "code": null, "e": 1512, "s": 1435, "text": "Above you can see Box1 is our object. We will use it to access the members −" }, { "code": null, "e": 1529, "s": 1512, "text": "b1.height = 7.0;" }, { "code": null, "e": 1576, "s": 1529, "text": "You can also use it to call member functions −" }, { "code": null, "e": 1592, "s": 1576, "text": "b1.getVolume();" }, { "code": null, "e": 1663, "s": 1592, "text": "The following is an example showing how objects and class work in C# −" }, { "code": null, "e": 1674, "s": 1663, "text": " Live Demo" }, { "code": null, "e": 2975, "s": 1674, "text": "using System;\n\nnamespace BoxApplication {\n class Box {\n private double length; // Length of a box\n private double breadth; // Breadth of a box\n private double height; // Height of a box\n\n public void setLength( double len ) {\n length = len;\n }\n\n public void setBreadth( double bre ) {\n breadth = bre;\n }\n\n public void setHeight( double hei ) {\n height = hei;\n }\n\n public double getVolume() {\n return length * breadth * height;\n }\n }\n\n class Boxtester {\n static void Main(string[] args) {\n // Creating two objects\n Box Box1 = new Box(); // Declare Box1 of type Box\n Box Box2 = new Box();\n double volume;\n\n // using objects to call the member functions\n Box1.setLength(6.0);\n Box1.setBreadth(7.0);\n Box1.setHeight(5.0);\n\n // box 2 specification\n Box2.setLength(12.0);\n Box2.setBreadth(13.0);\n Box2.setHeight(10.0);\n\n // volume of box 1\n volume = Box1.getVolume();\n Console.WriteLine(\"Volume of Box1 : {0}\" ,volume);\n\n // volume of box 2\n volume = Box2.getVolume();\n Console.WriteLine(\"Volume of Box2 : {0}\", volume);\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3018, "s": 2975, "text": "Volume of Box1 : 210\nVolume of Box2 : 1560" } ]
Android - Text To Speech
Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages. Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListener. Its syntax is given below − private EditText write; ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { } }); In this listener, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below − ttobj.setLanguage(Locale.UK); The method setLanguage takes an Locale object as parameter. The list of some of the locales available are given below − Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below − ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); Apart from the speak method, there are some other methods available in the TextToSpeech class. They are listed below − addSpeech(String text, String filename) This method adds a mapping between a string of text and a sound file. getLanguage() This method returns a Locale instance describing the language. isSpeaking() This method checks whether the TextToSpeech engine is busy speaking. setPitch(float pitch) This method sets the speech pitch for the TextToSpeech engine. setSpeechRate(float speechRate) This method sets the speech rate. shutdown() This method releases the resources used by the TextToSpeech engine. stop() This method stop the speak. The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it. To experiment with this example , you need to run this on an actual device. Here is the content of src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.Locale; import android.widget.Toast; public class MainActivity extends Activity { TextToSpeech t1; EditText ed1; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1=(EditText)findViewById(R.id.editText); b1=(Button)findViewById(R.id.button); t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status != TextToSpeech.ERROR) { t1.setLanguage(Locale.UK); } } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String toSpeak = ed1.getText().toString(); Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show(); t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } }); } public void onPause(){ if(t1 !=null){ t1.stop(); t1.shutdown(); } super.onPause(); } } Here is the content of activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:transitionGroup="true"> <TextView android:text="Text to Speech" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:theme="@style/Base.TextAppearance.AppCompat" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_below="@+id/imageView" android:layout_marginTop="46dp" android:hint="Enter Text" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textColor="#ff7aff10" android:textColorHint="#ffff23d1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text to Speech" android:id="@+id/button" android:layout_below="@+id/editText" android:layout_centerHorizontal="true" android:layout_marginTop="46dp" /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name="app_name">My Application</string> </resources> Here is the content of AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" > <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display following screen. Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below − Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below − 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3756, "s": 3607, "text": "Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages." }, { "code": null, "e": 3949, "s": 3756, "text": "Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListener. Its syntax is given below −" }, { "code": null, "e": 4115, "s": 3949, "text": "private EditText write;\nttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {\n @Override\n public void onInit(int status) {\n }\n});" }, { "code": null, "e": 4310, "s": 4115, "text": "In this listener, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below −" }, { "code": null, "e": 4341, "s": 4310, "text": "ttobj.setLanguage(Locale.UK);\n" }, { "code": null, "e": 4461, "s": 4341, "text": "The method setLanguage takes an Locale object as parameter. The list of some of the locales available are given below −" }, { "code": null, "e": 4579, "s": 4461, "text": "Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below −" }, { "code": null, "e": 4633, "s": 4579, "text": "ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);" }, { "code": null, "e": 4752, "s": 4633, "text": "Apart from the speak method, there are some other methods available in the TextToSpeech class. They are listed below −" }, { "code": null, "e": 4792, "s": 4752, "text": "addSpeech(String text, String filename)" }, { "code": null, "e": 4862, "s": 4792, "text": "This method adds a mapping between a string of text and a sound file." }, { "code": null, "e": 4876, "s": 4862, "text": "getLanguage()" }, { "code": null, "e": 4939, "s": 4876, "text": "This method returns a Locale instance describing the language." }, { "code": null, "e": 4952, "s": 4939, "text": "isSpeaking()" }, { "code": null, "e": 5021, "s": 4952, "text": "This method checks whether the TextToSpeech engine is busy speaking." }, { "code": null, "e": 5043, "s": 5021, "text": "setPitch(float pitch)" }, { "code": null, "e": 5106, "s": 5043, "text": "This method sets the speech pitch for the TextToSpeech engine." }, { "code": null, "e": 5138, "s": 5106, "text": "setSpeechRate(float speechRate)" }, { "code": null, "e": 5172, "s": 5138, "text": "This method sets the speech rate." }, { "code": null, "e": 5183, "s": 5172, "text": "shutdown()" }, { "code": null, "e": 5251, "s": 5183, "text": "This method releases the resources used by the TextToSpeech engine." }, { "code": null, "e": 5258, "s": 5251, "text": "stop()" }, { "code": null, "e": 5286, "s": 5258, "text": "This method stop the speak." }, { "code": null, "e": 5426, "s": 5286, "text": "The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it." }, { "code": null, "e": 5502, "s": 5426, "text": "To experiment with this example , you need to run this on an actual device." }, { "code": null, "e": 5548, "s": 5502, "text": "Here is the content of src/MainActivity.java." }, { "code": null, "e": 6934, "s": 5548, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.speech.tts.TextToSpeech;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport java.util.Locale;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n TextToSpeech t1;\n EditText ed1;\n Button b1;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ed1=(EditText)findViewById(R.id.editText);\n b1=(Button)findViewById(R.id.button);\n\n t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {\n @Override\n public void onInit(int status) {\n if(status != TextToSpeech.ERROR) {\n t1.setLanguage(Locale.UK);\n }\n }\n });\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String toSpeak = ed1.getText().toString();\n Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();\n t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);\n }\n });\n }\n\n public void onPause(){\n if(t1 !=null){\n t1.stop();\n t1.shutdown();\n }\n super.onPause();\n }\n}" }, { "code": null, "e": 6975, "s": 6934, "text": "Here is the content of activity_main.xml" }, { "code": null, "e": 9276, "s": 6975, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\"\n android:transitionGroup=\"true\">\n \n <TextView android:text=\"Text to Speech\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:theme=\"@style/Base.TextAppearance.AppCompat\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_below=\"@+id/imageView\"\n android:layout_marginTop=\"46dp\"\n android:hint=\"Enter Text\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:textColor=\"#ff7aff10\"\n android:textColorHint=\"#ffff23d1\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Text to Speech\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/editText\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"46dp\" />\n\n</RelativeLayout>" }, { "code": null, "e": 9312, "s": 9276, "text": "Here is the content of Strings.xml." }, { "code": null, "e": 9388, "s": 9312, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>" }, { "code": null, "e": 9431, "s": 9388, "text": "Here is the content of AndroidManifest.xml" }, { "code": null, "e": 10125, "s": 9431, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" >\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 10506, "s": 10125, "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. Before starting your application, android studio will display following window to select an option where you want to run your Android application." }, { "code": null, "e": 10616, "s": 10506, "text": "Select your mobile device as an option and then check your mobile device which will display following screen." }, { "code": null, "e": 10785, "s": 10616, "text": "Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below −" }, { "code": null, "e": 10907, "s": 10785, "text": "Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below −" }, { "code": null, "e": 10942, "s": 10907, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10954, "s": 10942, "text": " Aditya Dua" }, { "code": null, "e": 10989, "s": 10954, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11003, "s": 10989, "text": " Sharad Kumar" }, { "code": null, "e": 11035, "s": 11003, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11052, "s": 11035, "text": " Abhilash Nelson" }, { "code": null, "e": 11087, "s": 11052, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11104, "s": 11087, "text": " Abhilash Nelson" }, { "code": null, "e": 11139, "s": 11104, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11156, "s": 11139, "text": " Abhilash Nelson" }, { "code": null, "e": 11189, "s": 11156, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11206, "s": 11189, "text": " Abhilash Nelson" }, { "code": null, "e": 11213, "s": 11206, "text": " Print" }, { "code": null, "e": 11224, "s": 11213, "text": " Add Notes" } ]
How Does Linear Regression Actually Work? | by Anas Al-Masri | Towards Data Science
Linear Regression is arguably one of the most famous topics in both statistics and Machine Learning. It is so essential to the point where it withholds a significant part in almost any Machine Learning course out there. However, it could be a bit tricky to wrap the head around, especially if one has no statistics background. Linear Regression can be considered a Machine Learning algorithm that allows us to map numeric inputs to numeric outputs, fitting a line into the data points. In other words, Linear Regression is a way of modelling the relationship between one or more variables. From the Machine Learning perspective, this is done to ensure generalization — giving the model the ability to predict outputs for inputs it has never seen before. If you read any of my other posts here on Medium, you will notice that I try to emphasize on the idea of generalization as much as possible. Generalization is the essence of Machine Learning. The whole idea of having this artificial form of intelligence relies on the process of teaching a model so well to the point where it can “act” on its own. In other words, you want the model to not be limited to whatever it has learned. Think of it as a child. If your child has only seen cats his whole life — for some disturbing reason that you imposed on him — and if at some point you decide to show him a picture of a dog, you’d expect him to know that the dog is not a cat. It is not something he has learned. So a group of creative Tech enthusiasts started a company in Silicon Valley. This start-up — called Banana — is so innovative that they have been growing constantly since 2016. You, the wealthy investor, would like to know whether to put your money on Banana’s success in the next year or not. Let’s assume that you don’t want to risk a lot of money, especially since the stakes are high in Silicon Valley. So you decide to buy a few shares, instead of investing into a big portion of the company. You take a look at the Banana’s stock prices ever since they were kick-started, and you see the following figure. Well, you can definitely see the trend. Banana is growing like crazy, kicking up their stock price from 100 dollars to 500 in just three years. You only care about how the price is going to be like in the year 2021, because you want to give your investment some time to blossom along with the company. Optimistically speaking, it looks like you will be growing your money in the upcoming years. The trend is likely not to go through a sudden, drastic change. This leads to you hypothesizing that the stock price will fall somewhere above the $500 indicator. Here’s an interesting thought. Based on the stock price records of the last couple of years you were able to predict what the stock price is going to be like. You were able to infer the range of the new stock price (that doesn’t exist on the plot) for a year that we don’t have data for (the year 2021). Well — kinda. What you just did is infer your model (that head of yours) to generalize — predict the y-value for an x-value that is not even in your knowledge. However, this is not accurate in any way. You couldn’t specify what exactly is the stock price most likely going to be. For all you know, it is probably going to be above 500 dollars. Here is where Linear Regression (LR) comes into play. The essence of LR is to find the line that best fits the data points on the plot, so that we can, more or less, know exactly where the stock price is likely to fall in the year 2021. Let’s examine the LR-generated line (in red) above, by looking at the importance of it. It looks like, with just a little modification, we were able to realize that Banana’s stock price is likely to be worth a little bit higher than $600 by the year 2021. Obviously, this is an oversimplified example. However, the process stays the same. Linear Regression as an algorithm relies on the concept of lowering the cost to maximize the performance. We will examine this concept, and how we got the red line on the plot next. To get the technicalities out of the way. What I described in the previous section is referred to as Univariate Linear Regression, because we are trying to map one independent variable (x-value) to one dependent variable (y-value). This is in contrast to Multivariate Linear Regression, where we try to map multiple independent variables (i.e. features) to a dependent variable (i.e. labels). Now, let’s get down to business. Any straight line on a plot follows the formula: f(X) = M.X + B Where M is the slope of the line, B is the y-intercept that allows vertical movement of the line, and X which is the function’s input value. In terms of Machine Learning, this follows the convention: h(X) = W0 + W1.X Where W0 and W1 are weights, X is the input feature, and h(X) is the label (i.e. y-value). The way Linear Regression works is by trying to find the weights (namely, W0 and W1) that lead to the best-fitting line for the input data (i.e. X features) we have. The best-fitting line is determined in terms of lowest cost. Here’s the thing. Cost could take different forms, depending on the Machine Learning application at hand. However, in general, cost refers to the loss or error that the model yields in terms of how off it is from the actual Training data. When it comes to Linear Regression, the cost function we usually use is the Squared Error Cost. J(W0,W1) = (1/2n).sigma((h(Xi)-Ti)^2) for all i=1 until i=n Where J(W0,W1) refers to the total cost of the model with weights W0, W1. h(Xi) refers to the model’s prediction of the y-value at feature X with index i. Ti is the actual y-value at index i. And finally, n is the total number of data points in the data set. All what our cost function is doing is basically getting the distance (e.g. Euclidean distance) between what y-value the model predicted and what the actual y-value resident in the data set is for every data point, then squaring this distance and dividing it by the number of data points we have to get the average cost. Said distances are illustrated in the above figure as error vectors. The 2 in the term (1/2n) is merely to ease the process of differentiating the cost function in the next section. Training a Machine Learning model is all about using a Learning Algorithm to find the weights (W0, W1 in our formula) that minimize the cost. For simplicity, let’s use the Gradient Descent algorithm for this. Although it is a fairly simple topic, Gradient Descent deserves its own post. Therefore, we will only go through it briefly. In the context of Linear Regression, training is basically finding those weights and plugging them into the straight line function so that we have best-fit line (with W0, W1 minimizing the cost). The algorithm basically follows the pseudo-code: Repeat until convergence { temp0 := W0 - a.((d/dW0) J(W0,W1)) temp1 := W1 - a.((d/dW1) J(W0,W1)) W0 = temp0 W1 = temp1} Where (d/dW0) and (d/dW1) are the partial derivatives of J(W0,W1) with respect to W0 and W1, respectively. The gist of this partial differentiation is basically the derivatives: (d/dW0) J(W0,W1) = W0 + W1.X - T(d/dW1) j(W0,W1) = (W0 + W1.X - T).X If we run the Gradient Descent learning algorithm on the model, and through the costs obtained at every step, the model will converge to a minimum cost. The weights that led to that minimum cost are dealt with as the final values for the line function we mentioned earlier (i.e. h(X) = W0 + W1.X). This means that the line equivalent to our h(X) function is actually our Linear Regressor. Sometimes, when the Training data set includes a huge amount of data points whose values are inconsistent, we resort to a process called Discretization. This refers to converting the Y values in the data set from continuous to discrete, resulting in succinct, clean and usable ranges of data rather than the data values themselves. However, this leads to data loss, as you would technically be breaking up data points into bins that symbolize ranges of continuous values. Another major factor in the effectiveness of the model afterwards would be its dependence on the number of bins/ranges we choose. In case of bad Linear Regression model performance, we usually go for a higher polynomial function. This is basically the introduction of new variables into the Regressor function so that we allow more flexibility to it. However, this will cause the LR line not to be a straight line anymore. It turns out that, in terms of Linear Regression, “linear” does not refer to “straight line”, but rather to “falling on one line”. This means that our Linear Regressor does not actually have to be a straight line, as we are usually used to see in mathematics. This flexibility in regression could improve the performance drastically. However, higher polynomials could lead to higher variance, and exponentially higher computational complexity. More often than not, this leads to over-fitting. This is a big topic that I will talk about extensively in a separate post. Linear Regression is the process of finding a line that best fits the data points available on the plot, so that we can use it to predict output values for inputs that are not present in the data set we have, with the belief that those outputs would fall on the line. Performance (and error rates) depends on various factors including the how clean and consistent the data is. There are different ways of improving the performance (i.e. generalizability) of the model. However, each one has its own pros and cons, which makes the choice of methods application-dependent.
[ { "code": null, "e": 499, "s": 172, "text": "Linear Regression is arguably one of the most famous topics in both statistics and Machine Learning. It is so essential to the point where it withholds a significant part in almost any Machine Learning course out there. However, it could be a bit tricky to wrap the head around, especially if one has no statistics background." }, { "code": null, "e": 658, "s": 499, "text": "Linear Regression can be considered a Machine Learning algorithm that allows us to map numeric inputs to numeric outputs, fitting a line into the data points." }, { "code": null, "e": 926, "s": 658, "text": "In other words, Linear Regression is a way of modelling the relationship between one or more variables. From the Machine Learning perspective, this is done to ensure generalization — giving the model the ability to predict outputs for inputs it has never seen before." }, { "code": null, "e": 1634, "s": 926, "text": "If you read any of my other posts here on Medium, you will notice that I try to emphasize on the idea of generalization as much as possible. Generalization is the essence of Machine Learning. The whole idea of having this artificial form of intelligence relies on the process of teaching a model so well to the point where it can “act” on its own. In other words, you want the model to not be limited to whatever it has learned. Think of it as a child. If your child has only seen cats his whole life — for some disturbing reason that you imposed on him — and if at some point you decide to show him a picture of a dog, you’d expect him to know that the dog is not a cat. It is not something he has learned." }, { "code": null, "e": 2132, "s": 1634, "text": "So a group of creative Tech enthusiasts started a company in Silicon Valley. This start-up — called Banana — is so innovative that they have been growing constantly since 2016. You, the wealthy investor, would like to know whether to put your money on Banana’s success in the next year or not. Let’s assume that you don’t want to risk a lot of money, especially since the stakes are high in Silicon Valley. So you decide to buy a few shares, instead of investing into a big portion of the company." }, { "code": null, "e": 2246, "s": 2132, "text": "You take a look at the Banana’s stock prices ever since they were kick-started, and you see the following figure." }, { "code": null, "e": 2804, "s": 2246, "text": "Well, you can definitely see the trend. Banana is growing like crazy, kicking up their stock price from 100 dollars to 500 in just three years. You only care about how the price is going to be like in the year 2021, because you want to give your investment some time to blossom along with the company. Optimistically speaking, it looks like you will be growing your money in the upcoming years. The trend is likely not to go through a sudden, drastic change. This leads to you hypothesizing that the stock price will fall somewhere above the $500 indicator." }, { "code": null, "e": 3122, "s": 2804, "text": "Here’s an interesting thought. Based on the stock price records of the last couple of years you were able to predict what the stock price is going to be like. You were able to infer the range of the new stock price (that doesn’t exist on the plot) for a year that we don’t have data for (the year 2021). Well — kinda." }, { "code": null, "e": 3452, "s": 3122, "text": "What you just did is infer your model (that head of yours) to generalize — predict the y-value for an x-value that is not even in your knowledge. However, this is not accurate in any way. You couldn’t specify what exactly is the stock price most likely going to be. For all you know, it is probably going to be above 500 dollars." }, { "code": null, "e": 3689, "s": 3452, "text": "Here is where Linear Regression (LR) comes into play. The essence of LR is to find the line that best fits the data points on the plot, so that we can, more or less, know exactly where the stock price is likely to fall in the year 2021." }, { "code": null, "e": 3945, "s": 3689, "text": "Let’s examine the LR-generated line (in red) above, by looking at the importance of it. It looks like, with just a little modification, we were able to realize that Banana’s stock price is likely to be worth a little bit higher than $600 by the year 2021." }, { "code": null, "e": 4210, "s": 3945, "text": "Obviously, this is an oversimplified example. However, the process stays the same. Linear Regression as an algorithm relies on the concept of lowering the cost to maximize the performance. We will examine this concept, and how we got the red line on the plot next." }, { "code": null, "e": 4636, "s": 4210, "text": "To get the technicalities out of the way. What I described in the previous section is referred to as Univariate Linear Regression, because we are trying to map one independent variable (x-value) to one dependent variable (y-value). This is in contrast to Multivariate Linear Regression, where we try to map multiple independent variables (i.e. features) to a dependent variable (i.e. labels). Now, let’s get down to business." }, { "code": null, "e": 4685, "s": 4636, "text": "Any straight line on a plot follows the formula:" }, { "code": null, "e": 4700, "s": 4685, "text": "f(X) = M.X + B" }, { "code": null, "e": 4841, "s": 4700, "text": "Where M is the slope of the line, B is the y-intercept that allows vertical movement of the line, and X which is the function’s input value." }, { "code": null, "e": 4900, "s": 4841, "text": "In terms of Machine Learning, this follows the convention:" }, { "code": null, "e": 4917, "s": 4900, "text": "h(X) = W0 + W1.X" }, { "code": null, "e": 5008, "s": 4917, "text": "Where W0 and W1 are weights, X is the input feature, and h(X) is the label (i.e. y-value)." }, { "code": null, "e": 5235, "s": 5008, "text": "The way Linear Regression works is by trying to find the weights (namely, W0 and W1) that lead to the best-fitting line for the input data (i.e. X features) we have. The best-fitting line is determined in terms of lowest cost." }, { "code": null, "e": 5474, "s": 5235, "text": "Here’s the thing. Cost could take different forms, depending on the Machine Learning application at hand. However, in general, cost refers to the loss or error that the model yields in terms of how off it is from the actual Training data." }, { "code": null, "e": 5570, "s": 5474, "text": "When it comes to Linear Regression, the cost function we usually use is the Squared Error Cost." }, { "code": null, "e": 5630, "s": 5570, "text": "J(W0,W1) = (1/2n).sigma((h(Xi)-Ti)^2) for all i=1 until i=n" }, { "code": null, "e": 5889, "s": 5630, "text": "Where J(W0,W1) refers to the total cost of the model with weights W0, W1. h(Xi) refers to the model’s prediction of the y-value at feature X with index i. Ti is the actual y-value at index i. And finally, n is the total number of data points in the data set." }, { "code": null, "e": 6392, "s": 5889, "text": "All what our cost function is doing is basically getting the distance (e.g. Euclidean distance) between what y-value the model predicted and what the actual y-value resident in the data set is for every data point, then squaring this distance and dividing it by the number of data points we have to get the average cost. Said distances are illustrated in the above figure as error vectors. The 2 in the term (1/2n) is merely to ease the process of differentiating the cost function in the next section." }, { "code": null, "e": 6726, "s": 6392, "text": "Training a Machine Learning model is all about using a Learning Algorithm to find the weights (W0, W1 in our formula) that minimize the cost. For simplicity, let’s use the Gradient Descent algorithm for this. Although it is a fairly simple topic, Gradient Descent deserves its own post. Therefore, we will only go through it briefly." }, { "code": null, "e": 6971, "s": 6726, "text": "In the context of Linear Regression, training is basically finding those weights and plugging them into the straight line function so that we have best-fit line (with W0, W1 minimizing the cost). The algorithm basically follows the pseudo-code:" }, { "code": null, "e": 7103, "s": 6971, "text": "Repeat until convergence { temp0 := W0 - a.((d/dW0) J(W0,W1)) temp1 := W1 - a.((d/dW1) J(W0,W1)) W0 = temp0 W1 = temp1}" }, { "code": null, "e": 7281, "s": 7103, "text": "Where (d/dW0) and (d/dW1) are the partial derivatives of J(W0,W1) with respect to W0 and W1, respectively. The gist of this partial differentiation is basically the derivatives:" }, { "code": null, "e": 7350, "s": 7281, "text": "(d/dW0) J(W0,W1) = W0 + W1.X - T(d/dW1) j(W0,W1) = (W0 + W1.X - T).X" }, { "code": null, "e": 7739, "s": 7350, "text": "If we run the Gradient Descent learning algorithm on the model, and through the costs obtained at every step, the model will converge to a minimum cost. The weights that led to that minimum cost are dealt with as the final values for the line function we mentioned earlier (i.e. h(X) = W0 + W1.X). This means that the line equivalent to our h(X) function is actually our Linear Regressor." }, { "code": null, "e": 8341, "s": 7739, "text": "Sometimes, when the Training data set includes a huge amount of data points whose values are inconsistent, we resort to a process called Discretization. This refers to converting the Y values in the data set from continuous to discrete, resulting in succinct, clean and usable ranges of data rather than the data values themselves. However, this leads to data loss, as you would technically be breaking up data points into bins that symbolize ranges of continuous values. Another major factor in the effectiveness of the model afterwards would be its dependence on the number of bins/ranges we choose." }, { "code": null, "e": 8634, "s": 8341, "text": "In case of bad Linear Regression model performance, we usually go for a higher polynomial function. This is basically the introduction of new variables into the Regressor function so that we allow more flexibility to it. However, this will cause the LR line not to be a straight line anymore." }, { "code": null, "e": 8765, "s": 8634, "text": "It turns out that, in terms of Linear Regression, “linear” does not refer to “straight line”, but rather to “falling on one line”." }, { "code": null, "e": 9202, "s": 8765, "text": "This means that our Linear Regressor does not actually have to be a straight line, as we are usually used to see in mathematics. This flexibility in regression could improve the performance drastically. However, higher polynomials could lead to higher variance, and exponentially higher computational complexity. More often than not, this leads to over-fitting. This is a big topic that I will talk about extensively in a separate post." } ]
How to put author/title name over image in ReactJS? - GeeksforGeeks
06 Sep, 2021 We can place the author or title name over the image using the GridListTileBar Component in ReactJS. This component adds an overlay over the child component. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridListTileBar component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile';import GridListTileBar from '@material-ui/core/GridListTileBar';import ListSubheader from '@material-ui/core/ListSubheader';import IconButton from '@material-ui/core/IconButton';import InfoIcon from '@material-ui/icons/Info'; const App = () => { return ( <div style={{ width: 700, margin: 'auto' }}> <h3>How to put title over image in ReactJS?</h3> <GridList cellHeight={180} > <GridListTile key="Subheader" cols={2} rows={4} style={{ height: 'auto' }}> <ListSubheader component="div">December</ListSubheader> </GridListTile> <GridListTile> <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"/> <GridListTileBar title='Computer Science Portal' subtitle={<span>by: GeeksforGeeks</span>} actionIcon={ <IconButton aria-label={`Best Place to learn`}> <InfoIcon /> </IconButton> } /> </GridListTile> </GridList> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: sagar0719kumar JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 24921, "s": 24893, "text": "\n06 Sep, 2021" }, { "code": null, "e": 25253, "s": 24921, "text": "We can place the author or title name over the image using the GridListTileBar Component in ReactJS. This component adds an overlay over the child component. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridListTileBar component in ReactJS using the following approach." }, { "code": null, "e": 25303, "s": 25253, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25367, "s": 25303, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25399, "s": 25367, "text": "npx create-react-app foldername" }, { "code": null, "e": 25499, "s": 25399, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25513, "s": 25499, "text": "cd foldername" }, { "code": null, "e": 25622, "s": 25513, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25683, "s": 25622, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 25735, "s": 25683, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25753, "s": 25735, "text": "Project Structure" }, { "code": null, "e": 25891, "s": 25753, "text": "Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25902, "s": 25891, "text": "Javascript" }, { "code": "import React from 'react';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile';import GridListTileBar from '@material-ui/core/GridListTileBar';import ListSubheader from '@material-ui/core/ListSubheader';import IconButton from '@material-ui/core/IconButton';import InfoIcon from '@material-ui/icons/Info'; const App = () => { return ( <div style={{ width: 700, margin: 'auto' }}> <h3>How to put title over image in ReactJS?</h3> <GridList cellHeight={180} > <GridListTile key=\"Subheader\" cols={2} rows={4} style={{ height: 'auto' }}> <ListSubheader component=\"div\">December</ListSubheader> </GridListTile> <GridListTile> <img src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\"/> <GridListTileBar title='Computer Science Portal' subtitle={<span>by: GeeksforGeeks</span>} actionIcon={ <IconButton aria-label={`Best Place to learn`}> <InfoIcon /> </IconButton> } /> </GridListTile> </GridList> </div> );} export default App;", "e": 27082, "s": 25902, "text": null }, { "code": null, "e": 27198, "s": 27085, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27210, "s": 27200, "text": "npm start" }, { "code": null, "e": 27309, "s": 27210, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27328, "s": 27313, "text": "sagar0719kumar" }, { "code": null, "e": 27339, "s": 27328, "text": "JavaScript" }, { "code": null, "e": 27347, "s": 27339, "text": "ReactJS" }, { "code": null, "e": 27364, "s": 27347, "text": "Web Technologies" }, { "code": null, "e": 27462, "s": 27364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27471, "s": 27462, "text": "Comments" }, { "code": null, "e": 27484, "s": 27471, "text": "Old Comments" }, { "code": null, "e": 27545, "s": 27484, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27586, "s": 27545, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27626, "s": 27586, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27680, "s": 27626, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27742, "s": 27680, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27785, "s": 27742, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27830, "s": 27785, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27895, "s": 27830, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27963, "s": 27895, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Largest Even Number | Practice | GeeksforGeeks
Given an integer S. Find the largest even number that can be formed by rearranging the digits of S. Note: In case the number does not contain any even digit then output the largest odd number possible. Example 1: Input: S = "1324" Output: "4312" Explanation: Largest even number: 4312 Example 2: Input: S = "3555" Output: "5553" Explanation: No even number possible, So we'll find largest odd number. Your Task: You don't need to read input or print anything. Your task is to complete the function LargestEven() which takes the string S as inputs representing the integer and returns the answer. Expected Time Complexity: O(|S| * log |S|) Expected Auxiliary Space: O(1) Constraints: 1 ≤ |S| ≤ 105 S contains only digits from '0' to '9'. 0 cedera987et2 days ago Python Solution: class Solution: def LargestEven(self, S): a = list(S) e = [] o = [] for i in range(len(a)): if int(a[i])%2==0: e.append(int(a[i])) else: o.append(int(a[i])) if len(e)==0: return "".join(sorted(a, reverse=True)) e.sort() t = e[0] e.pop(0) c = e+o c.sort(reverse=True) c.append(t) for i in range(len(c)): c[i] = str(c[i]) return "".join(c) +1 omkarsubhasishkhuntia5 months ago vector<int>v; for(int i=0;i<S.size();i++){ v.push_back(int(S[i])); } sort(v.begin(),v.end()); reverse(v.begin(),v.end()); for(int i=S.size()-1;i>=0;i--){ if(v[i]%2==0){ while(i!=S.size()-1){ swap(v[i],v[i+1]); i++; } break; } } string res=""; for(int i=0;i<S.size();i++){ res+=char(v[i]); } return res; 0 pikucode156 months ago class Solution{ public: string LargestEven(string S){ sort(S.begin(),S.end(),greater<char>()); int evMinIndx=-1; for(int i=S.size()-1;i>=0;i--) { if((S[i]-'0')%2==0) { evMinIndx=i; break; } } if(evMinIndx==-1) return S; char temp=S[evMinIndx]; for(int i=evMinIndx;i<S.size()-1;i++) S[i]=S[i+1]; S[S.size()-1]=temp; return S; } }; -1 sknwd88647 months ago string LargestEven(string str){ sort(str.begin(),str.end(),greater<int>()); int len=str.length(); for(int i=len-1;i>=0;i--) { if((int)str[i]%2==0) { swap(str[i],str[len-1]); break; } } sort(str.begin(),str.begin()+len-1,greater<int>()); return str; } 0 Faisal Alam9 months ago Faisal Alam O(nlogn) O(1)class Solution{ public: string LargestEven(string str){ char num; int index=-1; sort(str.begin(), str.end(), greater<int>()); for(int i=str.size()-1; i>=0; i--){ if(str[i]%2==0){ //ascii values of even char number is also even so it works without conversion index=i; num=str[index]; break; } } if(index!=-1){ for(int i=index+1; i<str.size(); i++){="" str[i-1]="str[i];" }="" str[str.size()-1]="num;" }="" return="" str;="" }="" };="" <="" code=""> 0 Jashwant Kumar9 months ago Jashwant Kumar int res[10]; bool even=false; for(int i=0;i<10;i++) { res[i]=0; } int n=S.length(); for(int i=0;i<n;i++) {="" char="" s1="S[i];" res[s1-'0']++;="" }="" for(int="" i="0;i&lt;9;i=i+2)" {="" if(res[i]="">0) { res[i]--; S[n-1]='0'+i; even=true; break; } } if(even==false) { sort(S.begin(),S.end(),greater<>()); return S; } int k=0; for(int i=9;i>=0;i--) { for(int j=0;j<res[i];j++) {="" s[k]="0" +i;="" k++;="" }="" }="" return="" s;=""> 0 AKS9 months ago AKS def LargestEven(self, S): # code herel = list(map(int, list(S))) d = [] for i in l: if i % 2 == 0: d.append(i) if len(d): l.remove(min(d)) l = sorted(l, reverse = True) l.append(min(d)) return ''.join(list(map(str, l))) else: l = sorted(l, reverse = True) return ''.join(list(map(str, l))) 0 Mansi Garg9 months ago Mansi Garg C++ SolutionExecution Time: 0.5void swap(char &a, char &b){ char t = a; a = b; b = t; } string LargestEven(string S){ //complete the function here sort(S.begin(), S.end(), greater<int>()); bool even = false; for(int i=0; i<s.size(); i++){="" if((s[i]-'0')%2="=0){" even="true;" break;="" }="" }="" if(even="=true" &&="" (s[s.size()-1]-'0')%2!="0){" for(int="" i="S.size()-2;" i="">=0; i--){ if((S[i]-'0')%2==0){ swap(S[i], S[S.size()-1]); sort(S.begin(), S.begin()+S.size()-1, greater<int>()); break; } } } return S; } 0 Ashish Dhakad10 months ago Ashish Dhakad SIMPLE C++ SOLUTION class Solution{ public: string LargestEven(string S){ sort(S.begin(),S.end(),greater<>()); int n=S.length(); int l=n-1; for(int i=n-1;i>=0;i--) { if(S[i]%2==0){ l=i; break; } } int temp=S[l]; S[l]=S[n-1]; sort(S.begin(),S.end(),greater<>()); S[n-1]=temp; return S; 0 Anwesan De10 months ago Anwesan De Python solution https://p.ip.fi/UOKV 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": 338, "s": 238, "text": "Given an integer S. Find the largest even number that can be formed by rearranging the digits of S." }, { "code": null, "e": 440, "s": 338, "text": "Note: In case the number does not contain any even digit then output the largest odd number possible." }, { "code": null, "e": 451, "s": 440, "text": "Example 1:" }, { "code": null, "e": 524, "s": 451, "text": "Input:\nS = \"1324\"\nOutput: \"4312\"\nExplanation: Largest even number: 4312\n" }, { "code": null, "e": 535, "s": 524, "text": "Example 2:" }, { "code": null, "e": 641, "s": 535, "text": "Input:\nS = \"3555\"\nOutput: \"5553\"\nExplanation: No even number possible,\nSo we'll find largest odd number.\n" }, { "code": null, "e": 981, "s": 641, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function LargestEven() which takes the string S as inputs representing the integer and returns the answer.\n\nExpected Time Complexity: O(|S| * log |S|)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ |S| ≤ 105\nS contains only digits from '0' to '9'." }, { "code": null, "e": 983, "s": 981, "text": "0" }, { "code": null, "e": 1005, "s": 983, "text": "cedera987et2 days ago" }, { "code": null, "e": 1022, "s": 1005, "text": "Python Solution:" }, { "code": null, "e": 1560, "s": 1030, "text": "class Solution: def LargestEven(self, S): a = list(S) e = [] o = [] for i in range(len(a)): if int(a[i])%2==0: e.append(int(a[i])) else: o.append(int(a[i])) if len(e)==0: return \"\".join(sorted(a, reverse=True)) e.sort() t = e[0] e.pop(0) c = e+o c.sort(reverse=True) c.append(t) for i in range(len(c)): c[i] = str(c[i]) return \"\".join(c) " }, { "code": null, "e": 1563, "s": 1560, "text": "+1" }, { "code": null, "e": 1597, "s": 1563, "text": "omkarsubhasishkhuntia5 months ago" }, { "code": null, "e": 2081, "s": 1597, "text": " vector<int>v; for(int i=0;i<S.size();i++){ v.push_back(int(S[i])); } sort(v.begin(),v.end()); reverse(v.begin(),v.end()); for(int i=S.size()-1;i>=0;i--){ if(v[i]%2==0){ while(i!=S.size()-1){ swap(v[i],v[i+1]); i++; } break; } } string res=\"\"; for(int i=0;i<S.size();i++){ res+=char(v[i]); } return res;" }, { "code": null, "e": 2083, "s": 2081, "text": "0" }, { "code": null, "e": 2106, "s": 2083, "text": "pikucode156 months ago" }, { "code": null, "e": 2581, "s": 2106, "text": "class Solution{ public: string LargestEven(string S){ sort(S.begin(),S.end(),greater<char>()); int evMinIndx=-1; for(int i=S.size()-1;i>=0;i--) { if((S[i]-'0')%2==0) { evMinIndx=i; break; } } if(evMinIndx==-1) return S; char temp=S[evMinIndx]; for(int i=evMinIndx;i<S.size()-1;i++) S[i]=S[i+1]; S[S.size()-1]=temp; return S; } };" }, { "code": null, "e": 2584, "s": 2581, "text": "-1" }, { "code": null, "e": 2606, "s": 2584, "text": "sknwd88647 months ago" }, { "code": null, "e": 2999, "s": 2606, "text": "string LargestEven(string str){\n sort(str.begin(),str.end(),greater<int>());\n int len=str.length();\n for(int i=len-1;i>=0;i--)\n {\n if((int)str[i]%2==0)\n {\n swap(str[i],str[len-1]);\n break;\n }\n }\n sort(str.begin(),str.begin()+len-1,greater<int>());\n return str;\n } " }, { "code": null, "e": 3001, "s": 2999, "text": "0" }, { "code": null, "e": 3025, "s": 3001, "text": "Faisal Alam9 months ago" }, { "code": null, "e": 3037, "s": 3025, "text": "Faisal Alam" }, { "code": null, "e": 3627, "s": 3037, "text": "O(nlogn) O(1)class Solution{ public: string LargestEven(string str){ char num; int index=-1; sort(str.begin(), str.end(), greater<int>()); for(int i=str.size()-1; i>=0; i--){ if(str[i]%2==0){ //ascii values of even char number is also even so it works without conversion index=i; num=str[index]; break; } } if(index!=-1){ for(int i=index+1; i<str.size(); i++){=\"\" str[i-1]=\"str[i];\" }=\"\" str[str.size()-1]=\"num;\" }=\"\" return=\"\" str;=\"\" }=\"\" };=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 3629, "s": 3627, "text": "0" }, { "code": null, "e": 3656, "s": 3629, "text": "Jashwant Kumar9 months ago" }, { "code": null, "e": 3671, "s": 3656, "text": "Jashwant Kumar" }, { "code": null, "e": 4322, "s": 3671, "text": "int res[10]; bool even=false; for(int i=0;i<10;i++) { res[i]=0; } int n=S.length(); for(int i=0;i<n;i++) {=\"\" char=\"\" s1=\"S[i];\" res[s1-'0']++;=\"\" }=\"\" for(int=\"\" i=\"0;i&lt;9;i=i+2)\" {=\"\" if(res[i]=\"\">0) { res[i]--; S[n-1]='0'+i; even=true; break; } } if(even==false) { sort(S.begin(),S.end(),greater<>()); return S; } int k=0; for(int i=9;i>=0;i--) { for(int j=0;j<res[i];j++) {=\"\" s[k]=\"0\" +i;=\"\" k++;=\"\" }=\"\" }=\"\" return=\"\" s;=\"\">" }, { "code": null, "e": 4324, "s": 4322, "text": "0" }, { "code": null, "e": 4340, "s": 4324, "text": "AKS9 months ago" }, { "code": null, "e": 4344, "s": 4340, "text": "AKS" }, { "code": null, "e": 4502, "s": 4344, "text": "def LargestEven(self, S): # code herel = list(map(int, list(S))) d = [] for i in l: if i % 2 == 0: d.append(i)" }, { "code": null, "e": 4762, "s": 4502, "text": " if len(d): l.remove(min(d)) l = sorted(l, reverse = True) l.append(min(d)) return ''.join(list(map(str, l))) else: l = sorted(l, reverse = True) return ''.join(list(map(str, l)))" }, { "code": null, "e": 4764, "s": 4762, "text": "0" }, { "code": null, "e": 4787, "s": 4764, "text": "Mansi Garg9 months ago" }, { "code": null, "e": 4798, "s": 4787, "text": "Mansi Garg" }, { "code": null, "e": 5458, "s": 4798, "text": "C++ SolutionExecution Time: 0.5void swap(char &a, char &b){ char t = a; a = b; b = t; } string LargestEven(string S){ //complete the function here sort(S.begin(), S.end(), greater<int>()); bool even = false; for(int i=0; i<s.size(); i++){=\"\" if((s[i]-'0')%2=\"=0){\" even=\"true;\" break;=\"\" }=\"\" }=\"\" if(even=\"=true\" &&=\"\" (s[s.size()-1]-'0')%2!=\"0){\" for(int=\"\" i=\"S.size()-2;\" i=\"\">=0; i--){ if((S[i]-'0')%2==0){ swap(S[i], S[S.size()-1]); sort(S.begin(), S.begin()+S.size()-1, greater<int>()); break; } } } return S; } " }, { "code": null, "e": 5460, "s": 5458, "text": "0" }, { "code": null, "e": 5487, "s": 5460, "text": "Ashish Dhakad10 months ago" }, { "code": null, "e": 5501, "s": 5487, "text": "Ashish Dhakad" }, { "code": null, "e": 5521, "s": 5501, "text": "SIMPLE C++ SOLUTION" }, { "code": null, "e": 5918, "s": 5521, "text": "class Solution{ public: string LargestEven(string S){ sort(S.begin(),S.end(),greater<>()); int n=S.length(); int l=n-1; for(int i=n-1;i>=0;i--) { if(S[i]%2==0){ l=i; break; } } int temp=S[l]; S[l]=S[n-1]; sort(S.begin(),S.end(),greater<>()); S[n-1]=temp;" }, { "code": null, "e": 5936, "s": 5918, "text": " return S;" }, { "code": null, "e": 5938, "s": 5936, "text": "0" }, { "code": null, "e": 5962, "s": 5938, "text": "Anwesan De10 months ago" }, { "code": null, "e": 5973, "s": 5962, "text": "Anwesan De" }, { "code": null, "e": 5989, "s": 5973, "text": "Python solution" }, { "code": null, "e": 6010, "s": 5989, "text": "https://p.ip.fi/UOKV" }, { "code": null, "e": 6156, "s": 6010, "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": 6192, "s": 6156, "text": " Login to access your submissions. " }, { "code": null, "e": 6202, "s": 6192, "text": "\nProblem\n" }, { "code": null, "e": 6212, "s": 6202, "text": "\nContest\n" }, { "code": null, "e": 6275, "s": 6212, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6423, "s": 6275, "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": 6631, "s": 6423, "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": 6737, "s": 6631, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
GIS data processing cheat sheet: Effectively using command line GDAL | by Kanishka Narayan | Towards Data Science
Geographical Information systems (GIS) are highly informative and provide a granular representation of data. Needless to say, these datasets are very attractive to researchers, data analysts and data scientists. But these data come with a big catch. They are heavy and a pain to manipulate from a processing and computational time perspective. Given their size and structure, it is also difficult to analyze these datasets meaningfully unless you are using software like ArcGis or QGIS. In this article, I provide some simple command line code that can be used to greatly minimize the processing time and can be effectively used to extract meaningful information from these data. The code makes use of the GDAL program that is available here. So, let’s jump right in. To those unfamiliar with GIS data types- I’d like to provide a simple summary of the different types of GIS data that one may encounter. There are two broad categories to consider. The first is raster data which are grid/cell based data that contain some information about what a cell contains (discrete data like the population contained within the cell) or what it represents (continuous data like what category a particular cell belongs to). An example of a raster format would be a .tif, .bsq or .bil file. The second is vector data which are data represented as shapes like maps of countries, states etc. An example of a vector format is a .shp or shapefile. Now that, we know the data we will be working with, let’s jump into the code. To use this code, you will need GDAL installed on your machine. If you are on a windows machine, I would recommend installing GDAL through a cygwin terminal. 1. Getting information/metadata- I have used an example raster for this article here, called gpw_v4_population_count_rev11_2000_30_sec.tif. This is a file downloaded from a database maintained by NASA that can be accessed here.It is a simple raster that contains population by grid cell for every country in the world. To see what this raster actually contains let’s use the below gdalinfo function. #First go the directory containing the filecd 'file path here'#Now let's run gdalinfogdalinfo gpw_v4_population_count_rev11_2000_30_sec.tif#This is the output we getDriver: GTiff/GeoTIFFFiles: gpw_v4_population_count_rev11_2015_30_sec.tifSize is 43200, 21600Origin = (-180.000000000000000,89.999999999999915)Pixel Size = (0.008333333333333,-0.008333333333333)Metadata:AREA_OR_POINT=AreaDataType=GenericImage Structure Metadata:COMPRESSION=LZWINTERLEAVE=BANDCorner Coordinates:Upper Left (-180.0000000, 90.0000000)Lower Left (-180.0000000, -90.0000000)Upper Right ( 180.0000000, 90.0000000)Lower Right ( 180.0000000, -90.0000000)Center ( -0.0000000, -0.0000000)Band 1 Block=43200x1 Type=Float32, ColorInterp=GrayNoData Value=-3.40282306073709653e+38 So, the information we get tells us the Driver: which is the type of file (which in this case is a tif file), Size: which is the size of the grid (the number of rows and columns which make up the grid which in this case are 43200,21600). The Pixel Size: which is the size of the projection within a pixel (which in this case is 0.00833333 degrees which is 5 arc minutes), the Corner Co-ordinates: which is the extent of the projection (This will tell us if certain regions are missing from the projection. For example, some maps will have some regions cut off etc) and finally we get the NoData value: which is the value with no data accounting, or essentially the nulls within the datasets. All of these data are useful as we will see in the rest of the article. But gdalinfo is really useful in that it provides a quick summary of the available data within a file and consumes no processing power. 2. Filling Nodata values in a raster- For different projects, we may not want NoData values or may want to replace NoData values with a different value from the default. There are 3 steps that we can to follow to accomplish this with gdal. First, we need to replace the NoData value with our own default (let’s say 0), replace all NoData values with zeroes (This is a sanity check to ensure that we are catching Nodata values that are not specified by the metadata) and then we need to take off the NoData tag, since NoData is essentially a qualitative tag. We can use two commands here, first the gdalwarp to replace values and a gdal_translate to remove the tag. Note that both these commands like most other gdal commands will ask you to specify a separate output object. #Fill NoData values with zerogdalwarp -srcnodata -3.40282306073709653e+38 dstnodata 0 gpw_v4_population_count_rev11_2015_30_sec.tif population_nodatafilled.tif# Now replace all no_data values with a 0.gdal_translate -b 1 -a_nodata 0 population_nodatafilled.tif population_only_data.tif#Note that the -b indicates the band within the raster where you want to the operation. This would change for multiband rasters.# Now take off the no_data tag itselfgdal_translate -a_nodata none population_only_data.tif population_clean.tif 3. Re-projecting rasters- When comparing two raster files, we need to make sure we are comparing apples to apples since there may be differences in the grid size, projection type or projection sizes or even the extents. The gdalwarp allows us to do convenient reprojections to standardize raster files. So, continuing on with our current example, if we wanted to reproject our data onto a smaller grid size with a different projection type, we would use the following gdalwarp command. The comment in the code also provides a description of the parameters we are feeding this command. #Let's reproject gdalwarp -ts 1440 600 -r average -ot Float32 -t_srs "+proj=longlat +ellps=WGS84" -te -180 -60 180 90 population_clean.tif population_reprojected.tif#Note the following:# -ts is the size of the grid that we want in rows and columns# -r is specifying the method used to aggregate/dis-aggregate. There #are a number of options available, but the one that makes the most #sense is average since this is basically the sum of the cell values #being aggregated divided by the number of cells.# -ot is the output type which is set to a Float since this us a #mathematical operation.# -t_srs is the reprojection type. The one I am specifying here is a #longlat projection using a WGS84 datum.# -te is the extent itself, which is the extent of the projection. #If you standardize the grid size and the reprojection type, you will automatically standradize the pixel size. Now, you may have noticed that you can’t even open the original tif. After the reprojection though, we can actually plot out the raster since the size is much smaller. 4. Convert raster data types- Often users will want to convert data types. A common reason to do this would be space. For example, geotiffs are expensive in terms of memory but .bil or .bsq files are much cheaper. So, we can convert this easily using gdal_translate. The great part about this is that gdal will create header files with automatically where ever necessary. #Convert tif to bilgdal_translate -of ENVI population_reprojected.tif population_final.bil#The -of specifies the file type we want to convert to. 5. Replacing specific pixel values based on a criteria- Now, users may also want to replace specific values within a raster with their own values. Let’s say we wanted in the raster in question, grid cells with any value of population to have a value of 1 while those without should have a value of 0. We can achieve this using gdal_calc.py. We would just use the below code to complete this. Note that this is a python command. #Replace pixel values based on criteriagdal_calc.py -A population_final.bil --calc='((A>0))*1+((A<=0)*A)' --outfile=population_final_reclass.bil#This will basically replace all values within pixels with 1 and those without values to 0. 6. Raster to vector conversion (polygonization)- Let’ say we wanted a global map of regions according to population. That is, a map that showed us where people were actually living in the world. We already have a raster which tracks exactly this for each pixel.If we could combine the pixels to get a meaningful map, that would be very helpful. This is easy to achieve in gdal using gdal_polygonize.py. This would take a raster, convert pixels to polygons and merge neighbouring pixels with the same values (in this case 1) and output a global map. #Convert raster to vector (shape file)gdal_polygonize.py population_final_reclass.bil population_map.shp pop#Note that the pop is the destination column name within the shape file. After this, if we were to plot out the map of the world regions where people live we get the map below. The great part about this is that it will correspond to the dimensions of our raster. 7. Merging vector files- Now, let’s say in the above map, we also wanted a representation in the map above of the different countries in the world. With the ogr2ogr command, you can also merge two vector files. Let’s say we had a shapefile called countries.shp with the actual boundaries of countries. We could merge it with our existing shape file to get a map file that shows you a map of countries along with holes for places within countries where people don’t live. #First create a file to merge againstogr2ogr -f 'ESRI Shapefile' population_boundaries_merged.shp population_map.shp#Now merge the boundaries shapefile into this oneogr2ogr -f -update -append population_boundaries_merged.shp ccountries.shp -nln merge#This command is updating the population_boundaries_merged.shp by appending a new boundaries file from countries.shp. And, this is the output we get out of the new population_boundaries_merged There you have it. These commands are a useful cheatsheet when having to process heavy GIS data and extract meaningful information out of them. They can obviously be modified to be adapted to a number of operations. I am also in the process of developing a repository that will host these commands as a formal set of bash scripts. The repository in its current form is here. As always, any and all feedback related to this is welcome!
[ { "code": null, "e": 939, "s": 171, "text": "Geographical Information systems (GIS) are highly informative and provide a granular representation of data. Needless to say, these datasets are very attractive to researchers, data analysts and data scientists. But these data come with a big catch. They are heavy and a pain to manipulate from a processing and computational time perspective. Given their size and structure, it is also difficult to analyze these datasets meaningfully unless you are using software like ArcGis or QGIS. In this article, I provide some simple command line code that can be used to greatly minimize the processing time and can be effectively used to extract meaningful information from these data. The code makes use of the GDAL program that is available here. So, let’s jump right in." }, { "code": null, "e": 1681, "s": 939, "text": "To those unfamiliar with GIS data types- I’d like to provide a simple summary of the different types of GIS data that one may encounter. There are two broad categories to consider. The first is raster data which are grid/cell based data that contain some information about what a cell contains (discrete data like the population contained within the cell) or what it represents (continuous data like what category a particular cell belongs to). An example of a raster format would be a .tif, .bsq or .bil file. The second is vector data which are data represented as shapes like maps of countries, states etc. An example of a vector format is a .shp or shapefile. Now that, we know the data we will be working with, let’s jump into the code." }, { "code": null, "e": 1839, "s": 1681, "text": "To use this code, you will need GDAL installed on your machine. If you are on a windows machine, I would recommend installing GDAL through a cygwin terminal." }, { "code": null, "e": 2239, "s": 1839, "text": "1. Getting information/metadata- I have used an example raster for this article here, called gpw_v4_population_count_rev11_2000_30_sec.tif. This is a file downloaded from a database maintained by NASA that can be accessed here.It is a simple raster that contains population by grid cell for every country in the world. To see what this raster actually contains let’s use the below gdalinfo function." }, { "code": null, "e": 2999, "s": 2239, "text": "#First go the directory containing the filecd 'file path here'#Now let's run gdalinfogdalinfo gpw_v4_population_count_rev11_2000_30_sec.tif#This is the output we getDriver: GTiff/GeoTIFFFiles: gpw_v4_population_count_rev11_2015_30_sec.tifSize is 43200, 21600Origin = (-180.000000000000000,89.999999999999915)Pixel Size = (0.008333333333333,-0.008333333333333)Metadata:AREA_OR_POINT=AreaDataType=GenericImage Structure Metadata:COMPRESSION=LZWINTERLEAVE=BANDCorner Coordinates:Upper Left (-180.0000000, 90.0000000)Lower Left (-180.0000000, -90.0000000)Upper Right ( 180.0000000, 90.0000000)Lower Right ( 180.0000000, -90.0000000)Center ( -0.0000000, -0.0000000)Band 1 Block=43200x1 Type=Float32, ColorInterp=GrayNoData Value=-3.40282306073709653e+38" }, { "code": null, "e": 3899, "s": 2999, "text": "So, the information we get tells us the Driver: which is the type of file (which in this case is a tif file), Size: which is the size of the grid (the number of rows and columns which make up the grid which in this case are 43200,21600). The Pixel Size: which is the size of the projection within a pixel (which in this case is 0.00833333 degrees which is 5 arc minutes), the Corner Co-ordinates: which is the extent of the projection (This will tell us if certain regions are missing from the projection. For example, some maps will have some regions cut off etc) and finally we get the NoData value: which is the value with no data accounting, or essentially the nulls within the datasets. All of these data are useful as we will see in the rest of the article. But gdalinfo is really useful in that it provides a quick summary of the available data within a file and consumes no processing power." }, { "code": null, "e": 4674, "s": 3899, "text": "2. Filling Nodata values in a raster- For different projects, we may not want NoData values or may want to replace NoData values with a different value from the default. There are 3 steps that we can to follow to accomplish this with gdal. First, we need to replace the NoData value with our own default (let’s say 0), replace all NoData values with zeroes (This is a sanity check to ensure that we are catching Nodata values that are not specified by the metadata) and then we need to take off the NoData tag, since NoData is essentially a qualitative tag. We can use two commands here, first the gdalwarp to replace values and a gdal_translate to remove the tag. Note that both these commands like most other gdal commands will ask you to specify a separate output object." }, { "code": null, "e": 5200, "s": 4674, "text": "#Fill NoData values with zerogdalwarp -srcnodata -3.40282306073709653e+38 dstnodata 0 gpw_v4_population_count_rev11_2015_30_sec.tif population_nodatafilled.tif# Now replace all no_data values with a 0.gdal_translate -b 1 -a_nodata 0 population_nodatafilled.tif population_only_data.tif#Note that the -b indicates the band within the raster where you want to the operation. This would change for multiband rasters.# Now take off the no_data tag itselfgdal_translate -a_nodata none population_only_data.tif population_clean.tif" }, { "code": null, "e": 5785, "s": 5200, "text": "3. Re-projecting rasters- When comparing two raster files, we need to make sure we are comparing apples to apples since there may be differences in the grid size, projection type or projection sizes or even the extents. The gdalwarp allows us to do convenient reprojections to standardize raster files. So, continuing on with our current example, if we wanted to reproject our data onto a smaller grid size with a different projection type, we would use the following gdalwarp command. The comment in the code also provides a description of the parameters we are feeding this command." }, { "code": null, "e": 6667, "s": 5785, "text": "#Let's reproject gdalwarp -ts 1440 600 -r average -ot Float32 -t_srs \"+proj=longlat +ellps=WGS84\" -te -180 -60 180 90 population_clean.tif population_reprojected.tif#Note the following:# -ts is the size of the grid that we want in rows and columns# -r is specifying the method used to aggregate/dis-aggregate. There #are a number of options available, but the one that makes the most #sense is average since this is basically the sum of the cell values #being aggregated divided by the number of cells.# -ot is the output type which is set to a Float since this us a #mathematical operation.# -t_srs is the reprojection type. The one I am specifying here is a #longlat projection using a WGS84 datum.# -te is the extent itself, which is the extent of the projection. #If you standardize the grid size and the reprojection type, you will automatically standradize the pixel size. " }, { "code": null, "e": 6835, "s": 6667, "text": "Now, you may have noticed that you can’t even open the original tif. After the reprojection though, we can actually plot out the raster since the size is much smaller." }, { "code": null, "e": 7207, "s": 6835, "text": "4. Convert raster data types- Often users will want to convert data types. A common reason to do this would be space. For example, geotiffs are expensive in terms of memory but .bil or .bsq files are much cheaper. So, we can convert this easily using gdal_translate. The great part about this is that gdal will create header files with automatically where ever necessary." }, { "code": null, "e": 7353, "s": 7207, "text": "#Convert tif to bilgdal_translate -of ENVI population_reprojected.tif population_final.bil#The -of specifies the file type we want to convert to." }, { "code": null, "e": 7781, "s": 7353, "text": "5. Replacing specific pixel values based on a criteria- Now, users may also want to replace specific values within a raster with their own values. Let’s say we wanted in the raster in question, grid cells with any value of population to have a value of 1 while those without should have a value of 0. We can achieve this using gdal_calc.py. We would just use the below code to complete this. Note that this is a python command." }, { "code": null, "e": 8017, "s": 7781, "text": "#Replace pixel values based on criteriagdal_calc.py -A population_final.bil --calc='((A>0))*1+((A<=0)*A)' --outfile=population_final_reclass.bil#This will basically replace all values within pixels with 1 and those without values to 0." }, { "code": null, "e": 8566, "s": 8017, "text": "6. Raster to vector conversion (polygonization)- Let’ say we wanted a global map of regions according to population. That is, a map that showed us where people were actually living in the world. We already have a raster which tracks exactly this for each pixel.If we could combine the pixels to get a meaningful map, that would be very helpful. This is easy to achieve in gdal using gdal_polygonize.py. This would take a raster, convert pixels to polygons and merge neighbouring pixels with the same values (in this case 1) and output a global map." }, { "code": null, "e": 8748, "s": 8566, "text": "#Convert raster to vector (shape file)gdal_polygonize.py population_final_reclass.bil population_map.shp pop#Note that the pop is the destination column name within the shape file. " }, { "code": null, "e": 8938, "s": 8748, "text": "After this, if we were to plot out the map of the world regions where people live we get the map below. The great part about this is that it will correspond to the dimensions of our raster." }, { "code": null, "e": 9409, "s": 8938, "text": "7. Merging vector files- Now, let’s say in the above map, we also wanted a representation in the map above of the different countries in the world. With the ogr2ogr command, you can also merge two vector files. Let’s say we had a shapefile called countries.shp with the actual boundaries of countries. We could merge it with our existing shape file to get a map file that shows you a map of countries along with holes for places within countries where people don’t live." }, { "code": null, "e": 9778, "s": 9409, "text": "#First create a file to merge againstogr2ogr -f 'ESRI Shapefile' population_boundaries_merged.shp population_map.shp#Now merge the boundaries shapefile into this oneogr2ogr -f -update -append population_boundaries_merged.shp ccountries.shp -nln merge#This command is updating the population_boundaries_merged.shp by appending a new boundaries file from countries.shp. " }, { "code": null, "e": 9853, "s": 9778, "text": "And, this is the output we get out of the new population_boundaries_merged" } ]
How to Find the Best Predictors for ML Algorithms | Towards Data Science
So now, you have your data cleaned and are ready to feed it to machine learning (ML) algorithms. But what if you have a substantial number of input features? Are they all useful and predictive enough for model learning? Will it make your model less interpretive if you use all the features? Having a large number of predictors are also likely to increase the development and model training time, while at the same time utilizing a large amount of system memory. Feature selection techniques aim to systematically select the best subset of input features for model training to predict the target variable. Do not confuse feature selection with other dimensionality reduction techniques (e.g., PCA or use of information theory). Feature selection techniques do not amend the original semantics of the predictors, but simply select a subset of them, thereby resulting in a more interpretable model. According to Sayes et al.1: “The objectives of feature selection are manifold, the most important ones being: to avoid overfitting and improve model performance, i.e., prediction performance in the case of supervised classification and better cluster detection in the case of clustering,to provide faster and more cost-effective models, andto gain a deeper insight into the underlying processes that generated the data.” to avoid overfitting and improve model performance, i.e., prediction performance in the case of supervised classification and better cluster detection in the case of clustering, to provide faster and more cost-effective models, and to gain a deeper insight into the underlying processes that generated the data.” Although feature selection is applicable for both supervised and unsupervised learning, I will focus here on supervised feature selection, where the target variable is known beforehand. We can define three broad categories in the context of supervised feature selection: Embedded methods: Sometimes also called intrinsic methods, these techniques are built-in into the model training phase of a classification or regression model. Examples include penalized regression models (e.g., Lasso) and tree-based models. Since such embedded methods are an integral part of model training, we will not be going over these in this post. Filter methods: These techniques look at the intrinsic properties of features and use statistical techniques to evaluate the relationship between a predictor and the target variable. The subset of best ranked or scored features is then used for model training. We will go over these various statistical techniques in this post. Wrapper methods: These methods utilize ML algorithms as part of the feature evaluation process to identify and select the best subset of features iteratively and according to a specific performance metric. For example, scikit-learn’s Recursive Feature Elimination (RFE) class that we will go over later in this post. Filter feature selection techniques utilize various statistical tests and measures to infer the relationship between input and target variables before selecting the best subset of input features. Note that these statistical measures are univariate, and accordingly, the correlations between various pairs of input features are not accounted for. It might be a good idea to first start with a correlation matrix to weed out redundant correlated features. Alternatively, specific advanced multivariate filter techniques can be utilized, for example, Correlation-based Feature Selection (CFS), Markov Blanket Filter (MBF), and Fast Correlation-based Feature Selection (FCBF). However, there are currently no widely used and supported python packages out there that support these advanced multivariate feature selection techniques. Two conventional statistical feature techniques that can be used for categorical features in a classification problem are: Chi-Squared Test of IndependenceMutual Information Chi-Squared Test of Independence Mutual Information The Chi-Squared test is used to determine the extent of relationship or dependence between two categorical variables — in our case, one categorical input feature, and the other, a categorical target variable. In probability and information theories, the Mutual Information of two random variables measures the level of independence between them. Higher values mean higher dependency. For categorical features encoded as integers (e.g., through OrdinalEncoder), scikit-learn’s SelectKBest class is used in conjunction with either the chi2 or mutual_info_classif functions to identify and select the top k most relevant features. The higher the score returned by SelectKBest, the better that feature’s predictive power will be. The shortlisted features are then fed into the ML algorithm for model development. A complete working example showing both chi2 and mutual_info_classif follows: Note that SelectKBest can also be used as part of a Pipeline for cross-validation purposes. However, depending upon the cardinality of your input features, using OrdinalEncoder in a Pipeline can sometimes not be feasible when the model comes across new value in the test set that was not available in the train set and was therefore not used for encoding. A workaround in such situations could be to run train_test_split multiple times with different test_size and random_state, and take an average of the selected validation metric. For object type categorical features that have not been numerically encoded (maybe because they will be one-hot encoded or converted to dummy variables at a later stage), SciPy’s chi2_contingency class is used to calculate the chi statistic and p values of each pair of categorical features and the target variable. Features with the lowest p values are then shortlisted for modeling. A complete working example follows: Two conventional statistical feature techniques that can be used for numerical features in a classification problem are: ANOVA F-StatisticMutual Information (as explained above) ANOVA F-Statistic Mutual Information (as explained above) The Analysis of Variance (ANOVA) F-statistic calculates the ratio of variances of the means of two or more samples of data. The higher this ratio between a numerical input feature and a categorical target feature, the lower the independence between the two and more likely to be useful for model training. Refer to this excellent article for details on the ANOVA F-statistic. ANOVA F-statistic for feature selection is similarly implemented in Python as a chi-squared test of independence through sci-kit learn’s f_classif function. Given that we are dealing with numerical features this time around, we can easily implement cross-validation through pipelines as demonstrated below: Ah, this is the easiest type of feature selection: identifying the most suitable numeric input feature for a numerical target variable (regression problem). Possible techniques include: Correlation statisticsMutual Information (same as explained earlier, with just a different score_func to be used: mutual_info_regression) Correlation statistics Mutual Information (same as explained earlier, with just a different score_func to be used: mutual_info_regression) Correlation measures the degree of change in one variable as a result of another. Perhaps the best-known correlation measure is Pearson’s correlation that assumes a Gaussian distribution of the data. Correlation coefficients range between -1 (perfect negative correlation) and 1 (perfect positive correlation) with 0 representing no relationship between the variables whatsoever. In addition to plotting the correlation matrix, automatic correlation-based feature selection can be implemented similar to a chi-squared test of independence or ANOVA F-statistic, using sci-kit learn’s f_regression function in conjunction with the SelectKBest class. Further, just like the ANOVA F-statistic function, we can easily implement cross-validation through pipelines as demonstrated below: Recursive Feature Elimination (RFE) from scikit-learn is the most widely used wrapper feature selection method in practice. RFE is feature-type agnostic that iteratively selects the best number of features through a given supervised learning model (estimator). From scikit-learn documentation: “First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached.” As evident from the above, RFE can only be used with an algorithm that has either a coef_ or feature_importances_ attribute to evaluate feature importance. Since RFE is a wrapper feature selection technique, it can use any given estimator (that can be different from the algorithm that is applied to the selected features) to identify the most suitable features. Given that RFE can be used for both categorical and numerical features; its implementation is similar in case of both classification and regression problems. The main parameter of RFE that requires tuning is n_features_to_select. A practical demonstration to identify the best number of features based on RFE using DecisionTreeClassifier for both feature selection and the classification algorithm is as below: The above code snippet will print out the mean and STD of Accuracy scores for each number of features utilized in RFE, something like below: >2: 0.710>3: 0.815>4: 0.872>5: 0.884>6: 0.891>7: 0.888>8: 0.888>9: 0.884 Based purely on the Accuracy score, selecting six features appears to be ideal in this scenario. However, how do we know that DecisionTreeClassifier is the best algorithm to be used within RFE? What if we would like to evaluate various algorithms with RFE? RFECV comes to our help here. The primary purpose of RFECV is to select the best number of features through cross-validation automatically. Since the ideal number of features will be auto-selected by RFECV (therefore, not requiring the for loop in the last code snippet), we can efficiently train and assess multiple models for RFECV feature selection. The model with the best validation metric can then be used moving forward for making predictions. Let us look at a practical example now: The above code snippet will print out the mean and STD of Accuracy scores for each of the model utilized in RFECV, something like below: >LR: 0.891>DT: 0.882>RF: 0.888>XGB: 0.886 The simple logistic regression model wins for wrapper feature selection. We can then use this for making predictions: # create pipelinerfecv = RFECV(estimator = LogisticRegression(), cv = 10, scoring = 'accuracy')model = DecisionTreeClassifier()pipeline = Pipeline(steps=[('features', rfecv), ('model', model)])# fit the model on all available datapipeline.fit(X, y)# make a prediction for one exampledata = #load or define any new data unseen data that you want to make predictions uponyhat = pipeline.predict(data)print('Predicted: %.3f' % (yhat)) The majority of ML algorithms have a built-in attribute to view the relative importance of the features used during model learning. Some examples include: Linear Regression: coef_ gives the list of coefficients. Higher the coefficient, the more of an impact that input feature has on the target variable Logistic Regression: coef_ provides the list of coefficients, to be interpreted the same as that in Linear Regression Decision Trees and Random Forests: feature_importanes_ — higher the better That is it from me this time. Feel free to reach out to me if you would like to discuss anything related to data analytics, traditional machine learning, or credit analysis. Till next time, rock on! Inspired by Dr. Jason Brownlee of Machine Learning Mastery [1] Saeys Y, Inaki I, Larranaga P. A Review of Feature SelectionTechniques in Bioinformatics. Bioinformatics. 2007; 23(19): 2507-2517.
[ { "code": null, "e": 634, "s": 172, "text": "So now, you have your data cleaned and are ready to feed it to machine learning (ML) algorithms. But what if you have a substantial number of input features? Are they all useful and predictive enough for model learning? Will it make your model less interpretive if you use all the features? Having a large number of predictors are also likely to increase the development and model training time, while at the same time utilizing a large amount of system memory." }, { "code": null, "e": 1068, "s": 634, "text": "Feature selection techniques aim to systematically select the best subset of input features for model training to predict the target variable. Do not confuse feature selection with other dimensionality reduction techniques (e.g., PCA or use of information theory). Feature selection techniques do not amend the original semantics of the predictors, but simply select a subset of them, thereby resulting in a more interpretable model." }, { "code": null, "e": 1178, "s": 1068, "text": "According to Sayes et al.1: “The objectives of feature selection are manifold, the most important ones being:" }, { "code": null, "e": 1489, "s": 1178, "text": "to avoid overfitting and improve model performance, i.e., prediction performance in the case of supervised classification and better cluster detection in the case of clustering,to provide faster and more cost-effective models, andto gain a deeper insight into the underlying processes that generated the data.”" }, { "code": null, "e": 1667, "s": 1489, "text": "to avoid overfitting and improve model performance, i.e., prediction performance in the case of supervised classification and better cluster detection in the case of clustering," }, { "code": null, "e": 1721, "s": 1667, "text": "to provide faster and more cost-effective models, and" }, { "code": null, "e": 1802, "s": 1721, "text": "to gain a deeper insight into the underlying processes that generated the data.”" }, { "code": null, "e": 1988, "s": 1802, "text": "Although feature selection is applicable for both supervised and unsupervised learning, I will focus here on supervised feature selection, where the target variable is known beforehand." }, { "code": null, "e": 2073, "s": 1988, "text": "We can define three broad categories in the context of supervised feature selection:" }, { "code": null, "e": 2429, "s": 2073, "text": "Embedded methods: Sometimes also called intrinsic methods, these techniques are built-in into the model training phase of a classification or regression model. Examples include penalized regression models (e.g., Lasso) and tree-based models. Since such embedded methods are an integral part of model training, we will not be going over these in this post." }, { "code": null, "e": 2757, "s": 2429, "text": "Filter methods: These techniques look at the intrinsic properties of features and use statistical techniques to evaluate the relationship between a predictor and the target variable. The subset of best ranked or scored features is then used for model training. We will go over these various statistical techniques in this post." }, { "code": null, "e": 3074, "s": 2757, "text": "Wrapper methods: These methods utilize ML algorithms as part of the feature evaluation process to identify and select the best subset of features iteratively and according to a specific performance metric. For example, scikit-learn’s Recursive Feature Elimination (RFE) class that we will go over later in this post." }, { "code": null, "e": 3270, "s": 3074, "text": "Filter feature selection techniques utilize various statistical tests and measures to infer the relationship between input and target variables before selecting the best subset of input features." }, { "code": null, "e": 3902, "s": 3270, "text": "Note that these statistical measures are univariate, and accordingly, the correlations between various pairs of input features are not accounted for. It might be a good idea to first start with a correlation matrix to weed out redundant correlated features. Alternatively, specific advanced multivariate filter techniques can be utilized, for example, Correlation-based Feature Selection (CFS), Markov Blanket Filter (MBF), and Fast Correlation-based Feature Selection (FCBF). However, there are currently no widely used and supported python packages out there that support these advanced multivariate feature selection techniques." }, { "code": null, "e": 4025, "s": 3902, "text": "Two conventional statistical feature techniques that can be used for categorical features in a classification problem are:" }, { "code": null, "e": 4076, "s": 4025, "text": "Chi-Squared Test of IndependenceMutual Information" }, { "code": null, "e": 4109, "s": 4076, "text": "Chi-Squared Test of Independence" }, { "code": null, "e": 4128, "s": 4109, "text": "Mutual Information" }, { "code": null, "e": 4337, "s": 4128, "text": "The Chi-Squared test is used to determine the extent of relationship or dependence between two categorical variables — in our case, one categorical input feature, and the other, a categorical target variable." }, { "code": null, "e": 4512, "s": 4337, "text": "In probability and information theories, the Mutual Information of two random variables measures the level of independence between them. Higher values mean higher dependency." }, { "code": null, "e": 4937, "s": 4512, "text": "For categorical features encoded as integers (e.g., through OrdinalEncoder), scikit-learn’s SelectKBest class is used in conjunction with either the chi2 or mutual_info_classif functions to identify and select the top k most relevant features. The higher the score returned by SelectKBest, the better that feature’s predictive power will be. The shortlisted features are then fed into the ML algorithm for model development." }, { "code": null, "e": 5015, "s": 4937, "text": "A complete working example showing both chi2 and mutual_info_classif follows:" }, { "code": null, "e": 5549, "s": 5015, "text": "Note that SelectKBest can also be used as part of a Pipeline for cross-validation purposes. However, depending upon the cardinality of your input features, using OrdinalEncoder in a Pipeline can sometimes not be feasible when the model comes across new value in the test set that was not available in the train set and was therefore not used for encoding. A workaround in such situations could be to run train_test_split multiple times with different test_size and random_state, and take an average of the selected validation metric." }, { "code": null, "e": 5934, "s": 5549, "text": "For object type categorical features that have not been numerically encoded (maybe because they will be one-hot encoded or converted to dummy variables at a later stage), SciPy’s chi2_contingency class is used to calculate the chi statistic and p values of each pair of categorical features and the target variable. Features with the lowest p values are then shortlisted for modeling." }, { "code": null, "e": 5970, "s": 5934, "text": "A complete working example follows:" }, { "code": null, "e": 6091, "s": 5970, "text": "Two conventional statistical feature techniques that can be used for numerical features in a classification problem are:" }, { "code": null, "e": 6148, "s": 6091, "text": "ANOVA F-StatisticMutual Information (as explained above)" }, { "code": null, "e": 6166, "s": 6148, "text": "ANOVA F-Statistic" }, { "code": null, "e": 6206, "s": 6166, "text": "Mutual Information (as explained above)" }, { "code": null, "e": 6582, "s": 6206, "text": "The Analysis of Variance (ANOVA) F-statistic calculates the ratio of variances of the means of two or more samples of data. The higher this ratio between a numerical input feature and a categorical target feature, the lower the independence between the two and more likely to be useful for model training. Refer to this excellent article for details on the ANOVA F-statistic." }, { "code": null, "e": 6889, "s": 6582, "text": "ANOVA F-statistic for feature selection is similarly implemented in Python as a chi-squared test of independence through sci-kit learn’s f_classif function. Given that we are dealing with numerical features this time around, we can easily implement cross-validation through pipelines as demonstrated below:" }, { "code": null, "e": 7075, "s": 6889, "text": "Ah, this is the easiest type of feature selection: identifying the most suitable numeric input feature for a numerical target variable (regression problem). Possible techniques include:" }, { "code": null, "e": 7213, "s": 7075, "text": "Correlation statisticsMutual Information (same as explained earlier, with just a different score_func to be used: mutual_info_regression)" }, { "code": null, "e": 7236, "s": 7213, "text": "Correlation statistics" }, { "code": null, "e": 7352, "s": 7236, "text": "Mutual Information (same as explained earlier, with just a different score_func to be used: mutual_info_regression)" }, { "code": null, "e": 7732, "s": 7352, "text": "Correlation measures the degree of change in one variable as a result of another. Perhaps the best-known correlation measure is Pearson’s correlation that assumes a Gaussian distribution of the data. Correlation coefficients range between -1 (perfect negative correlation) and 1 (perfect positive correlation) with 0 representing no relationship between the variables whatsoever." }, { "code": null, "e": 8133, "s": 7732, "text": "In addition to plotting the correlation matrix, automatic correlation-based feature selection can be implemented similar to a chi-squared test of independence or ANOVA F-statistic, using sci-kit learn’s f_regression function in conjunction with the SelectKBest class. Further, just like the ANOVA F-statistic function, we can easily implement cross-validation through pipelines as demonstrated below:" }, { "code": null, "e": 8394, "s": 8133, "text": "Recursive Feature Elimination (RFE) from scikit-learn is the most widely used wrapper feature selection method in practice. RFE is feature-type agnostic that iteratively selects the best number of features through a given supervised learning model (estimator)." }, { "code": null, "e": 8820, "s": 8394, "text": "From scikit-learn documentation: “First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached.”" }, { "code": null, "e": 9183, "s": 8820, "text": "As evident from the above, RFE can only be used with an algorithm that has either a coef_ or feature_importances_ attribute to evaluate feature importance. Since RFE is a wrapper feature selection technique, it can use any given estimator (that can be different from the algorithm that is applied to the selected features) to identify the most suitable features." }, { "code": null, "e": 9341, "s": 9183, "text": "Given that RFE can be used for both categorical and numerical features; its implementation is similar in case of both classification and regression problems." }, { "code": null, "e": 9594, "s": 9341, "text": "The main parameter of RFE that requires tuning is n_features_to_select. A practical demonstration to identify the best number of features based on RFE using DecisionTreeClassifier for both feature selection and the classification algorithm is as below:" }, { "code": null, "e": 9735, "s": 9594, "text": "The above code snippet will print out the mean and STD of Accuracy scores for each number of features utilized in RFE, something like below:" }, { "code": null, "e": 9808, "s": 9735, "text": ">2: 0.710>3: 0.815>4: 0.872>5: 0.884>6: 0.891>7: 0.888>8: 0.888>9: 0.884" }, { "code": null, "e": 9905, "s": 9808, "text": "Based purely on the Accuracy score, selecting six features appears to be ideal in this scenario." }, { "code": null, "e": 10095, "s": 9905, "text": "However, how do we know that DecisionTreeClassifier is the best algorithm to be used within RFE? What if we would like to evaluate various algorithms with RFE? RFECV comes to our help here." }, { "code": null, "e": 10516, "s": 10095, "text": "The primary purpose of RFECV is to select the best number of features through cross-validation automatically. Since the ideal number of features will be auto-selected by RFECV (therefore, not requiring the for loop in the last code snippet), we can efficiently train and assess multiple models for RFECV feature selection. The model with the best validation metric can then be used moving forward for making predictions." }, { "code": null, "e": 10556, "s": 10516, "text": "Let us look at a practical example now:" }, { "code": null, "e": 10693, "s": 10556, "text": "The above code snippet will print out the mean and STD of Accuracy scores for each of the model utilized in RFECV, something like below:" }, { "code": null, "e": 10735, "s": 10693, "text": ">LR: 0.891>DT: 0.882>RF: 0.888>XGB: 0.886" }, { "code": null, "e": 10853, "s": 10735, "text": "The simple logistic regression model wins for wrapper feature selection. We can then use this for making predictions:" }, { "code": null, "e": 11289, "s": 10853, "text": "# create pipelinerfecv = RFECV(estimator = LogisticRegression(), cv = 10, scoring = 'accuracy')model = DecisionTreeClassifier()pipeline = Pipeline(steps=[('features', rfecv), ('model', model)])# fit the model on all available datapipeline.fit(X, y)# make a prediction for one exampledata = #load or define any new data unseen data that you want to make predictions uponyhat = pipeline.predict(data)print('Predicted: %.3f' % (yhat))" }, { "code": null, "e": 11444, "s": 11289, "text": "The majority of ML algorithms have a built-in attribute to view the relative importance of the features used during model learning. Some examples include:" }, { "code": null, "e": 11593, "s": 11444, "text": "Linear Regression: coef_ gives the list of coefficients. Higher the coefficient, the more of an impact that input feature has on the target variable" }, { "code": null, "e": 11711, "s": 11593, "text": "Logistic Regression: coef_ provides the list of coefficients, to be interpreted the same as that in Linear Regression" }, { "code": null, "e": 11786, "s": 11711, "text": "Decision Trees and Random Forests: feature_importanes_ — higher the better" }, { "code": null, "e": 11960, "s": 11786, "text": "That is it from me this time. Feel free to reach out to me if you would like to discuss anything related to data analytics, traditional machine learning, or credit analysis." }, { "code": null, "e": 11985, "s": 11960, "text": "Till next time, rock on!" }, { "code": null, "e": 12044, "s": 11985, "text": "Inspired by Dr. Jason Brownlee of Machine Learning Mastery" } ]
How to write the temperature conversion table by using function?
Temperature conversion is nothing but converting Fahrenheit temperature to Celsius or Celsius to Fahrenheit. In this programming, we are going to explain, how to convert the Fahrenheit temperature to Celsius temperature and how to represent the same in the form of the table by using a function. Following is the C program for temperature conversion − Live Demo #include<stdio.h> float conversion(float); int main(){ float fh,cl; int begin=0,stop=300; printf("Fahrenheit \t Celsius\n");// display conversion table heading printf("----------\t-----------\n"); fh=begin; while(fh<=stop){ cl=conversion(fh); //calling function printf("%3.0f\t\t%6.lf\n",fh,cl); fh=fh+20; } return 0; } float conversion(float fh) //called function{ float cl; cl= (fh - 32) * 5 / 9; return cl; } When the above program is executed, it produces the following result − Fahrenheit Celsius ---------- ----------- 0 -18 20 -7 40 4 60 16 80 27 100 38 120 49 140 60 160 71 180 82 200 93 220 104 240 116 260 127 280 138 300 149 In a similar way, you can write the program for converting Celsius to Fahrenheit By simply changing the equation to Fahrenheit = (Celsius* 9 / 5) + 32.
[ { "code": null, "e": 1171, "s": 1062, "text": "Temperature conversion is nothing but converting Fahrenheit temperature to Celsius or Celsius to Fahrenheit." }, { "code": null, "e": 1358, "s": 1171, "text": "In this programming, we are going to explain, how to convert the Fahrenheit temperature to Celsius temperature and how to represent the same in the form of the table by using a function." }, { "code": null, "e": 1414, "s": 1358, "text": "Following is the C program for temperature conversion −" }, { "code": null, "e": 1425, "s": 1414, "text": " Live Demo" }, { "code": null, "e": 1888, "s": 1425, "text": "#include<stdio.h>\nfloat conversion(float);\nint main(){\n float fh,cl;\n int begin=0,stop=300;\n printf(\"Fahrenheit \\t Celsius\\n\");// display conversion table heading\n printf(\"----------\\t-----------\\n\");\n fh=begin;\n while(fh<=stop){\n cl=conversion(fh); //calling function\n printf(\"%3.0f\\t\\t%6.lf\\n\",fh,cl);\n fh=fh+20;\n }\n return 0;\n}\nfloat conversion(float fh) //called function{\n float cl;\n cl= (fh - 32) * 5 / 9;\n return cl;\n}" }, { "code": null, "e": 1959, "s": 1888, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2293, "s": 1959, "text": "Fahrenheit Celsius\n---------- -----------\n 0 -18\n 20 -7\n 40 4\n 60 16\n 80 27\n 100 38\n 120 49\n 140 60\n 160 71\n 180 82\n 200 93\n 220 104\n 240 116\n 260 127\n 280 138\n 300 149" }, { "code": null, "e": 2374, "s": 2293, "text": "In a similar way, you can write the program for converting Celsius to Fahrenheit" }, { "code": null, "e": 2409, "s": 2374, "text": "By simply changing the equation to" }, { "code": null, "e": 2445, "s": 2409, "text": "Fahrenheit = (Celsius* 9 / 5) + 32." } ]
Cross Product Operation in DFA - GeeksforGeeks
20 Nov, 2019 Prerequisite: Designing finite automataLet’s understand the cross product operation in Deterministic Finite Automata (DFA) with help of the below example- Designing a DFA for the set of string over {a, b} such that string of the language contains even number of a’s and b’s then desired language will be like below- L = {ε, aa, bb, abab, aabb, baba, bbaa, .......} Let’s see steps for cross product operation in DFA: Step-1:Let’s form a DFA which count even number of a’s-In the below state transition diagram, ‘W’ is the initial state and final state too, which accept language of string containing even number of a’s and any number of b’s.The language accepted by above DFA is- L = {ε, aab, b, baa, aabbbbb, aaaab, ..........} The language does not accepted by above DFA is- L = {aaa, abbb, baaa, bbaaba, ...........} Step-2:Let’s form a DFA which count even number of b’s-In the below state transition diagram, ‘Y’ is the initial state and final state too, which accept language of string containing even number of b’s and any number of a’s.The language accepted by above DFA is- L = {ε, bba, a, abb, bbbbaaaa, bbbba, ...........} The language does not accepted by above DFA is- L = {bbb, bbba, abbb, aaba, ...........} Step-3:Here the states of step-1 and step-2 get cross multiplied and produce a result like below- {W, X} * {Y, Z} = {WY, WZ, XY, XZ} And in the below, state transition diagram four states {WY, WZ, XY, XZ} used is the result of the cross product of step 1 and 2 states out of which ‘WY’ is the initial and final state too because in step 1 ‘W’ is the initial and final state and in step 2 ‘Y’ is the initial and final state and rest are normal states.Then the resultant state transition diagram after cross product operation becomes like below-Thus the above DFA accepts all the language of an even number of a’s and b’s string and the language which is accepted and not accepted by above DFA is given below- L1 = {ε, aa, bb, abab, aabb, baba, bbaa, .......} L2 = {aaa, aaabb, aaabaabb, aaabb, baaba, bbbaa, .......} L1 is accepted by above DFA but L2 does not. GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Clustered and Non-clustered index Phases of a Compiler Regular Expressions, Regular Grammar and Regular Languages Preemptive and Non-Preemptive Scheduling Introduction of Process Synchronization Regular Expressions, Regular Grammar and Regular Languages Difference between DFA and NFA Introduction of Finite Automata Difference between Mealy machine and Moore machine Pumping Lemma in Theory of Computation
[ { "code": null, "e": 24352, "s": 24324, "text": "\n20 Nov, 2019" }, { "code": null, "e": 24507, "s": 24352, "text": "Prerequisite: Designing finite automataLet’s understand the cross product operation in Deterministic Finite Automata (DFA) with help of the below example-" }, { "code": null, "e": 24668, "s": 24507, "text": "Designing a DFA for the set of string over {a, b} such that string of the language contains even number of a’s and b’s then desired language will be like below-" }, { "code": null, "e": 24717, "s": 24668, "text": "L = {ε, aa, bb, abab, aabb, baba, bbaa, .......}" }, { "code": null, "e": 24769, "s": 24717, "text": "Let’s see steps for cross product operation in DFA:" }, { "code": null, "e": 25032, "s": 24769, "text": "Step-1:Let’s form a DFA which count even number of a’s-In the below state transition diagram, ‘W’ is the initial state and final state too, which accept language of string containing even number of a’s and any number of b’s.The language accepted by above DFA is-" }, { "code": null, "e": 25081, "s": 25032, "text": "L = {ε, aab, b, baa, aabbbbb, aaaab, ..........}" }, { "code": null, "e": 25129, "s": 25081, "text": "The language does not accepted by above DFA is-" }, { "code": null, "e": 25172, "s": 25129, "text": "L = {aaa, abbb, baaa, bbaaba, ...........}" }, { "code": null, "e": 25435, "s": 25172, "text": "Step-2:Let’s form a DFA which count even number of b’s-In the below state transition diagram, ‘Y’ is the initial state and final state too, which accept language of string containing even number of b’s and any number of a’s.The language accepted by above DFA is-" }, { "code": null, "e": 25486, "s": 25435, "text": "L = {ε, bba, a, abb, bbbbaaaa, bbbba, ...........}" }, { "code": null, "e": 25534, "s": 25486, "text": "The language does not accepted by above DFA is-" }, { "code": null, "e": 25575, "s": 25534, "text": "L = {bbb, bbba, abbb, aaba, ...........}" }, { "code": null, "e": 25673, "s": 25575, "text": "Step-3:Here the states of step-1 and step-2 get cross multiplied and produce a result like below-" }, { "code": null, "e": 25709, "s": 25673, "text": "{W, X} * {Y, Z} = {WY, WZ, XY, XZ} " }, { "code": null, "e": 26284, "s": 25709, "text": "And in the below, state transition diagram four states {WY, WZ, XY, XZ} used is the result of the cross product of step 1 and 2 states out of which ‘WY’ is the initial and final state too because in step 1 ‘W’ is the initial and final state and in step 2 ‘Y’ is the initial and final state and rest are normal states.Then the resultant state transition diagram after cross product operation becomes like below-Thus the above DFA accepts all the language of an even number of a’s and b’s string and the language which is accepted and not accepted by above DFA is given below-" }, { "code": null, "e": 26393, "s": 26284, "text": "L1 = {ε, aa, bb, abab, aabb, baba, bbaa, .......}\nL2 = {aaa, aaabb, aaabaabb, aaabb, baaba, bbbaa, .......}\n" }, { "code": null, "e": 26438, "s": 26393, "text": "L1 is accepted by above DFA but L2 does not." }, { "code": null, "e": 26446, "s": 26438, "text": "GATE CS" }, { "code": null, "e": 26479, "s": 26446, "text": "Theory of Computation & Automata" }, { "code": null, "e": 26577, "s": 26479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26586, "s": 26577, "text": "Comments" }, { "code": null, "e": 26599, "s": 26586, "text": "Old Comments" }, { "code": null, "e": 26652, "s": 26599, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26673, "s": 26652, "text": "Phases of a Compiler" }, { "code": null, "e": 26732, "s": 26673, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 26773, "s": 26732, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 26813, "s": 26773, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 26872, "s": 26813, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 26903, "s": 26872, "text": "Difference between DFA and NFA" }, { "code": null, "e": 26935, "s": 26903, "text": "Introduction of Finite Automata" }, { "code": null, "e": 26986, "s": 26935, "text": "Difference between Mealy machine and Moore machine" } ]
Dart Programming - Defining a Function
A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The syntax for defining a standard function is given below − function_name() { //statements } OR void function_name() { //statements } The void keyword indicates that the function does not return any value to the caller. test() { //function definition print("function called"); } 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2707, "s": 2525, "text": "A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The syntax for defining a standard function is given below −" }, { "code": null, "e": 2752, "s": 2707, "text": "function_name() { \n //statements \n}\n" }, { "code": null, "e": 2755, "s": 2752, "text": "OR" }, { "code": null, "e": 2799, "s": 2755, "text": "void function_name() { \n //statements \n}\n" }, { "code": null, "e": 2885, "s": 2799, "text": "The void keyword indicates that the function does not return any value to the caller." }, { "code": null, "e": 2952, "s": 2885, "text": "test() { \n //function definition \n print(\"function called\"); }" }, { "code": null, "e": 2987, "s": 2952, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3007, "s": 2987, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3040, "s": 3007, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3060, "s": 3040, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3093, "s": 3060, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3110, "s": 3093, "text": " Frahaan Hussain" }, { "code": null, "e": 3145, "s": 3110, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3162, "s": 3145, "text": " Frahaan Hussain" }, { "code": null, "e": 3197, "s": 3162, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3217, "s": 3197, "text": " Pranjal Srivastava" }, { "code": null, "e": 3250, "s": 3217, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3270, "s": 3250, "text": " Pranjal Srivastava" }, { "code": null, "e": 3277, "s": 3270, "text": " Print" }, { "code": null, "e": 3288, "s": 3277, "text": " Add Notes" } ]
How to retrieve table names from a database in MySQL?
To retrieve table names from a database in MySQL, the syntax is as follows − show tables from yourDatabaseName; Let us implement the above query in order to retrieve table names from a database in MySQL − mysql> show tables from hb_student_tracker; This will produce the following output − +------------------------------+ | Tables_in_hb_student_tracker | +------------------------------+ | demotable192 | | demotable193 | | demotable194 | | demotable195 | | demotable196 | | demotable197 | | demotable198 | | demotable199 | | demotable200 | | demotable201 | | demotable202 | | demotable203 | | demotable204 | | demotable205 | | demotable206 | | demotable207 | | demotable208 | | demotable209 | | demotable210 | | demotable211 | | demotable212 | | demotable213 | | demotable214 | | demotable215 | | demotable216 | | demotable217 | | demotable218 | | demotable219 | | demotable220 | | demotable221 | | demotable223 | | demotable224 | | demotable225 | | demotable226 | | demotable227 | | demotable228 | | demotable229 | | demotable230 | | demotable231 | | demotable232 | | demotable233 | | insertcurrentdate | | reorderintegerexcept0 | | student | +------------------------------+ 44 rows in set (0.00 sec)
[ { "code": null, "e": 1139, "s": 1062, "text": "To retrieve table names from a database in MySQL, the syntax is as follows −" }, { "code": null, "e": 1174, "s": 1139, "text": "show tables from yourDatabaseName;" }, { "code": null, "e": 1267, "s": 1174, "text": "Let us implement the above query in order to retrieve table names from a database in MySQL −" }, { "code": null, "e": 1311, "s": 1267, "text": "mysql> show tables from hb_student_tracker;" }, { "code": null, "e": 1352, "s": 1311, "text": "This will produce the following output −" }, { "code": null, "e": 2962, "s": 1352, "text": "+------------------------------+\n| Tables_in_hb_student_tracker |\n+------------------------------+\n| demotable192 |\n| demotable193 |\n| demotable194 |\n| demotable195 |\n| demotable196 |\n| demotable197 |\n| demotable198 |\n| demotable199 |\n| demotable200 |\n| demotable201 |\n| demotable202 |\n| demotable203 |\n| demotable204 |\n| demotable205 |\n| demotable206 |\n| demotable207 |\n| demotable208 |\n| demotable209 |\n| demotable210 |\n| demotable211 |\n| demotable212 |\n| demotable213 |\n| demotable214 |\n| demotable215 |\n| demotable216 |\n| demotable217 |\n| demotable218 |\n| demotable219 |\n| demotable220 |\n| demotable221 |\n| demotable223 |\n| demotable224 |\n| demotable225 |\n| demotable226 |\n| demotable227 |\n| demotable228 |\n| demotable229 |\n| demotable230 |\n| demotable231 |\n| demotable232 |\n| demotable233 |\n| insertcurrentdate |\n| reorderintegerexcept0 |\n| student |\n+------------------------------+\n44 rows in set (0.00 sec)" } ]
Python Plotly – Exporting to Static Images
19 Dec, 2021 In this article, we will discuss how to export plotly graphs as static images using Python. To get the job done there are certain additional installations that need to be done. Apart from plotly, orca and psutil have to be installed. psutil (python system and process utilities) is a cross-platform Python package that retrieves information about running processes and system utilisation. It can be installed as follows. pip install psutil ocra cannot be installed via pip so conda is employed for the same. conda install -c plotly plotly-orca psutil Once all installations are successful, we have to import plotly.io when importing other required modules and use, write_image() function to save the output plot. Syntax: write_image(figure, path) Parameter: figure: plot format: location to save along with the format Plotly images can be made static if they are exported either as images or in vector format. The only difference is specifying the format while importing. Example: In this example, we export a plotly graph as an image in python. Dataset used here: bestsellers.csv Python3 # import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio # read datasetdata = pd.read_csv("bestsellers.csv") # create plotfig = px.scatter(data, x="Year", y="Price", color="Genre") # export as static imagepio.write_image(fig, "op.png") Output: Example: In this example, we export plotly graph as a vector image in python. Python3 # import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio # read datasetdata = pd.read_csv("bestsellers.csv") # create plotfig = px.scatter(data, x="Year", y="Price", color="Genre") # export as static imagepio.write_image(fig, "op.pdf") Output: Picked Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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 Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 120, "s": 28, "text": "In this article, we will discuss how to export plotly graphs as static images using Python." }, { "code": null, "e": 262, "s": 120, "text": "To get the job done there are certain additional installations that need to be done. Apart from plotly, orca and psutil have to be installed." }, { "code": null, "e": 450, "s": 262, "text": "psutil (python system and process utilities) is a cross-platform Python package that retrieves information about running processes and system utilisation. It can be installed as follows." }, { "code": null, "e": 469, "s": 450, "text": "pip install psutil" }, { "code": null, "e": 537, "s": 469, "text": "ocra cannot be installed via pip so conda is employed for the same." }, { "code": null, "e": 580, "s": 537, "text": "conda install -c plotly plotly-orca psutil" }, { "code": null, "e": 742, "s": 580, "text": "Once all installations are successful, we have to import plotly.io when importing other required modules and use, write_image() function to save the output plot." }, { "code": null, "e": 750, "s": 742, "text": "Syntax:" }, { "code": null, "e": 776, "s": 750, "text": "write_image(figure, path)" }, { "code": null, "e": 787, "s": 776, "text": "Parameter:" }, { "code": null, "e": 800, "s": 787, "text": "figure: plot" }, { "code": null, "e": 847, "s": 800, "text": "format: location to save along with the format" }, { "code": null, "e": 1001, "s": 847, "text": "Plotly images can be made static if they are exported either as images or in vector format. The only difference is specifying the format while importing." }, { "code": null, "e": 1011, "s": 1001, "text": "Example: " }, { "code": null, "e": 1077, "s": 1011, "text": "In this example, we export a plotly graph as an image in python. " }, { "code": null, "e": 1112, "s": 1077, "text": "Dataset used here: bestsellers.csv" }, { "code": null, "e": 1120, "s": 1112, "text": "Python3" }, { "code": "# import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio # read datasetdata = pd.read_csv(\"bestsellers.csv\") # create plotfig = px.scatter(data, x=\"Year\", y=\"Price\", color=\"Genre\") # export as static imagepio.write_image(fig, \"op.png\")", "e": 1390, "s": 1120, "text": null }, { "code": null, "e": 1398, "s": 1390, "text": "Output:" }, { "code": null, "e": 1476, "s": 1398, "text": "Example: In this example, we export plotly graph as a vector image in python." }, { "code": null, "e": 1484, "s": 1476, "text": "Python3" }, { "code": "# import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio # read datasetdata = pd.read_csv(\"bestsellers.csv\") # create plotfig = px.scatter(data, x=\"Year\", y=\"Price\", color=\"Genre\") # export as static imagepio.write_image(fig, \"op.pdf\")", "e": 1754, "s": 1484, "text": null }, { "code": null, "e": 1762, "s": 1754, "text": "Output:" }, { "code": null, "e": 1769, "s": 1762, "text": "Picked" }, { "code": null, "e": 1783, "s": 1769, "text": "Python-Plotly" }, { "code": null, "e": 1790, "s": 1783, "text": "Python" }, { "code": null, "e": 1888, "s": 1790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1920, "s": 1888, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1947, "s": 1920, "text": "Python Classes and Objects" }, { "code": null, "e": 1968, "s": 1947, "text": "Python OOPs Concepts" }, { "code": null, "e": 1991, "s": 1968, "text": "Introduction To PYTHON" }, { "code": null, "e": 2022, "s": 1991, "text": "Python | os.path.join() method" }, { "code": null, "e": 2078, "s": 2022, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2120, "s": 2078, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2162, "s": 2120, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2201, "s": 2162, "text": "Python | Get unique values from a list" } ]
HTML | target Attribute
13 Dec, 2021 The HTML target Attribute is used to specify where to open the linked document. It can be used on various elements such as: HTML | <a> target Attribute HTML | <area> target Attribute HTML | <base> target Attribute HTML | <form> target Attribute Syntax: <element target="_blank|_self|_parent|_top|framename"\> Attribute Values: _blank: It opens the link in a new window. _self: It is the default value. It opens the linked document in the same frame. _parent: It opens the linked document in the parent frameset. _top: It opens the linked document in the full body of the window. framename: It opens the linked document in the named frame. Example: <!DOCTYPE html> <html> <head> <title> HTML target Attribute </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTML Target Attribute</h2> <p>Welcome to <a href="https://ide.geeksforgeeks.org/" id="GFG" target="_self"> GeeksforGeeks </a> </p> </center> </body> </html> Output: Supported Browsers: The browser supported by HTML target Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari arorakashish0911 chhabradhanvi 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": "\n13 Dec, 2021" }, { "code": null, "e": 152, "s": 28, "text": "The HTML target Attribute is used to specify where to open the linked document. It can be used on various elements such as:" }, { "code": null, "e": 180, "s": 152, "text": "HTML | <a> target Attribute" }, { "code": null, "e": 211, "s": 180, "text": "HTML | <area> target Attribute" }, { "code": null, "e": 242, "s": 211, "text": "HTML | <base> target Attribute" }, { "code": null, "e": 273, "s": 242, "text": "HTML | <form> target Attribute" }, { "code": null, "e": 281, "s": 273, "text": "Syntax:" }, { "code": null, "e": 337, "s": 281, "text": "<element target=\"_blank|_self|_parent|_top|framename\"\\>" }, { "code": null, "e": 355, "s": 337, "text": "Attribute Values:" }, { "code": null, "e": 398, "s": 355, "text": "_blank: It opens the link in a new window." }, { "code": null, "e": 478, "s": 398, "text": "_self: It is the default value. It opens the linked document in the same frame." }, { "code": null, "e": 540, "s": 478, "text": "_parent: It opens the linked document in the parent frameset." }, { "code": null, "e": 607, "s": 540, "text": "_top: It opens the linked document in the full body of the window." }, { "code": null, "e": 667, "s": 607, "text": "framename: It opens the linked document in the named frame." }, { "code": null, "e": 676, "s": 667, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML target Attribute </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>HTML Target Attribute</h2> <p>Welcome to <a href=\"https://ide.geeksforgeeks.org/\" id=\"GFG\" target=\"_self\"> GeeksforGeeks </a> </p> </center> </body> </html> ", "e": 1079, "s": 676, "text": null }, { "code": null, "e": 1087, "s": 1079, "text": "Output:" }, { "code": null, "e": 1172, "s": 1087, "text": "Supported Browsers: The browser supported by HTML target Attribute are listed below:" }, { "code": null, "e": 1186, "s": 1172, "text": "Google Chrome" }, { "code": null, "e": 1204, "s": 1186, "text": "Internet Explorer" }, { "code": null, "e": 1212, "s": 1204, "text": "Firefox" }, { "code": null, "e": 1218, "s": 1212, "text": "Opera" }, { "code": null, "e": 1225, "s": 1218, "text": "Safari" }, { "code": null, "e": 1242, "s": 1225, "text": "arorakashish0911" }, { "code": null, "e": 1256, "s": 1242, "text": "chhabradhanvi" }, { "code": null, "e": 1272, "s": 1256, "text": "HTML-Attributes" }, { "code": null, "e": 1277, "s": 1272, "text": "HTML" }, { "code": null, "e": 1294, "s": 1277, "text": "Web Technologies" }, { "code": null, "e": 1299, "s": 1294, "text": "HTML" } ]
JavaScript | typedArray.subarray() with Examples
14 Feb, 2019 The typedArray.subarray() is an inbuilt function in JavaScript which is used to return a part of the typedArray object.Syntax: typedarray.subarray(begin, end) Parameters: It accepts two parameters which are described below: begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive.end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive. begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive. end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive. Return value: It returns a new array which is formed from the given typedArray object. <script> // Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]); // Calling subarray() functions B = A.subarray(1, 3) C = A.subarray(1) D = A.subarray(3) E = A.subarray(0, 6) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray document.write(B +"<br>"); document.write(C +"<br>"); document.write(D +"<br>"); document.write(E +"<br>"); document.write(F +"<br>"); </script> Output: 10,15 10,15,20,25,30,35 20,25,30,35 5,10,15,20,25,30 5,10,15,20,25,30,35 Code #2:When index are in negative then elements get accessed from the end of the typedArray object. Below is the required code which illustrates this negative indexing concept. <script> // Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]); // Calling subarray() functions B = A.subarray(-1) C = A.subarray(-2) D = A.subarray(-3) E = A.subarray(3) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray document.write(B +"<br>"); document.write(C +"<br>"); document.write(D +"<br>"); document.write(E +"<br>"); document.write(F +"<br>"); </script> Output: 35 30,35 25,30,35 20,25,30,35 5,10,15,20,25,30,35 javascript-functions javascript-typedArray JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? Lodash _.debounce() Method JavaScript String includes() Method JavaScript | fetch() Method Lodash _.groupBy() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2019" }, { "code": null, "e": 155, "s": 28, "text": "The typedArray.subarray() is an inbuilt function in JavaScript which is used to return a part of the typedArray object.Syntax:" }, { "code": null, "e": 187, "s": 155, "text": "typedarray.subarray(begin, end)" }, { "code": null, "e": 252, "s": 187, "text": "Parameters: It accepts two parameters which are described below:" }, { "code": null, "e": 525, "s": 252, "text": "begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive.end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive." }, { "code": null, "e": 663, "s": 525, "text": "begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive." }, { "code": null, "e": 799, "s": 663, "text": "end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive." }, { "code": null, "e": 886, "s": 799, "text": "Return value: It returns a new array which is formed from the given typedArray object." }, { "code": "<script> // Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]); // Calling subarray() functions B = A.subarray(1, 3) C = A.subarray(1) D = A.subarray(3) E = A.subarray(0, 6) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray document.write(B +\"<br>\"); document.write(C +\"<br>\"); document.write(D +\"<br>\"); document.write(E +\"<br>\"); document.write(F +\"<br>\"); </script>", "e": 1397, "s": 886, "text": null }, { "code": null, "e": 1405, "s": 1397, "text": "Output:" }, { "code": null, "e": 1478, "s": 1405, "text": "10,15\n10,15,20,25,30,35\n20,25,30,35\n5,10,15,20,25,30\n5,10,15,20,25,30,35" }, { "code": null, "e": 1579, "s": 1478, "text": "Code #2:When index are in negative then elements get accessed from the end of the typedArray object." }, { "code": null, "e": 1656, "s": 1579, "text": "Below is the required code which illustrates this negative indexing concept." }, { "code": "<script> // Creating a new typedArray Uint8Array() object const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]); // Calling subarray() functions B = A.subarray(-1) C = A.subarray(-2) D = A.subarray(-3) E = A.subarray(3) F = A.subarray(0) // Printing some new typedArray which are // the part of the given input typedArray document.write(B +\"<br>\"); document.write(C +\"<br>\"); document.write(D +\"<br>\"); document.write(E +\"<br>\"); document.write(F +\"<br>\"); </script>", "e": 2164, "s": 1656, "text": null }, { "code": null, "e": 2172, "s": 2164, "text": "Output:" }, { "code": null, "e": 2222, "s": 2172, "text": "35\n30,35\n25,30,35\n20,25,30,35\n5,10,15,20,25,30,35" }, { "code": null, "e": 2243, "s": 2222, "text": "javascript-functions" }, { "code": null, "e": 2265, "s": 2243, "text": "javascript-typedArray" }, { "code": null, "e": 2276, "s": 2265, "text": "JavaScript" }, { "code": null, "e": 2374, "s": 2276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2435, "s": 2374, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2475, "s": 2435, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2517, "s": 2475, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2558, "s": 2517, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2580, "s": 2558, "text": "JavaScript | Promises" }, { "code": null, "e": 2628, "s": 2580, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 2655, "s": 2628, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 2691, "s": 2655, "text": "JavaScript String includes() Method" }, { "code": null, "e": 2719, "s": 2691, "text": "JavaScript | fetch() Method" } ]
Compare two file paths in Java
Two file paths can be compared lexicographically in Java using the method java.io.File.compareTo(). This method requires a single parameter i.e.the abstract path name that is to be compared. It returns 0 if the two file path names are equal. A program that demonstrates this is given as follows − Live Demo import java.io.File; public class Demo { public static void main(String[] args) { File file1 = new File("C:/File/demo1.txt"); File file2 = new File("C:/File/demo1.txt"); if (file1.compareTo(file2) == 0) { System.out.println("Both the paths are lexicographically equal"); } else { System.out.println("Both the paths are lexicographically not equal"); } } } The output of the above program is as follows − Both the paths are lexicographically equal Now let us understand the above program. The method java.io.File.compareTo() is used to compare the two file paths lexicographically. If 0 is returned by the method, the file paths are lexicographically equal, otherwise not. A code snippet that demonstrates this is given as follows − File file1 = new File("C:/File/demo1.txt"); File file2 = new File("C:/File/demo1.txt"); if (file1.compareTo(file2) == 0) { System.out.println("Both the paths are lexicographically equal"); } else { System.out.println("Both the paths are lexicographically not equal"); }
[ { "code": null, "e": 1304, "s": 1062, "text": "Two file paths can be compared lexicographically in Java using the method java.io.File.compareTo(). This method requires a single parameter i.e.the abstract path name that is to be compared. It returns 0 if the two file path names are equal." }, { "code": null, "e": 1359, "s": 1304, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1370, "s": 1359, "text": " Live Demo" }, { "code": null, "e": 1780, "s": 1370, "text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n File file1 = new File(\"C:/File/demo1.txt\");\n File file2 = new File(\"C:/File/demo1.txt\");\n if (file1.compareTo(file2) == 0) {\n System.out.println(\"Both the paths are lexicographically equal\");\n } else {\n System.out.println(\"Both the paths are lexicographically not equal\");\n }\n }\n}" }, { "code": null, "e": 1828, "s": 1780, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1871, "s": 1828, "text": "Both the paths are lexicographically equal" }, { "code": null, "e": 1912, "s": 1871, "text": "Now let us understand the above program." }, { "code": null, "e": 2156, "s": 1912, "text": "The method java.io.File.compareTo() is used to compare the two file paths lexicographically. If 0 is returned by the method, the file paths are lexicographically equal, otherwise not. A code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2432, "s": 2156, "text": "File file1 = new File(\"C:/File/demo1.txt\");\nFile file2 = new File(\"C:/File/demo1.txt\");\nif (file1.compareTo(file2) == 0) {\n System.out.println(\"Both the paths are lexicographically equal\");\n} else {\n System.out.println(\"Both the paths are lexicographically not equal\");\n}" } ]
Automated Web Scraping Using Cron | Towards Data Science
Sometimes, we want to do some task daily. It seems boring if you do it by yourself, and you waste your time just for doing it. Automation is what we need. By scheduling it at a given time, we can save our time, and let the computer do the task itself. In this article, I want to show you how to build a COVID-19 dataset for Riau Province, Indonesia using Python to retrieve the dataset and also Cron to schedule the task. If you want to know more, you can check about it on my GitHub repository here. Riau is a province in Indonesia. Just like other places, this place also fights COVID-19. They have the source of information which is corona.riau.go.id. The front page looks like this, On the website, it shows the number of cases that exist at the province and regional level. Although it is up to date, they do not show the historical data of it. Just like these pictures below, Because of that problem, I propose a web scraping technique to record the data and save them as .csv format. After this, I will show you step-by-step on how I scrape the website, and how to automate those task at a given schedule. The first thing that I do is to scrape the website. To scrape it, I use the bs4 library to extract the text from it. For this case, There are some problems. First, the table that I’ve shown before is from another website, and it’s just a frame at the web. Therefore, we have to get the source of it. On Microsoft Edge browser, We can get the source of the frame for each table by right-clicking on it, and select view frame source. For the province-level data, the source comes from https://covid19.riau.go.id/webster. For the city or regency level, the source comes from https://covid19.riau.go.id/pantauan_data_kasus. The next step is to scrape each website to get the data that we need. First, we will extract the data from https://covid19.riau.go.id/webster. Retrieving the data is not so difficult because we only have to inspect which tag belongs to the number. The data that we want to extract is just the numbers of each column, so we can make the column’s name using a list. Based on the picture above, the <td> tag contains the numbers. The <td> tag is encapsulated by the <table> tag. Therefore, we have to extract all of the <table> tags, and after that, we extract the <td> tag content for each <tbody> tag. We use looping to extract the data, and we put it to a variable which has a dictionary structure to it, and after that, we write it to CSV file. The code looks like this, If we display the .csv file, it looks like this, After that, we will extract the city regency level dataset. For the dataset, we will scrape from https://covid19.riau.go.id/pantauan_data_kasus. Based on the picture above, we only have to retrieve all of the <tr> tag first. After that, we can retrieve the <td> tag for each of the <tr> tag. The process to become a .csv file is same as the previous one, and the code looks like this, After we run the code, it will create a .csv file, and it appends below the existing line. Here is the preview of the .csv file, After we’ve created the dataset, we can focus on how to update the dataset daily. To achieve this, we can schedule the task using Cron on Linux. In this case, I will use the Raspberry Pi Zero W as my server to scrape the dataset daily, and the operating system that I use is Raspbian. You’ve noticed that I’ve made the script on Windows. Therefore, I’ve made a repository of it on GitHub, so it’s become accessible from any device. If you want to know the code, you can see it on my repository here. I’ve already cloned the repository on my Pi, so we can straight to schedule the task. Before we create the schedule command, we have to make a file with .sh format to put the script that we want to run. The script that I’ve made looks like this, The first line is a shebang declarative that tells the system to use the bash interpreter. The line below is the python script that we want to run. After we make this, we can create our schedule command using Cron. To do this, we can open the terminal first. Then, type crontab -e, and the terminal will open a Nano text editor (you change it if you want to use vim). At first, we will see some note of the crontab file like this, We can write our schedule task below of it. The structure of it looks like this, 59 23 * * * /bin/bash ~/projects/covid-riau-tracker/script.sh Well, it seems weird at first, but let me explain. The first five fields describe the schedule of our task. In order, each of them describes the minute (0–60), the hour (0–24), the day of month (1–31), the month (1–12), and the day of week (1–7). After those fields, we can define the command that we want to run. Because I’ve written the script, we can run it using bash. If you look in detail, I write the absolute path of it. It’s because the Cron doesn’t have the same path as our file. That’s why I write the absolute path to access the file. After we write the task, we can save it by using CTRL + O, and we can exit to the terminal by using CTRL + X. That’s it, we’ve created an automation to the web scraping task. In conclusion, web scraping is a useful method to retrieve the data that we want if it doesn’t exist in friendly-format like .csv format. Also, we can do this without running it by yourself, and let the Cron to do that. Although it is already automated, there is a problem. It’s how to update the dataset, and then push it to GitHub. Until now, I still cannot push the result to the GitHub, and I’m struggling with it. So, if you know how to do that in Cron, leave comments down below. I think that’s what I can share to you right now. I hope that useful to you on how the web scraping is really useful to retrieve the data that we want, and also how to automate it. Thank you.
[ { "code": null, "e": 424, "s": 172, "text": "Sometimes, we want to do some task daily. It seems boring if you do it by yourself, and you waste your time just for doing it. Automation is what we need. By scheduling it at a given time, we can save our time, and let the computer do the task itself." }, { "code": null, "e": 673, "s": 424, "text": "In this article, I want to show you how to build a COVID-19 dataset for Riau Province, Indonesia using Python to retrieve the dataset and also Cron to schedule the task. If you want to know more, you can check about it on my GitHub repository here." }, { "code": null, "e": 859, "s": 673, "text": "Riau is a province in Indonesia. Just like other places, this place also fights COVID-19. They have the source of information which is corona.riau.go.id. The front page looks like this," }, { "code": null, "e": 1054, "s": 859, "text": "On the website, it shows the number of cases that exist at the province and regional level. Although it is up to date, they do not show the historical data of it. Just like these pictures below," }, { "code": null, "e": 1285, "s": 1054, "text": "Because of that problem, I propose a web scraping technique to record the data and save them as .csv format. After this, I will show you step-by-step on how I scrape the website, and how to automate those task at a given schedule." }, { "code": null, "e": 1585, "s": 1285, "text": "The first thing that I do is to scrape the website. To scrape it, I use the bs4 library to extract the text from it. For this case, There are some problems. First, the table that I’ve shown before is from another website, and it’s just a frame at the web. Therefore, we have to get the source of it." }, { "code": null, "e": 1975, "s": 1585, "text": "On Microsoft Edge browser, We can get the source of the frame for each table by right-clicking on it, and select view frame source. For the province-level data, the source comes from https://covid19.riau.go.id/webster. For the city or regency level, the source comes from https://covid19.riau.go.id/pantauan_data_kasus. The next step is to scrape each website to get the data that we need." }, { "code": null, "e": 2269, "s": 1975, "text": "First, we will extract the data from https://covid19.riau.go.id/webster. Retrieving the data is not so difficult because we only have to inspect which tag belongs to the number. The data that we want to extract is just the numbers of each column, so we can make the column’s name using a list." }, { "code": null, "e": 2677, "s": 2269, "text": "Based on the picture above, the <td> tag contains the numbers. The <td> tag is encapsulated by the <table> tag. Therefore, we have to extract all of the <table> tags, and after that, we extract the <td> tag content for each <tbody> tag. We use looping to extract the data, and we put it to a variable which has a dictionary structure to it, and after that, we write it to CSV file. The code looks like this," }, { "code": null, "e": 2726, "s": 2677, "text": "If we display the .csv file, it looks like this," }, { "code": null, "e": 2786, "s": 2726, "text": "After that, we will extract the city regency level dataset." }, { "code": null, "e": 3111, "s": 2786, "text": "For the dataset, we will scrape from https://covid19.riau.go.id/pantauan_data_kasus. Based on the picture above, we only have to retrieve all of the <tr> tag first. After that, we can retrieve the <td> tag for each of the <tr> tag. The process to become a .csv file is same as the previous one, and the code looks like this," }, { "code": null, "e": 3240, "s": 3111, "text": "After we run the code, it will create a .csv file, and it appends below the existing line. Here is the preview of the .csv file," }, { "code": null, "e": 3525, "s": 3240, "text": "After we’ve created the dataset, we can focus on how to update the dataset daily. To achieve this, we can schedule the task using Cron on Linux. In this case, I will use the Raspberry Pi Zero W as my server to scrape the dataset daily, and the operating system that I use is Raspbian." }, { "code": null, "e": 3826, "s": 3525, "text": "You’ve noticed that I’ve made the script on Windows. Therefore, I’ve made a repository of it on GitHub, so it’s become accessible from any device. If you want to know the code, you can see it on my repository here. I’ve already cloned the repository on my Pi, so we can straight to schedule the task." }, { "code": null, "e": 3986, "s": 3826, "text": "Before we create the schedule command, we have to make a file with .sh format to put the script that we want to run. The script that I’ve made looks like this," }, { "code": null, "e": 4201, "s": 3986, "text": "The first line is a shebang declarative that tells the system to use the bash interpreter. The line below is the python script that we want to run. After we make this, we can create our schedule command using Cron." }, { "code": null, "e": 4417, "s": 4201, "text": "To do this, we can open the terminal first. Then, type crontab -e, and the terminal will open a Nano text editor (you change it if you want to use vim). At first, we will see some note of the crontab file like this," }, { "code": null, "e": 4498, "s": 4417, "text": "We can write our schedule task below of it. The structure of it looks like this," }, { "code": null, "e": 4560, "s": 4498, "text": "59 23 * * * /bin/bash ~/projects/covid-riau-tracker/script.sh" }, { "code": null, "e": 4874, "s": 4560, "text": "Well, it seems weird at first, but let me explain. The first five fields describe the schedule of our task. In order, each of them describes the minute (0–60), the hour (0–24), the day of month (1–31), the month (1–12), and the day of week (1–7). After those fields, we can define the command that we want to run." }, { "code": null, "e": 5108, "s": 4874, "text": "Because I’ve written the script, we can run it using bash. If you look in detail, I write the absolute path of it. It’s because the Cron doesn’t have the same path as our file. That’s why I write the absolute path to access the file." }, { "code": null, "e": 5283, "s": 5108, "text": "After we write the task, we can save it by using CTRL + O, and we can exit to the terminal by using CTRL + X. That’s it, we’ve created an automation to the web scraping task." }, { "code": null, "e": 5503, "s": 5283, "text": "In conclusion, web scraping is a useful method to retrieve the data that we want if it doesn’t exist in friendly-format like .csv format. Also, we can do this without running it by yourself, and let the Cron to do that." }, { "code": null, "e": 5769, "s": 5503, "text": "Although it is already automated, there is a problem. It’s how to update the dataset, and then push it to GitHub. Until now, I still cannot push the result to the GitHub, and I’m struggling with it. So, if you know how to do that in Cron, leave comments down below." } ]